Statistics
| Revision:

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

History | View | Annotate | Download (118 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.awt.Window;
35
import java.awt.event.ActionEvent;
36
import java.awt.event.ActionListener;
37
import java.io.BufferedOutputStream;
38
import java.io.BufferedReader;
39
import java.io.File;
40
import java.io.FileFilter;
41
import java.io.FileInputStream;
42
import java.io.FileNotFoundException;
43
import java.io.FileOutputStream;
44
import java.io.FileReader;
45
import java.io.IOException;
46
import java.io.InputStream;
47
import java.io.InputStreamReader;
48
import java.io.OutputStreamWriter;
49
import java.io.Reader;
50
import java.io.StringWriter;
51
import java.net.Authenticator;
52
import java.net.MalformedURLException;
53
import java.net.PasswordAuthentication;
54
import java.net.URL;
55
import java.net.URLClassLoader;
56
import java.nio.channels.FileChannel;
57
import java.security.AllPermission;
58
import java.security.CodeSource;
59
import java.security.PermissionCollection;
60
import java.security.Permissions;
61
import java.security.Policy;
62
import java.text.MessageFormat;
63
import java.util.ArrayList;
64
import java.util.Comparator;
65
import java.util.Enumeration;
66
import java.util.HashMap;
67
import java.util.HashSet;
68
import java.util.Iterator;
69
import java.util.List;
70
import java.util.Locale;
71
import java.util.Map;
72
import java.util.Map.Entry;
73
import java.util.Properties;
74
import java.util.Set;
75
import java.util.TreeSet;
76
import java.util.prefs.Preferences;
77

    
78
import javax.swing.ImageIcon;
79
import javax.swing.JButton;
80
import javax.swing.JComponent;
81
import javax.swing.JDialog;
82
import javax.swing.JFrame;
83
import javax.swing.JOptionPane;
84
import javax.swing.JPopupMenu;
85
import javax.swing.ListSelectionModel;
86
import javax.swing.SwingUtilities;
87
import javax.swing.UIManager;
88

    
89
import org.apache.commons.cli.CommandLine;
90
import org.apache.commons.cli.CommandLineParser;
91
import org.apache.commons.cli.Options;
92
import org.apache.commons.cli.ParseException;
93
import org.apache.commons.cli.PosixParser;
94
import org.apache.commons.io.FileUtils;
95
import org.apache.log4j.AppenderSkeleton;
96
import org.apache.log4j.PatternLayout;
97
import org.apache.log4j.PropertyConfigurator;
98
import org.apache.log4j.RollingFileAppender;
99
import org.apache.log4j.spi.LoggingEvent;
100
import org.apache.log4j.spi.ThrowableInformation;
101
import org.exolab.castor.xml.MarshalException;
102
import org.exolab.castor.xml.ValidationException;
103
import org.gvsig.andami.actioninfo.ActionInfo;
104
import org.gvsig.andami.actioninfo.ActionInfoManager;
105
import org.gvsig.andami.authentication.IAuthentication;
106
import org.gvsig.andami.config.generate.Andami;
107
import org.gvsig.andami.config.generate.AndamiConfig;
108
import org.gvsig.andami.config.generate.Plugin;
109
import org.gvsig.andami.messages.Messages;
110
import org.gvsig.andami.messages.NotificationManager;
111
import org.gvsig.andami.persistence.serverData.ServerDataPersistence;
112
import org.gvsig.andami.plugins.ExclusiveUIExtension;
113
import org.gvsig.andami.plugins.ExtensionDecorator;
114
import org.gvsig.andami.plugins.IExtension;
115
import org.gvsig.andami.plugins.PluginClassLoader;
116
import org.gvsig.andami.plugins.config.generate.Action;
117
import org.gvsig.andami.plugins.config.generate.ActionTool;
118
import org.gvsig.andami.plugins.config.generate.AlternativeNames;
119
import org.gvsig.andami.plugins.config.generate.ComboButton;
120
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
121
import org.gvsig.andami.plugins.config.generate.ComboScale;
122
import org.gvsig.andami.plugins.config.generate.Depends;
123
import org.gvsig.andami.plugins.config.generate.Extension;
124
import org.gvsig.andami.plugins.config.generate.Extensions;
125
import org.gvsig.andami.plugins.config.generate.LabelSet;
126
import org.gvsig.andami.plugins.config.generate.Menu;
127
import org.gvsig.andami.plugins.config.generate.PluginConfig;
128
import org.gvsig.andami.plugins.config.generate.PopupMenu;
129
import org.gvsig.andami.plugins.config.generate.PopupMenus;
130
import org.gvsig.andami.plugins.config.generate.SelectableTool;
131
import org.gvsig.andami.plugins.config.generate.SkinExtension;
132
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
133
import org.gvsig.andami.plugins.config.generate.ToolBar;
134
import org.gvsig.andami.plugins.status.IExtensionStatus;
135
import org.gvsig.andami.plugins.status.IUnsavedData;
136
import org.gvsig.andami.ui.AndamiEventQueue;
137
import org.gvsig.andami.ui.DisablePluginsConflictingLayoutPanel;
138
import org.gvsig.andami.ui.MDIManagerLoadException;
139
import org.gvsig.andami.ui.ToolsWindowManager;
140
import org.gvsig.andami.ui.fonts.FontUtils;
141
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
142
import org.gvsig.andami.ui.mdiFrame.MainFrame;
143
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
144
import org.gvsig.andami.ui.splash.MultiSplashWindow;
145
import org.gvsig.andami.ui.theme.Theme;
146
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
147
import org.gvsig.installer.lib.api.Dependencies;
148
import org.gvsig.installer.lib.api.Dependency;
149
import org.gvsig.installer.lib.api.InstallerLocator;
150
import org.gvsig.installer.lib.api.InstallerManager;
151
import org.gvsig.installer.lib.api.PackageInfo;
152
import org.gvsig.installer.lib.api.creation.MakePluginPackageServiceException;
153
import org.gvsig.installer.swing.api.SwingInstallerLocator;
154
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
155
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
156
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
157
import org.gvsig.tools.exception.ListBaseException;
158
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
159
import org.gvsig.tools.swing.api.ToolsSwingLocator;
160
import org.gvsig.tools.swing.icontheme.IconTheme;
161
import org.gvsig.tools.swing.icontheme.IconThemeManager;
162
import org.gvsig.tools.util.FolderSet;
163
import org.gvsig.tools.util.FolderSet.FolderEntry;
164
import org.gvsig.utils.DateTime;
165
import org.gvsig.utils.DefaultListModel;
166
import org.gvsig.utils.XMLEntity;
167
import org.gvsig.utils.xml.XMLEncodingUtils;
168
import org.gvsig.utils.xmlEntity.generate.XmlTag;
169
import org.slf4j.Logger;
170
import org.slf4j.LoggerFactory;
171

    
172
/**
173
 * <p>
174
 * Andami's launching class. This is the class used to create the Andami's
175
 * plugin environment.<br>
176
 * </p>
177
 * 
178
 * <p>
179
 * <b>Syntax:</b> <br>
180
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or
181
 * semicolon-separated(windows) list of files containg base library of classes}]
182
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
183
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
184
 * [{list of additional custom application arguments separated by spaces}]
185
 * </p>
186
 * 
187
 * 
188
 * @author $author$
189
 * @version $Revision: 40305 $
190
 */
191
public class Launcher {
192

    
193
        public static abstract class MapWithAlias<Item> extends HashMap<String, Item> {
194
                private HashMap<String, String> aliases = new HashMap<String, String>();  
195
                
196
                public abstract String[] getAliases(Item item);
197
                
198
                public Item get(Object key) {
199
                        Item item = super.get(key);
200
                        if( item != null ) {
201
                                return item;
202
                        }
203
                        String alias = aliases.get(key);
204
                        if( alias != null ) {
205
                                return super.get(alias);
206
                        }
207
                        return null;
208
                }
209
                
210
                public boolean containsKey(Object key) {
211
                        boolean contains = super.containsKey(key);
212
                        if( contains ) {
213
                                return true;
214
                        }
215
                        String alias = aliases.get(key);
216
                        return super.containsKey(alias);
217
                }
218
                
219
                public Item put(String key, Item value) {
220
                        super.put(key, value);
221
                        String[] aliases = getAliases(value);
222
                        if( aliases==null ) {
223
                                return value;
224
                        }
225
                        for( int n=0; n<aliases.length; n++ ) {
226
                                this.aliases.put(aliases[n].trim(), key);
227
                        }
228
                        return value;
229
                }
230
                
231
                public void putAll(Map<? extends String, ? extends Item> m) {
232
                        Iterator<?> it = m.entrySet().iterator();
233
                        while( it.hasNext() ) {
234
                                Map.Entry<String, Item> x = (Map.Entry<String, Item>) it.next();
235
                                this.put(x.getKey(), x.getValue());
236
                        }
237
                }
238
                
239
                public Item remove(Object key) {
240
                        Item item = super.get(key);
241
                        if( item == null ) {
242
                                String alias = aliases.get(key);
243
                                if( alias == null ) {
244
                                        return null;
245
                                }
246
                                item = super.get(alias);
247
                                super.remove(alias);
248
                        } else {
249
                                super.remove(key);
250
                        }
251
                        String[] aliases = getAliases(item);
252
                        if( aliases==null ) {
253
                                return item;
254
                        }
255
                        // Rebuild the alias list
256
                        this.aliases = new HashMap<String, String>();  
257
                        Iterator<java.util.Map.Entry<String, Item>> it = this.entrySet().iterator();
258
                        while(it.hasNext()) {
259
                                java.util.Map.Entry<String, Item> entry = it.next();
260
                                aliases = getAliases(entry.getValue());
261
                                if( aliases==null ) {
262
                                        continue;
263
                                }
264
                                for( int n=0; n<aliases.length; n++ ) {
265
                                        this.aliases.put(aliases[n].trim(), entry.getKey());
266
                                }
267
                        }
268

    
269
                        return item;
270
                }
271
                
272
        }
273
        
274
        public static class PluginsConfig extends MapWithAlias<org.gvsig.andami.plugins.config.generate.PluginConfig>  {
275
                
276
                public String[] getAliases(
277
                                org.gvsig.andami.plugins.config.generate.PluginConfig item) {
278
                        return getAlternativeNames(item);
279
                }
280

    
281
                static String[] getAlternativeNames(org.gvsig.andami.plugins.config.generate.PluginConfig item) {
282
                        AlternativeNames[] x = item.getAlternativeNames();
283
                        if( x == null ) {
284
                                return null;
285
                        }
286
                        String[] r = new String[x.length];
287
                        for( int i=0; i<x.length; i++) {
288
                                r[i] = x[i].getName();
289
                        }
290
                        return r;
291
                }
292
                
293
        }
294
        
295
        public static class PluginsServices extends MapWithAlias<org.gvsig.andami.PluginServices>  {
296

    
297
                public String[] getAliases(org.gvsig.andami.PluginServices item) {
298
                        return item.getAlternativeNames();
299
                }
300
        }
301
        
302
        protected static Logger logger = LoggerFactory.getLogger(Launcher.class
303
                        .getName());
304
        protected static Preferences prefs = Preferences.userRoot().node(
305
                        "gvsig.connection");
306
        protected static AndamiConfig andamiConfig;
307
        protected static MultiSplashWindow splashWindow;
308
        protected static String appName;
309
        protected static Locale locale;
310
        protected static PluginsConfig pluginsConfig = new PluginsConfig();
311
        protected static PluginsServices pluginsServices = new PluginsServices();
312
        protected static MDIFrame frame;
313
        protected static HashMap<Class<? extends IExtension>, ExtensionDecorator> classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
314
        protected static String andamiConfigPath;
315
        protected static final String nonWinDefaultLookAndFeel = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
316

    
317
        protected static ArrayList<String> pluginsOrdered = new ArrayList<String>();
318
        protected static ArrayList<IExtension> extensions = new ArrayList<IExtension>();
319
        protected static String appHomeDir = null;
320
        // it seems castor uses this encoding
321
        protected static final String CASTORENCODING = "UTF8";
322

    
323
        protected static ListBaseException launcherrors = null;
324

    
325
        protected static Theme theme = null;
326

    
327
        private static final class ProxyAuth extends Authenticator {
328

    
329
                private PasswordAuthentication auth;
330

    
331
                private ProxyAuth(String user, String pass) {
332
                        auth = new PasswordAuthentication(user, pass.toCharArray());
333
                }
334

    
335
                protected PasswordAuthentication getPasswordAuthentication() {
336
                        return auth;
337
                }
338
        }
339

    
340
        private static Launcher launcherInstance;
341

    
342
        public static Launcher getInstance() {
343
                if( launcherInstance == null ) {
344
                        launcherInstance = new Launcher();
345
                }
346
                return launcherInstance;
347
        }
348
        
349
        public static void main(String[] args) throws Exception {
350
                Launcher launcher = getInstance();
351
                boolean install = false;
352
                for (int i = 0; i < args.length; i++) {
353
                        if (args[i].equalsIgnoreCase("--install")) {
354
                                install = true;
355
                        }
356
                }
357
                try {
358
                        if (install) {
359
                                launcher.doInstall(args);
360
                        } else {
361
                                launcher.doMain(args);
362
                        }
363
                } catch (Exception e) {
364
                        logger.error("excepci?n al arrancar", e);
365
                        System.exit(-1);
366
                }
367
        }
368

    
369
        protected void downloadExtensions(String extDir) {
370
                // do nothing
371
        }
372

    
373
        public static class LaunchException extends ListBaseException {
374

    
375
                private static final long serialVersionUID = 4541192746962684705L;
376

    
377
                public LaunchException() {
378
                        super("Errors in initialization of application.",
379
                                        "_errors_in_initialization_of_application",
380
                                        serialVersionUID);
381
                }
382

    
383
        }
384

    
385
        protected void addError(Throwable ex) {
386
                if (launcherrors == null) {
387
                        launcherrors = new LaunchException();
388
                }
389
                launcherrors.add(ex);
390
        }
391

    
392
        protected void addError(String msg, Throwable cause) {
393
                logger.error(msg, cause);
394
                this.addError(new RuntimeException(msg, cause));
395
        }
396

    
397
        protected void addError(String msg) {
398
                this.addError(msg, null);
399
        }
400

    
401
        private String translate(String msg) {
402
                return PluginServices.getText(Launcher.class,msg);
403
        }
404
        
405
        public void doMain(String[] args) throws Exception {
406

    
407
                if (args.length < 1) {
408
                        System.err.println("Usage: Launcher appName plugins-directory [language=locale]");
409
                        System.err.println("No arguments specified.");
410
                        System.err.println("Use default arguments 'gvSIG gvSIG/extensiones'");
411
                        args = new String[] { "gvSIG", "gvSIG/extensiones" };
412
                }
413

    
414
                initializeApp(args);
415

    
416
                // Solucionamos el problema de permisos que se produc?do con Java
417
                // Web Start con este codigo.
418
                // System.setSecurityManager(null);
419
                Policy.setPolicy(new Policy() {
420

    
421
                        public PermissionCollection getPermissions(CodeSource codesource) {
422
                                Permissions perms = new Permissions();
423
                                perms.add(new AllPermission());
424
                                return (perms);
425
                        }
426

    
427
                        public void refresh() {
428
                        }
429
                });
430
        
431
        new DefaultLibrariesInitializer().fullInitialize(true);
432
        InstallerLocator.getInstallerManager().setDownloadBaseURL(
433
            new URL("http://downloads.gvsig.org/download/gvsig-desktop/"));
434

    
435
                try {
436
                        initIconThemes();
437
                } catch (Exception ex) {
438
                        this.addError("Can't initialize icon theme", ex);
439
                }
440
                // Registramos los iconos base
441
                try {
442
                        registerIcons();
443
                } catch (Exception ex) {
444
                        this.addError("Can't register icons", ex);
445
                }
446
                validate();
447

    
448
                // Obtener la personalizaci?n de la aplicacion.
449
                try {
450
                        logger.info("Initialize andami theme");
451
                        theme = getTheme(andamiConfig.getPluginsDirectory());
452
                } catch (Exception ex) {
453
                        this.addError("Can't get personalized theme for the application",
454
                                        ex);
455
                }
456

    
457
                // Mostrar la ventana de inicio
458
                Frame f = new Frame();
459
                splashWindow = new MultiSplashWindow(f, theme, 27);
460

    
461
                // Ponemos los datos del proxy
462
                splashWindow.process(translate("SplashWindow.configuring_proxy"));
463
                logger.info("Configute http proxy");
464
                configureProxy();
465

    
466
                // Buscar actualizaciones de los plugins
467
                splashWindow.process(translate("SplashWindow.looking_for_updates"));
468
                try {
469
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
470
                } catch (Exception ex) {
471
                        this.addError("Can't downloads plugins", ex);
472
                }
473

    
474
                // Initialize andami libraries
475
                splashWindow.process(translate("SplashWindow.initialize_install_manager"));
476
                
477
                File defaultAddonsRepository = PluginsLocator.getManager()
478
                                .getPluginsFolder();
479
                InstallerManager installerManager = InstallerLocator
480
                                .getInstallerManager();
481
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
482
                installerManager
483
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
484

    
485
                splashWindow.process(translate("SplashWindow.initialize_list_of_addons_installeds"));
486
                // ---------------------------------------------
487
                // Get the list of installed packages
488
                PluginsManager pluginmgr = PluginsLocator.getManager();
489
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
490

    
491
                PackageInfo[] installedPackages = null;
492
                try {
493
                        installedPackages = installmgr.getInstalledPackages(pluginmgr
494
                                        .getPluginsFolder());
495
                } catch (MakePluginPackageServiceException e) {
496
                        // Do nothing, ignore errors
497
                }
498

    
499
                splashWindow.process(translate("SplashWindow.Dump_system_information"));
500
                logger.info("Dump system information");
501
                logger_info(getInformation(installedPackages));
502
                saveEnvironInformation(installedPackages);
503

    
504
                // Se leen los config.xml de los plugins
505
                splashWindow.process(translate("SplashWindow.load_plugins_configuration"));
506
                try {
507
                        logger.info("Load plugins information");
508
                        this.loadPlugins(andamiConfig.getPluginsDirectory());
509
                } catch (Exception ex) {
510
                        this.addError("Can't load plugins", ex);
511
                }
512

    
513
                splashWindow.process(translate("SplashWindow.check_incompatible_plugins"));
514
                fixIncompatiblePlugins(installedPackages);
515
                
516
                // Se configura el classloader del plugin
517
                splashWindow.process(translate("SplashWindow.setup_plugins_configuration"));
518
                try {
519
                        logger.info("Configure plugins class loader");
520
                        this.pluginsClassLoaders();
521
                } catch (Exception ex) {
522
                        this.addError("Can't initialize plugin's classloaders  ", ex);
523
                }
524

    
525
                // Initialize libraries
526
                splashWindow.process(translate("SplashWindow.initialize_plugins_libraries"));
527
                initializeLibraries();
528

    
529
                // Se carga un Skin si alguno ide los plugins trae informacion para ello
530
                splashWindow.process(translate("SplashWindow.looking_for_a_skin"));
531
                logger.info("Initialize skin");
532
                skinPlugin(null);
533

    
534
                // Se configura la cola de eventos
535
                splashWindow.process(translate("setting_up_event_queue"));
536
                EventQueue waitQueue = new AndamiEventQueue();
537
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
538

    
539
                // Se configura la internacionalizacion del plugin
540
                splashWindow.process(translate("SplashWindow.starting_plugin_internationalization_system"));
541
                pluginsMessages();
542

    
543
                // Se modifica el andami-config con los plugins nuevos
544
                splashWindow.process(translate("SplashWindow.update_framework_configuration"));
545
                updateAndamiConfig();
546

    
547
                frame = new MDIFrame();
548
                // Se configura el nombre e icono de la aplicacion
549
                splashWindow.process(translate("SplashWindow.setting_up_applications_name_and_icons"));
550
                frameIcon(theme);
551

    
552
                // Se prepara el MainFrame para albergar las extensiones
553
                splashWindow.process(translate("SplashWindow.preparing_workbench"));
554
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
555
                SwingUtilities.invokeAndWait(new Runnable() {
556
                        public void run() {
557
                                frame.init();
558
                        }
559
                });
560
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
561

    
562
                // Leer el fichero de persistencia de los plugins
563
                splashWindow.process(translate("SplashWindow.loading_plugin_settings"));
564
                loadPluginsPersistence();
565

    
566
                // Se instalan los controles del skin
567
                // Se inicializan todas las extensiones de todos los plugins
568
                splashWindow.process(translate("SplashWindow.initializing_extensions"));
569
                SwingUtilities.invokeAndWait(new Runnable() {
570
                        public void run() {
571
                                initializeExtensions();
572
                        }
573
                });
574

    
575
                // Se inicializan la extension exclusiva
576
                splashWindow.process(translate("SplashWindow.setting_up_master_extension"));
577
                SwingUtilities.invokeAndWait(new Runnable() {
578
                        public void run() {
579
                                initializeExclusiveUIExtension();
580
                        }
581
                });
582
                frame.setClassesExtensions(classesExtensions);
583

    
584
                // Se instalan los controles de las extensiones de los plugins
585
                splashWindow.process(translate("SplashWindow.installing_extensions_controls"));
586
                SwingUtilities.invokeAndWait(new Runnable() {
587
                        public void run() {
588
                                installPluginsControls();
589
                        }
590
                });
591

    
592
                // Se instalan los menus de las extensiones de los plugins
593
                splashWindow.process(translate("SplashWindow.installing_extensions_menus"));
594
                SwingUtilities.invokeAndWait(new Runnable() {
595
                        public void run() {
596
                                installPluginsMenus();
597
                        }
598
                });
599

    
600
                // Se instalan las etiquetas de las extensiones de los plugins
601
                splashWindow.process(translate("SplashWindow.installing_extensions_labels"));
602
                SwingUtilities.invokeAndWait(new Runnable() {
603
                        public void run() {
604
                                installPluginsLabels();
605
                        }
606
                });
607

    
608
                // Se muestra el frame principal
609
                splashWindow.process(translate("creating_main_window"));
610
                frame.setVisible(true);
611

    
612
                /* 
613
                 * Initialize local repository folders of the installer 
614
                 */
615
                splashWindow.process(translate("SplashWindow.initializing_local_addon_repository_folders"));
616
                initializeLocalAddOnRepositoryFolders();
617

    
618
                // Se ejecuta el postInitialize
619
                splashWindow.process(translate("SplashWindow.post_initializing_extensions"));
620
                SwingUtilities.invokeAndWait(new Runnable() {
621
                        public void run() {
622
                                postInitializeExtensions();
623
                        }
624
                });
625

    
626
                splashWindow.process(translate("SplashWindow.initializing_server_data_persistence"));
627
                ServerDataPersistence.registerPersistence();
628

    
629
                // Definimos un KeyEventDispatcher global para que las extensiones
630
                // puedan registrar sus "teclas rapidas".
631
                splashWindow.process(translate("SplashWindow.initializing_accelerator_keys"));
632
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
633
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
634

    
635
                splashWindow.process(translate("SplashWindow.enable_controls"));
636
                SwingUtilities.invokeAndWait(new Runnable() {
637
                        public void run() {
638
                                frame.enableControls();
639
                        }
640
                });
641

    
642
                frame.message(translate("StatusBar.Aplicacion_iniciada"), JOptionPane.INFORMATION_MESSAGE);
643

    
644
                splashWindow.close();
645
                
646
                if (launcherrors != null) {
647
                        NotificationManager.addError(launcherrors);
648
                }
649
                org.apache.log4j.Logger.getRootLogger().addAppender(
650
                                new NotificationAppender());
651

    
652
        }
653

    
654
        private void initializeLocalAddOnRepositoryFolders() {
655
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
656

    
657
                File defaultAddonsRepository = PluginsLocator.getManager().getPluginsFolder();
658

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

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

    
682
                logger.info("Initializing plugins libraries: ");
683
                while (iter.hasNext()) {
684
                        String pName = (String) iter.next();
685
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
686
                        logger.info("Initializing plugin libraries (" + pName + ")");
687
                        classLoaders.add(ps.getClassLoader());
688
                }
689

    
690
                // Create the libraries initializer and
691
                // initialize the plugin libraries
692
                new DefaultLibrariesInitializer(classLoaders
693
                                .toArray(new ClassLoader[classLoaders.size()]))
694
                                .fullInitialize(true);
695

    
696
                // Remove them all, we don't need them anymore
697
                classLoaders.clear();
698
                classLoaders = null;
699
        }
700

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

    
712
                // Clean temporal files
713
                Utilities.cleanUpTempFiles();
714

    
715
                if( args.length<1 ) {
716
                        appName = "gvSIG"; // Nombre de aplicacion por defecto es "gvSIG"
717
                } else {
718
                        appName = args[0];
719
                }
720

    
721
                getOrCreateConfigFolder();
722

    
723
                configureLogging(appName);
724

    
725
                if( args.length<2 ) {
726
                        loadAndamiConfig("gvSIG/extensiones"); // Valor por defecto 
727
                } else {
728
                        loadAndamiConfig(args[1]);
729
                }
730

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

    
736
                configureLocales(args);
737

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

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

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

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

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

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

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

    
812
        private class NotificationAppender extends AppenderSkeleton {
813

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

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

    
839
                }
840

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

    
847
        }
848

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1091
                XMLEntity entity = new XMLEntity();
1092

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

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

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

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

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

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

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

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

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

    
1164
                Class<? extends IExtension> skinClass;
1165

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

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

    
1195
        }
1196

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

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

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

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

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

    
1258
        }
1259

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

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

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

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

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

    
1290
        private void initializeExtensions() {
1291

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1568
                }
1569
        }
1570
        
1571

    
1572
        private TreeSet<SortableMenu> getOrderedMenus() { 
1573

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1640
                }
1641

    
1642
                return orderedMenus;
1643
        }
1644

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2493
        }
2494

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2591
                return null;
2592
        }
2593

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

    
2598
        private static class ExtensionComparator implements Comparator {
2599

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

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

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

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

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

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

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

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

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

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

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

    
2661
        private static class SortableMenu {
2662

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

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

    
2676
        private static class SortableTool {
2677

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2859
                return UIManager.getSystemLookAndFeelClassName();
2860
        }
2861

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

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

    
2917
        /**
2918
         * Configures the locales (languages and local resources) to be used by the
2919
         * application.
2920
         * 
2921
         * First it tries to get the locale from the command line parameters, then
2922
         * the andami-config file is checked.
2923
         * 
2924
         * The locale name is normalized to get a two characters language code as
2925
         * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
2926
         * also accepted from the command line or the configuration file).
2927
         * 
2928
         * Finally, the gvsig-i18n library and the default locales for Java and
2929
         * Swing are configured.
2930
         * 
2931
         */
2932
        private static void configureLocales(String[] args) {
2933
                // Configurar el locale
2934
                String localeStr = null;
2935

    
2936
                localeStr = PluginServices.getArgumentByName("language");
2937
                if (localeStr == null) {
2938
                        localeStr = andamiConfig.getLocaleLanguage();
2939
                }
2940
                localeStr = normalizeLanguageCode(localeStr);
2941
                locale = getLocale(localeStr, andamiConfig.getLocaleCountry(),
2942
                                andamiConfig.getLocaleVariant());
2943
                Locale.setDefault(locale);
2944
                JComponent.setDefaultLocale(locale);
2945
                org.gvsig.i18n.Messages.addLocale(locale);
2946
                // add english and spanish as fallback languages
2947
                if (localeStr.equals("es") || localeStr.equals("ca")
2948
                                || localeStr.equals("gl") || localeStr.equals("eu")
2949
                                || localeStr.equals("va")) {
2950
                        // prefer Spanish for languages spoken in Spain
2951
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2952
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2953
                } else {
2954
                        // prefer English for the rest
2955
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2956
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2957
                }
2958

    
2959
        // Create classloader for the i18n resources in the
2960
        // andami and user i18n folder. Those values will have
2961
        // precedence over any other values added afterwards
2962
        File andamiI18nFolder =
2963
            new File(System.getProperty("user.dir"), "i18n");
2964
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2965
        if( !userI18nFolder.exists() ) {
2966
                try {
2967
                                FileUtils.forceMkdir(userI18nFolder);
2968
                        } catch (IOException e) {
2969
                                logger.info("Can't create i18n folder in gvSIG home ("+userI18nFolder+").",e);
2970
                        }
2971
        }
2972

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3207
                        System.exit(0);
3208
                }
3209

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

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

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

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

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

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

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

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

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

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

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

    
3347
                                }
3348

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

    
3353
                                }
3354

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

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

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

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

    
3412
        }
3413

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

    
3418
        private PackageInfo getPackageInfo(String pluginsFolder) {
3419
                try {
3420
                    PluginsManager pm = PluginsLocator.getManager();
3421
                    return pm.getPackageInfo();
3422
                } catch (Exception e) {
3423
                        logger.info("Can't locate PackageInfo from plugin org.gvsig.app",e);
3424
                        return null;
3425
                }
3426
        }
3427

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

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

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

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

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

    
3548
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3549

    
3550
                // Launch installer
3551
                PluginsManager manager = PluginsLocator.getManager();
3552

    
3553
                File defaultAddonsRepository = PluginsLocator.getManager()
3554
                                .getPluginsFolder();
3555
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3556
                installerManager
3557
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3558

    
3559
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3560
                                .getSwingInstallerManager().createInstallPackageWizard(
3561
                                                manager.getApplicationFolder(),
3562
                                                manager.getInstallFolder());
3563
                installPackageWizard
3564
                                .setWizardActionListener(new InstallerWizardActionListener() {
3565

    
3566
                                        public void finish(InstallerWizardPanel installerWizard) {
3567
                                                System.exit(0);
3568
                                        }
3569

    
3570
                                        public void cancel(InstallerWizardPanel installerWizard) {
3571
                                                System.exit(0);
3572
                                        }
3573
                                });
3574

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

    
3580

    
3581
                // 1. Create the frame.
3582
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3583

    
3584
                // 2. What happens when the frame closes?
3585
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3586
                Runtime.getRuntime().addShutdownHook(new Thread() {
3587

    
3588
                        @Override
3589
                        public void run() {
3590
                                getTerminationProcess().saveAndamiConfig();
3591
                        }
3592
                });
3593

    
3594
                // 3. Add the installer panel to the frame
3595
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3596

    
3597
                // 4. Size the frame and center on the screen
3598
                frame.pack();
3599
                frame.setLocationRelativeTo(null);
3600

    
3601
                // 5. Show it.
3602
                frame.setVisible(true);
3603
        }
3604

    
3605
        public static String getInformation() {
3606
                return getInformation(null);
3607
        }
3608
        
3609
        public static String getInformation(PackageInfo[] pkgs) {
3610
                PluginsManager pluginmgr = PluginsLocator.getManager();
3611

    
3612
                StringWriter writer = new StringWriter();
3613

    
3614
                Properties props = System.getProperties();
3615

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

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

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

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

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

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

    
3711
        private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3712
                final Set<String> incompatiblePlugins = new HashSet<String>();
3713
                
3714
                // Add installed packages to a Map to optimize searchs
3715
                final Map<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
3716
                for( int i=0 ; i<installedPackages.length; i++) {
3717
                        packages.put(installedPackages[i].getCode(), installedPackages[i]);
3718
                }
3719
                Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
3720
                while( it.hasNext() ) {
3721
                        List<String> pluginNames = new ArrayList<String>();
3722
                        Entry<String, PluginConfig> entry = it.next();
3723
                        PluginConfig pluginConfig = entry.getValue();
3724
                        pluginNames.add(entry.getKey());
3725
                        
3726
                        // Locate the package for this plugin.
3727
                        // Be care whith alias
3728
                        String[] aliases = pluginsConfig.getAliases(pluginConfig);
3729
                        if( aliases!=null ) {
3730
                                for( int i=0; i<aliases.length; i++ ) {
3731
                                        pluginNames.add(aliases[i]);
3732
                                }
3733
                        }
3734
                        PackageInfo pkg = null;
3735
                        for( int n=0; n<pluginNames.size(); n++ ) {
3736
                                pkg = packages.get(pluginNames.get(n));
3737
                                if( pkg != null ) {
3738
                                        break;
3739
                                }
3740
                        }
3741
                
3742
                        // If package is found verify dependencies
3743
                        if( pkg!= null ) {
3744
                                Dependencies dependencies = pkg.getDependencies();
3745
                                for( int i=0 ; i<dependencies.size(); i++ ) {
3746
                                        Dependency dependency = (Dependency) dependencies.get(i);
3747
                                        if( Dependency.CONFLICT.equalsIgnoreCase(dependency.getType())  ) {
3748
                                                String code = dependency.getCode();
3749
                                                if( pluginsConfig.get(code)!=null ) {
3750
                                                        incompatiblePlugins.add(pkg.getCode());
3751
                                                        incompatiblePlugins.add(code);
3752
                                                }
3753
                                        }
3754
                                }
3755
                        }
3756
                }
3757
                if( incompatiblePlugins.isEmpty() ) {
3758
                        return;
3759
                }
3760
                splashWindow.toBack();
3761
                DisablePluginsConflictingDialog dlg = new DisablePluginsConflictingDialog(packages, incompatiblePlugins);
3762
//                dlg.setAlwaysOnTop(true);
3763
                dlg.setVisible(true);
3764
                splashWindow.toFront();
3765
                switch(dlg.getAction()) {
3766
                case DisablePluginsConflictingDialog.CLOSE:
3767
                        System.exit(0);
3768
                        break;
3769
                case DisablePluginsConflictingDialog.CONTINUE:
3770
                        break;
3771
                }
3772
                List<String> pluginsToDesable = dlg.getPluginNamesToDisable();
3773
                if( pluginsToDesable  == null ) {
3774
                        return;
3775
                }
3776
                PluginConfig x = pluginsConfig.get("org.gvsig.projection.app.mainplugin");
3777
                
3778
                Iterator<String> it2 = pluginsToDesable.iterator();
3779
                while( it2.hasNext() ) {
3780
                        String pluginName = it2.next();
3781
                        logger.info("Disabling plugin '"+pluginName+"' by user action.");
3782
                        pluginsConfig.remove(pluginName);
3783
                }
3784
                PluginConfig y = pluginsConfig.get("org.gvsig.projection.app.mainplugin");
3785
                
3786
        }
3787
        
3788
        private class DisablePluginsConflictingDialog extends JDialog {
3789
        
3790
                public static final int CONTINUE = 0;
3791
                public static final int CLOSE = 1;
3792
                
3793
                private DisablePluginsConflictingLayoutPanel contents;
3794
                private int action = 0;
3795
                private List<Item> incompatiblePlugins = null;
3796
                private Map<String, PackageInfo> packages;
3797
                
3798
                private class Item {
3799
                        private String code;
3800
                        private PackageInfo pkg;
3801

    
3802
                        public Item(String code, PackageInfo pkg) {
3803
                                this.code = code;
3804
                                this.pkg = pkg;
3805
                        }
3806
                        public String toString() {
3807
                                if( this.pkg == null ) {
3808
                                        return code;
3809
                                }
3810
                                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
3811
                        }
3812
                        public String getCode() {
3813
                                if( pkg == null ) {
3814
                                        return code;
3815
                                }
3816
                                return pkg.getCode();
3817
                        }
3818
                }
3819

    
3820
                DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
3821
                        super((Frame)null, "",true);
3822
                        this.setTitle(translate("_Conflicting_plugins"));
3823
                        
3824
                        this.packages = packages;
3825
                        
3826
                        this.incompatiblePlugins  = new ArrayList<Item>();
3827
                        Item item = null;
3828
                        Iterator<String> it = incompatiblePlugins.iterator();
3829
                        while( it.hasNext() ) {
3830
                                String code = it.next();
3831
                                item = new Item(code, packages.get(code));
3832
                                this.incompatiblePlugins.add(item);
3833
                                logger.info("Found plugin '"+item.getCode()+"' incopatibles with each other.");
3834
                        }
3835
                        initComponents();
3836
                }
3837
                
3838
                private void initComponents() {
3839
                        this.contents = new DisablePluginsConflictingLayoutPanel();
3840
                        
3841
                        doTranslations();
3842

    
3843
                        this.contents.buttonClose.addActionListener( new ActionListener() {
3844
                                public void actionPerformed(ActionEvent arg0) {
3845
                                        doClose();
3846
                                }
3847
                        });
3848
                        this.contents.buttonContinue.addActionListener( new ActionListener() {
3849
                                public void actionPerformed(ActionEvent arg0) {
3850
                                        doContinue();
3851
                                }
3852
                        });
3853
                        this.contents.pluginList.setModel(new DefaultListModel(this.incompatiblePlugins));
3854
                        ListSelectionModel sm = this.contents.pluginList.getSelectionModel();
3855
                        sm.setSelectionMode(sm.MULTIPLE_INTERVAL_SELECTION);
3856
                        this.setContentPane(this.contents);
3857
                        this.pack();
3858

    
3859
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
3860
                setLocation((screenSize.width / 2) - (this.getWidth() / 2),
3861
                    (screenSize.height / 2) - (this.getHeight()/ 2));
3862
                }
3863
                
3864
                private void doTranslations() {
3865
                        DisablePluginsConflictingLayoutPanel c = this.contents;
3866
                        c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
3867
                        c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
3868
                        c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
3869
                        c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
3870
                        c.buttonClose.setText(translate("_Close"));
3871
                        c.buttonContinue.setText(translate("_Continue"));
3872
                }
3873
                
3874
                private String translate(String msg) {
3875
                        return PluginServices.getText(this,msg);
3876
                }
3877
                
3878
                private void doClose() {
3879
                        this.action = CLOSE;
3880
                        this.setVisible(false);
3881
                }
3882
                
3883
                private void doContinue() {
3884
                        this.action = CONTINUE;
3885
                        this.setVisible(false);
3886
                }
3887
                
3888
                public int getAction() {
3889
                        return this.action;
3890
                }
3891

    
3892
                public List<String> getPluginNamesToDisable() {
3893
                        if( this.action == CLOSE ) {
3894
                                return null;
3895
                        }
3896
                        Object[] selecteds = null;
3897
                        selecteds = (Object[]) this.contents.pluginList.getSelectedValues();
3898
                        if( selecteds == null || selecteds.length < 1 ) {
3899
                                return null;
3900
                        }
3901
                        List<String> values = new ArrayList<String>();
3902
                        for( int i=0 ; i<selecteds.length; i++ ) {
3903
                                values.add(((Item)selecteds[i]).getCode());
3904
                        }
3905
                        return values;
3906
                }
3907
        }
3908
}