Statistics
| Revision:

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

History | View | Annotate | Download (112 KB)

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

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

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

    
83
import org.apache.commons.cli.CommandLine;
84
import org.apache.commons.cli.CommandLineParser;
85
import org.apache.commons.cli.Options;
86
import org.apache.commons.cli.ParseException;
87
import org.apache.commons.cli.PosixParser;
88
import org.apache.commons.io.FileUtils;
89
import org.apache.log4j.AppenderSkeleton;
90
import org.apache.log4j.PatternLayout;
91
import org.apache.log4j.PropertyConfigurator;
92
import org.apache.log4j.RollingFileAppender;
93
import org.apache.log4j.spi.LoggingEvent;
94
import org.apache.log4j.spi.ThrowableInformation;
95
import org.exolab.castor.xml.MarshalException;
96
import org.exolab.castor.xml.ValidationException;
97
import org.slf4j.Logger;
98
import org.slf4j.LoggerFactory;
99
import org.gvsig.andami.actioninfo.ActionInfo;
100
import org.gvsig.andami.actioninfo.ActionInfoManager;
101
import org.gvsig.andami.authentication.IAuthentication;
102
import org.gvsig.andami.config.generate.Andami;
103
import org.gvsig.andami.config.generate.AndamiConfig;
104
import org.gvsig.andami.config.generate.Plugin;
105
import org.gvsig.andami.messages.Messages;
106
import org.gvsig.andami.messages.NotificationManager;
107
import org.gvsig.andami.persistence.serverData.ServerDataPersistence;
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
                                ServerDataPersistence.registerPersistence();
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.info("Initializing plugins libraries: ");
679
                while (iter.hasNext()) {
680
                        String pName = (String) iter.next();
681
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
682
                        logger.info("Initializing plugin libraries (" + pName + ")");
683
                        classLoaders.add(ps.getClassLoader());
684
                }
685

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

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

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

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

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

    
717
                getOrCreateConfigFolder();
718

    
719
                configureLogging(appName);
720

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

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

    
732
                configureLocales(args);
733

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

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

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

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

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

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

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

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

    
814
        private class NotificationAppender extends AppenderSkeleton {
815

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

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

    
841
                }
842

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

    
849
        }
850

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1093
                XMLEntity entity = new XMLEntity();
1094

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

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

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

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

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

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

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

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

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

    
1166
                Class<? extends IExtension> skinClass;
1167

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

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

    
1197
        }
1198

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

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

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

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

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

    
1260
        }
1261

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

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

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

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

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

    
1292
        private void initializeExtensions() {
1293

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1570
                }
1571
        }
1572
        
1573

    
1574
        private TreeSet<SortableMenu> getOrderedMenus() { 
1575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1642
                }
1643

    
1644
                return orderedMenus;
1645
        }
1646

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2495
        }
2496

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2593
                return null;
2594
        }
2595

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

    
2600
        private static class ExtensionComparator implements Comparator {
2601

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

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

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

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

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

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

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

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

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

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

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

    
2663
        private static class SortableMenu {
2664

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

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

    
2678
        private static class SortableTool {
2679

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2861
                return UIManager.getSystemLookAndFeelClassName();
2862
        }
2863

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3206
                        System.exit(0);
3207
                }
3208

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

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

    
3247
                /**
3248
                 * Exectutes the terminate method for all the extensions, in the reverse
3249
                 * order they were initialized
3250
                 * 
3251
                 */
3252
                private void finalizeExtensions() {
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
                                String extensionName = "(unknow)";
3257
                                try {
3258
                                        extensionName = extensionInstance.getClass().getName();
3259
                                        extensionInstance.terminate();
3260
                                } catch (Exception ex) {
3261
                                        logger.error(MessageFormat.format(
3262
                                                        "There was an error extension ending {0}",
3263
                                                        extensionName), ex);
3264
                                }
3265
                        }
3266
                }
3267

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

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

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

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

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

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

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

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

    
3346
                                }
3347

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

    
3352
                                }
3353

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

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

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

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

    
3411
        }
3412

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3588

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

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

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

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

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

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

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

    
3617
                StringWriter writer = new StringWriter();
3618

    
3619
                Properties props = System.getProperties();
3620

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

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

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

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

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

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

    
3713
}