Statistics
| Revision:

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

History | View | Annotate | Download (162 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 modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.andami;
24

    
25
import java.awt.BorderLayout;
26
import java.awt.Cursor;
27
import java.awt.Dimension;
28
import java.awt.EventQueue;
29
import java.awt.Frame;
30
import java.awt.KeyboardFocusManager;
31
import java.awt.Point;
32
import java.awt.Toolkit;
33
import java.awt.event.ActionEvent;
34
import java.awt.event.ActionListener;
35
import java.awt.event.WindowEvent;
36
import java.awt.event.WindowListener;
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.Arrays;
65
import java.util.Collections;
66
import java.util.Comparator;
67
import java.util.Enumeration;
68
import java.util.HashMap;
69
import java.util.HashSet;
70
import java.util.Iterator;
71
import java.util.List;
72
import java.util.Locale;
73
import java.util.Map;
74
import java.util.Map.Entry;
75
import java.util.Properties;
76
import java.util.Set;
77
import java.util.TreeSet;
78
import java.util.logging.Level;
79
import java.util.prefs.Preferences;
80

    
81
import javax.swing.ImageIcon;
82
import javax.swing.JButton;
83
import javax.swing.JComponent;
84
import javax.swing.JDialog;
85
import javax.swing.JFrame;
86
import javax.swing.JOptionPane;
87
import javax.swing.JPopupMenu;
88
import javax.swing.ListSelectionModel;
89
import javax.swing.SwingUtilities;
90
import javax.swing.UIManager;
91

    
92

    
93
import org.apache.commons.cli.CommandLine;
94
import org.apache.commons.cli.CommandLineParser;
95
import org.apache.commons.cli.Options;
96
import org.apache.commons.cli.ParseException;
97
import org.apache.commons.cli.PosixParser;
98
import org.apache.commons.configuration.PropertiesConfiguration;
99
import org.apache.commons.io.FileUtils;
100
import org.apache.commons.io.input.ClassLoaderObjectInputStream;
101
import org.apache.commons.lang3.JavaVersion;
102
import org.apache.commons.lang3.StringUtils;
103
import org.apache.commons.lang3.SystemUtils;
104
import org.apache.log4j.AppenderSkeleton;
105
import org.apache.log4j.PatternLayout;
106
import org.apache.log4j.PropertyConfigurator;
107
import org.apache.log4j.RollingFileAppender;
108
import org.apache.log4j.spi.LoggingEvent;
109
import org.apache.log4j.spi.ThrowableInformation;
110
import org.exolab.castor.xml.MarshalException;
111
import org.exolab.castor.xml.ValidationException;
112

    
113
import org.gvsig.andami.actioninfo.ActionInfo;
114
import org.gvsig.andami.actioninfo.ActionInfoManager;
115
import org.gvsig.andami.config.generate.Andami;
116
import org.gvsig.andami.config.generate.AndamiConfig;
117
import org.gvsig.andami.config.generate.Plugin;
118
import org.gvsig.andami.impl.UnsavedDataException;
119
import org.gvsig.andami.messages.Messages;
120
import org.gvsig.andami.messages.NotificationManager;
121
import org.gvsig.andami.persistence.serverData.ServerDataPersistence;
122
import org.gvsig.andami.plugins.ExclusiveUIExtension;
123
import org.gvsig.andami.plugins.ExtensionDecorator;
124
import org.gvsig.andami.plugins.IExtension;
125
import org.gvsig.andami.plugins.PluginClassLoader;
126
import org.gvsig.andami.plugins.config.generate.Action;
127
import org.gvsig.andami.plugins.config.generate.ActionTool;
128
import org.gvsig.andami.plugins.config.generate.AlternativeNames;
129
import org.gvsig.andami.plugins.config.generate.ComboButton;
130
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
131
import org.gvsig.andami.plugins.config.generate.ComboScale;
132
import org.gvsig.andami.plugins.config.generate.Depends;
133
import org.gvsig.andami.plugins.config.generate.Extension;
134
import org.gvsig.andami.plugins.config.generate.Extensions;
135
import org.gvsig.andami.plugins.config.generate.LabelSet;
136
import org.gvsig.andami.plugins.config.generate.Menu;
137
import org.gvsig.andami.plugins.config.generate.PluginConfig;
138
import org.gvsig.andami.plugins.config.generate.PopupMenu;
139
import org.gvsig.andami.plugins.config.generate.PopupMenus;
140
import org.gvsig.andami.plugins.config.generate.SelectableTool;
141
import org.gvsig.andami.plugins.config.generate.SkinExtension;
142
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
143
import org.gvsig.andami.plugins.config.generate.ToolBar;
144
import org.gvsig.andami.plugins.status.IExtensionStatus;
145
import org.gvsig.andami.plugins.status.IUnsavedData;
146
import org.gvsig.andami.ui.AndamiEventQueue;
147
import org.gvsig.andami.ui.DisablePluginsConflictingLayoutPanel;
148
import org.gvsig.andami.ui.MDIManagerLoadException;
149
import org.gvsig.andami.ui.ToolsWindowManager;
150
import org.gvsig.andami.ui.fonts.FontUtils;
151
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
152
import org.gvsig.andami.ui.mdiFrame.MainFrame;
153
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
154
import org.gvsig.andami.ui.splash.MultiSplashWindow;
155
import org.gvsig.andami.ui.theme.Theme;
156
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
157
import org.gvsig.andami.ui.wizard.UnsavedDataPanel.UnsavedDataPanelListener;
158
import org.gvsig.installer.lib.api.Dependencies;
159
import org.gvsig.installer.lib.api.Dependency;
160
import org.gvsig.installer.lib.api.InstallerLocator;
161
import org.gvsig.installer.lib.api.InstallerManager;
162
import org.gvsig.installer.lib.api.PackageInfo;
163
import org.gvsig.installer.lib.api.creation.MakePluginPackageServiceException;
164
import org.gvsig.installer.swing.api.SwingInstallerLocator;
165
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
166
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
167
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
168
import org.gvsig.tools.ToolsLocator;
169
import org.gvsig.tools.exception.ListBaseException;
170
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
171
import org.gvsig.tools.swing.api.ToolsSwingLocator;
172
import org.gvsig.tools.swing.api.windowmanager.WindowManager.MODE;
173
import org.gvsig.tools.swing.icontheme.IconTheme;
174
import org.gvsig.tools.swing.icontheme.IconThemeManager;
175
import org.gvsig.tools.util.FolderSet;
176
import org.gvsig.tools.util.FolderSet.FolderEntry;
177
import org.gvsig.utils.DateTime;
178
import org.gvsig.utils.DefaultListModel;
179
import org.gvsig.utils.XMLEntity;
180
import org.gvsig.utils.xml.XMLEncodingUtils;
181
import org.gvsig.utils.xmlEntity.generate.XmlTag;
182

    
183
import org.slf4j.Logger;
184
import org.slf4j.LoggerFactory;
185

    
186
/**
187
 * <p>
188
 * Andami's launching class. This is the class used to create the Andami's
189
 * plugin environment.<br>
190
 * </p>
191
 *
192
 * <p>
193
 * <b>Syntax:</b> <br>
194
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or
195
 * semicolon-separated(windows) list of files containg base library of classes}]
196
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
197
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
198
 * [{list of additional custom application arguments separated by spaces}]
199
 * </p>
200
 *
201
 *
202
 * @author $author$
203
 * @version $Revision: 40305 $
204
 */
205
public class Launcher {
206

    
207
    public static abstract class MapWithAlias<Item> extends HashMap<String, Item> {
208

    
209
        private HashMap<String, String> aliases = new HashMap<String, String>();
210

    
211
        public abstract String[] getAliases(Item item);
212

    
213
        public boolean isAlias(String key) {
214
            return aliases.get(key) != null;
215
        }
216

    
217
        public String getMainKey(String key) {
218
            Item item = super.get(key);
219
            if (item != null) {
220
                return key;
221
            }
222
            String alias = aliases.get(key);
223
            if (alias != null) {
224
                return alias;
225
            }
226
            return null;
227
        }
228

    
229
        public Item get(Object key) {
230
            Item item = super.get(key);
231
            if (item != null) {
232
                return item;
233
            }
234
            String alias = aliases.get(key);
235
            if (alias != null) {
236
                return super.get(alias);
237
            }
238
            return null;
239
        }
240

    
241
        public boolean containsKey(Object key) {
242
            boolean contains = super.containsKey(key);
243
            if (contains) {
244
                return true;
245
            }
246
            String alias = aliases.get(key);
247
            return super.containsKey(alias);
248
        }
249

    
250
        public Item put(String key, Item value) {
251
            super.put(key, value);
252
            String[] aliases = getAliases(value);
253
            if (aliases == null) {
254
                return value;
255
            }
256
            for (int n = 0; n < aliases.length; n++) {
257
                this.aliases.put(aliases[n].trim(), key);
258
            }
259
            return value;
260
        }
261

    
262
        public void putAll(Map<? extends String, ? extends Item> m) {
263
            Iterator<?> it = m.entrySet().iterator();
264
            while (it.hasNext()) {
265
                Map.Entry<String, Item> x = (Map.Entry<String, Item>) it.next();
266
                this.put(x.getKey(), x.getValue());
267
            }
268
        }
269

    
270
        public Item remove(Object key) {
271
            Item item = super.get(key);
272
            if (item == null) {
273
                String alias = aliases.get(key);
274
                if (alias == null) {
275
                    return null;
276
                }
277
                item = super.get(alias);
278
                super.remove(alias);
279
            } else {
280
                super.remove(key);
281
            }
282
            String[] aliases = getAliases(item);
283
            if (aliases == null) {
284
                return item;
285
            }
286
            // Rebuild the alias list
287
            this.aliases = new HashMap<String, String>();
288
            Iterator<java.util.Map.Entry<String, Item>> it = this.entrySet().iterator();
289
            while (it.hasNext()) {
290
                java.util.Map.Entry<String, Item> entry = it.next();
291
                aliases = getAliases(entry.getValue());
292
                if (aliases == null) {
293
                    continue;
294
                }
295
                for (int n = 0; n < aliases.length; n++) {
296
                    this.aliases.put(aliases[n].trim(), entry.getKey());
297
                }
298
            }
299

    
300
            return item;
301
        }
302

    
303
    }
304

    
305
    public static class PluginsConfig extends MapWithAlias<org.gvsig.andami.plugins.config.generate.PluginConfig> {
306

    
307
        public String[] getAliases(
308
                org.gvsig.andami.plugins.config.generate.PluginConfig item) {
309
            return getAlternativeNames(item);
310
        }
311

    
312
        static String[] getAlternativeNames(org.gvsig.andami.plugins.config.generate.PluginConfig item) {
313
            AlternativeNames[] x = item.getAlternativeNames();
314
            if (x == null) {
315
                return null;
316
            }
317
            String[] r = new String[x.length];
318
            for (int i = 0; i < x.length; i++) {
319
                r[i] = x[i].getName();
320
            }
321
            return r;
322
        }
323

    
324
    }
325

    
326
    public static class PluginsServices extends MapWithAlias<org.gvsig.andami.PluginServices> {
327

    
328
        public String[] getAliases(org.gvsig.andami.PluginServices item) {
329
            return item.getAlternativeNames();
330
        }
331
    }
332

    
333
    protected static Logger logger = LoggerFactory.getLogger(Launcher.class
334
            .getName());
335
    protected static Preferences prefs = Preferences.userRoot().node(
336
            "gvsig.connection");
337
    protected static AndamiConfig andamiConfig;
338
    protected static MultiSplashWindow splashWindow;
339
    protected static String appName;
340
    protected static Locale locale;
341
    protected static PluginsConfig pluginsConfig = new PluginsConfig();
342
    protected static PluginsServices pluginsServices = new PluginsServices();
343
    protected static MDIFrame frame;
344
    protected static HashMap<Class<? extends IExtension>, ExtensionDecorator> classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
345
    protected static String andamiConfigPath;
346
    protected static final String nonWinDefaultLookAndFeel = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
347

    
348
    protected static List<String> pluginsOrdered = new ArrayList<String>();
349
    protected static List<IExtension> extensions = new ArrayList<IExtension>();
350
    protected static String appHomeDir = null;
351
    // it seems castor uses this encoding
352
    protected static final String CASTORENCODING = "UTF8";
353

    
354
    protected static ListBaseException launcherrors = null;
355

    
356
    protected static Theme theme = null;
357

    
358
    private List<String> deprecatedPluginNames = null;
359

    
360
    private static final class ProxyAuth extends Authenticator {
361

    
362
        private PasswordAuthentication auth;
363

    
364
        private ProxyAuth(String user, String pass) {
365
            auth = new PasswordAuthentication(user, pass.toCharArray());
366
        }
367

    
368
        protected PasswordAuthentication getPasswordAuthentication() {
369
            return auth;
370
        }
371
    }
372

    
373
    private static Launcher launcherInstance;
374

    
375
    public static Launcher getInstance() {
376
        if (launcherInstance == null) {
377
            launcherInstance = new Launcher();
378
        }
379
        return launcherInstance;
380
    }
381

    
382
    public static void main(String[] args) throws Exception {
383
        Launcher launcher = getInstance();
384
        boolean install = false;
385
        for (int i = 0; i < args.length; i++) {
386
            if (args[i].equalsIgnoreCase("--install")) {
387
                install = true;
388
            }
389
        }
390

    
391
        try {
392
            if (install) {
393
                launcher.doInstall(args);
394
            } else {
395
                launcher.doMain(args);
396
            }
397
        } catch (Exception e) {
398
            logger.error("excepci?n al arrancar", e);
399
            System.exit(-1);
400
        }
401
    }
402

    
403
    protected void downloadExtensions(String extDir) {
404
        // do nothing
405
    }
406

    
407
    public static class LaunchException extends ListBaseException {
408

    
409
        private static final long serialVersionUID = 4541192746962684705L;
410

    
411
        public LaunchException() {
412
            super("Errors in initialization of application.",
413
                    "_errors_in_initialization_of_application",
414
                    serialVersionUID);
415
        }
416

    
417
    }
418

    
419
    protected void addError(Throwable ex) {
420
        if (launcherrors == null) {
421
            launcherrors = new LaunchException();
422
        }
423
        launcherrors.add(ex);
424
    }
425

    
426
    protected void addError(String msg, Throwable cause) {
427
        logger.error(msg, cause);
428
        this.addError(new RuntimeException(msg, cause));
429
    }
430

    
431
    protected void addError(String msg) {
432
        this.addError(msg, null);
433
    }
434

    
435
    private String translate(String msg) {
436
        return PluginServices.getText(Launcher.class, msg);
437
    }
438

    
439
    private List<String> getDeprecatedPluginNames() {
440
        if (deprecatedPluginNames == null) {
441
            String[] ss = new String[]{
442
                "org.gvsig.app",
443
                "org.gvsig.coreplugin",
444
                "org.gvsig.editing",
445
                "org.gvsig.installer.app.extension",
446
                "org.gvsig.exportto.app.extension"
447
            };
448
            deprecatedPluginNames = Arrays.asList(ss);
449
        }
450
        return deprecatedPluginNames;
451
    }
452

    
453
    public void doMain(String[] args) throws Exception {
454

    
455
        if (args.length < 1) {
456
            System.err.println("Usage: Launcher appName plugins-directory [language=locale]");
457
            System.err.println("No arguments specified.");
458
            System.err.println("Use default arguments 'gvSIG gvSIG/extensiones'");
459
            args = new String[]{"gvSIG", "gvSIG/extensiones"};
460
        }
461

    
462
        initializeApp(args, null);
463

    
464
                // Solucionamos el problema de permisos que se produc?do con Java
465
        // Web Start con este codigo.
466
        // System.setSecurityManager(null);
467
        Policy.setPolicy(new Policy() {
468

    
469
            public PermissionCollection getPermissions(CodeSource codesource) {
470
                Permissions perms = new Permissions();
471
                perms.add(new AllPermission());
472
                return (perms);
473
            }
474

    
475
            public void refresh() {
476
            }
477
        });
478

    
479
        new DefaultLibrariesInitializer().fullInitialize(true);
480
        InstallerLocator.getInstallerManager().setDownloadBaseURL(
481
                new URL("http://downloads.gvsig.org/download/gvsig-desktop/"));
482

    
483
        try {
484
            initIconThemes();
485
        } catch (Exception ex) {
486
            this.addError("Can't initialize icon theme", ex);
487
        }
488
        // Registramos los iconos base
489
        try {
490
            registerIcons();
491
        } catch (Exception ex) {
492
            this.addError("Can't register icons", ex);
493
        }
494

    
495
        // Obtener la personalizaci?n de la aplicacion.
496
        try {
497
            logger.info("Initialize andami theme");
498
            theme = getTheme(andamiConfig.getPluginsDirectory());
499
        } catch (Exception ex) {
500
            this.addError("Can't get personalized theme for the application",
501
                    ex);
502
        }
503
        UIManager.put("Desktop.background", theme.getBackgroundColor());
504

    
505
        // Mostrar la ventana de inicio
506
        Frame f = new Frame();
507
        splashWindow = new MultiSplashWindow(f, theme, 27);
508

    
509
        // Ponemos los datos del proxy
510
        splashWindow.process(translate("SplashWindow.configuring_proxy"));
511
        logger.info("Configute http proxy");
512
        configureProxy();
513

    
514
        // Buscar actualizaciones de los plugins
515
        splashWindow.process(translate("SplashWindow.looking_for_updates"));
516
        try {
517
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
518
        } catch (Exception ex) {
519
            this.addError("Can't downloads plugins", ex);
520
        }
521

    
522
        splashWindow.process(translate("SplashWindow.initialize_install_manager"));
523
        initializeInstallerManager();
524

    
525
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
526
        PackageInfo[] installedPackages = null;
527
        try {
528
            installedPackages = installerManager.getInstalledPackages();
529
        } catch (MakePluginPackageServiceException e) {
530
            // Do nothing, ignore errors
531
        }
532
        logger.info("Dump system information");
533
        logger_info(getInformation(installedPackages));
534
        saveEnvironInformation(installedPackages);
535

    
536
        // Se leen los config.xml de los plugins
537
        splashWindow.process(translate("SplashWindow.load_plugins_configuration"));
538
        try {
539
            logger.info("Load plugins information");
540
            this.loadPluginConfigs();
541
            if (pluginsConfig.isEmpty()) {
542
                logger.warn("No valid plugin was found.");
543
                System.exit(-1);
544
            }
545
        } catch (Throwable ex) {
546
            this.addError("Can't load plugins", ex);
547
        }
548

    
549
        splashWindow.process(translate("SplashWindow.check_incompatible_plugins"));
550
        fixIncompatiblePlugins(installedPackages);
551

    
552
        // Se configura el classloader del plugin
553
        splashWindow.process(translate("SplashWindow.setup_plugins_configuration"));
554
        try {
555
            logger.info("Configure plugins class loader");
556
            this.loadPluginServices();
557
        } catch (Throwable ex) {
558
            logger.warn("Can't initialize plugin's classloaders  ", ex);
559
        }
560
        try {
561
            registerActions();
562
        } catch (Throwable ex) {
563
            logger.warn("Can't register actions of plugins", ex);
564
        }
565

    
566
        initializeIdentityManagement(new File(andamiConfig.getPluginsDirectory()).getAbsoluteFile());
567

    
568
        // Initialize libraries
569
        splashWindow.process(translate("SplashWindow.initialize_plugins_libraries"));
570
        initializeLibraries();
571

    
572
        // Se carga un Skin si alguno ide los plugins trae informacion para ello
573
        splashWindow.process(translate("SplashWindow.looking_for_a_skin"));
574
        logger.info("Initialize skin");
575
        skinPlugin(null);
576

    
577
        // Se configura la cola de eventos
578
        splashWindow.process(translate("setting_up_event_queue"));
579
        EventQueue waitQueue = new AndamiEventQueue();
580
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
581

    
582
        // Se configura la internacionalizacion del plugin
583
        splashWindow.process(translate("SplashWindow.starting_plugin_internationalization_system"));
584
        pluginsMessages();
585

    
586
        // Se modifica el andami-config con los plugins nuevos
587
        splashWindow.process(translate("SplashWindow.update_framework_configuration"));
588
        updateAndamiConfig();
589

    
590
        frame = MDIFrame.getInstance();
591
        // Se configura el nombre e icono de la aplicacion
592
        splashWindow.process(translate("SplashWindow.setting_up_applications_name_and_icons"));
593
        frameIcon(theme);
594

    
595
        // Se prepara el MainFrame para albergar las extensiones
596
        splashWindow.process(translate("SplashWindow.preparing_workbench"));
597
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
598
        SwingUtilities.invokeAndWait(new Runnable() {
599
            public void run() {
600
                frame.init();
601
            }
602
        });
603
        ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
604

    
605
        // Leer el fichero de persistencia de los plugins
606
        splashWindow.process(translate("SplashWindow.loading_plugin_settings"));
607
        loadPluginsPersistence();
608

    
609
                // Se instalan los controles del skin
610
        // Se inicializan todas las extensiones de todos los plugins
611
        splashWindow.process(translate("SplashWindow.initializing_extensions"));
612
        SwingUtilities.invokeAndWait(new Runnable() {
613
            public void run() {
614
                initializeExtensions();
615
            }
616
        });
617

    
618
        // Se inicializan la extension exclusiva
619
        splashWindow.process(translate("SplashWindow.setting_up_master_extension"));
620
        SwingUtilities.invokeAndWait(new Runnable() {
621
            public void run() {
622
                initializeExclusiveUIExtension();
623
            }
624
        });
625
        frame.setClassesExtensions(classesExtensions);
626

    
627
        // Se instalan los controles de las extensiones de los plugins
628
        message(translate("SplashWindow.installing_extensions_controls"));
629
        SwingUtilities.invokeAndWait(new Runnable() {
630
            public void run() {
631
                installPluginsControls();
632
            }
633
        });
634

    
635
        // Se instalan los menus de las extensiones de los plugins
636
        message(translate("SplashWindow.installing_extensions_menus"));
637
        SwingUtilities.invokeAndWait(new Runnable() {
638
            public void run() {
639
                installPluginsMenus();
640
            }
641
        });
642

    
643
        message(translate("SplashWindow.initializing_server_data_persistence"));
644
        ServerDataPersistence.registerPersistence();
645

    
646
        // Se instalan las etiquetas de las extensiones de los plugins
647
        message(translate("SplashWindow.installing_extensions_labels"));
648
        SwingUtilities.invokeAndWait(new Runnable() {
649
            public void run() {
650
                installPluginsLabels();
651
            }
652
        });
653

    
654
        // Se muestra el frame principal
655
        message(translate("creating_main_window"));
656
        frame.setVisible(true);
657
        frame.setCursor(Cursor.WAIT_CURSOR);
658

    
659
                // Definimos un KeyEventDispatcher global para que las extensiones
660
        // puedan registrar sus "teclas rapidas".
661
        message(translate("SplashWindow.initializing_accelerator_keys"));
662
        GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
663
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
664

    
665
        message(translate("SplashWindow.enable_controls"));
666
        SwingUtilities.invokeAndWait(new Runnable() {
667
            public void run() {
668
                try {
669
                    frame.enableControls();
670
                } catch (Throwable th) {
671
                    logger.warn("Problems enabling controls", th);
672
                }
673
            }
674
        });
675

    
676
        // Se ejecuta el postInitialize
677
        message(translate("SplashWindow.post_initializing_extensions"));
678
        SwingUtilities.invokeAndWait(new Runnable() {
679
            public void run() {
680
                postInitializeExtensions();
681
            }
682
        });
683

    
684
        message(translate("SplashWindow.enable_controls"));
685
        SwingUtilities.invokeAndWait(new Runnable() {
686
            public void run() {
687
                try {
688
                    frame.enableControls();
689
                    message(translate("StatusBar.Aplicacion_iniciada"));
690
                } catch (Throwable th) {
691
                    logger.warn("Problems enabling controls", th);
692
                }
693
            }
694
        });
695

    
696
        splashWindow.close();
697

    
698
        frame.setCursor(Cursor.DEFAULT_CURSOR);
699

    
700
        if (launcherrors != null) {
701
            NotificationManager.addError(launcherrors);
702
        }
703
        org.apache.log4j.Logger.getRootLogger().addAppender(
704
                new NotificationAppender());
705

    
706
        /*
707
         * Executes additional tasks required by plugins
708
         */
709
        PluginsLocator.getManager().executeStartupTasks();
710

    
711
    }
712

    
713
    private void initializeInstallerManager() {
714
        PluginsManager pluginmgr = PluginsLocator.getManager();
715
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
716

    
717
            //
718
        // Configure repository of plugins
719
        //
720
        List<File> folders = pluginmgr.getPluginsFolders();
721
        for (File folder : folders) {
722
            installerManager.addLocalAddonRepository(folder, "plugin");
723
        }
724
        installerManager.setDefaultLocalAddonRepository(folders.get(0), "plugin");
725

    
726
            //
727
        // Configure repository of iconsets
728
        //
729
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
730
        FolderSet fset = iconManager.getRepository();
731
        Iterator<FolderSet.FolderEntry> it = fset.iterator();
732
        boolean first = true;
733
        while (it.hasNext()) {
734
            FolderEntry entry = it.next();
735
            installerManager.addLocalAddonRepository(entry.getFolder(), "iconset");
736
            if (first) {
737
                first = false;
738
                installerManager.setDefaultLocalAddonRepository(entry.getFolder(), "iconset");
739
            }
740
        }
741

    
742
    }
743

    
744
    private void message(final String msg) {
745
        if (!SwingUtilities.isEventDispatchThread()) {
746
            try {
747
                SwingUtilities.invokeAndWait(new Runnable() {
748
                    public void run() {
749
                        message(msg);
750
                    }
751
                });
752
            } catch (Exception e) {
753
                logger.info(msg);
754
                logger.warn("Error showing message.", e);
755
            }
756
            return;
757
        }
758
        if (splashWindow.isVisible()) {
759
            splashWindow.process(msg);
760
        }
761
        if (frame.isVisible()) {
762
            frame.message(msg, JOptionPane.INFORMATION_MESSAGE);
763
        }
764
    }
765

    
766
    private void initializeLibraries() {
767
        List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
768
                pluginsOrdered.size() + 1);
769
        classLoaders.add(getClass().getClassLoader());
770
        Iterator<String> iter = pluginsOrdered.iterator();
771

    
772
        logger.info("Initializing plugins libraries: ");
773
        while (iter.hasNext()) {
774
            String pName = (String) iter.next();
775
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
776
            logger.info("Initializing plugin libraries (" + pName + ")");
777
            classLoaders.add(ps.getClassLoader());
778
        }
779

    
780
                // Create the libraries initializer and
781
        // initialize the plugin libraries
782
        new DefaultLibrariesInitializer(classLoaders
783
                .toArray(new ClassLoader[classLoaders.size()]))
784
                .fullInitialize(true);
785

    
786
        // Remove them all, we don't need them anymore
787
        classLoaders.clear();
788
        classLoaders = null;
789
    }
790

    
791
    /**
792
     * @param args
793
     * @throws IOException
794
     * @throws ConfigurationException
795
     */
796
    private void initializeApp(String[] args, String applicationClasifier) throws IOException, ConfigurationException {
797
        if (args.length < 1) {
798
            appName = "gvSIG"; // Nombre de aplicacion por defecto es "gvSIG"
799
        } else {
800
            appName = args[0];
801
        }
802
        getOrCreateConfigFolder();
803
        configureLogging(appName, applicationClasifier);
804
        if (!validJVM()) {
805
            logger.error("Not a valid JRE. Exit application.");
806
            System.exit(-1);
807
        }
808
        // Clean temporal files
809
        Utilities.cleanUpTempFiles();
810

    
811
        if (args.length < 2) {
812
            loadAndamiConfig("gvSIG/extensiones"); // Valor por defecto
813
        } else {
814
            loadAndamiConfig(args[1]);
815
        }
816

    
817
                // Hacemos visibles los argumentos como una propiedad est?tica
818
        // de plugin services para quien lo quiera usar (por ejemplo, para
819
        // cargar un proyecto por l?nea de comandos)
820
        PluginServices.setArguments(args);
821

    
822
        configureLocales(args);
823

    
824
        logger.info("Configure LookAndFeel");
825
        configureLookAndFeel();
826
    }
827

    
828
    /**
829
     *
830
     */
831
    private void configureLookAndFeel() {
832
        // Se pone el lookAndFeel
833
        try {
834
            String lookAndFeel = getAndamiConfig().getLookAndFeel();
835
            if (lookAndFeel == null) {
836
                lookAndFeel = getDefaultLookAndFeel();
837
            }
838
            UIManager.setLookAndFeel(lookAndFeel);
839
        } catch (Exception e) {
840
            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
841
        }
842
        FontUtils.initFonts();
843
    }
844

    
845
    /**
846
     * @param args
847
     * @throws ConfigurationException
848
     */
849
    private void loadAndamiConfig(String pluginFolder)
850
            throws ConfigurationException {
851
        andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
852
        andamiConfigFromXML(andamiConfigPath);
853
        andamiConfig.setPluginsDirectory(pluginFolder);
854
    }
855

    
856
    /**
857
     *
858
     */
859
    private void getOrCreateConfigFolder() {
860
        // Create application configuration folder
861
        appHomeDir = System.getProperty(appName + ".home");
862
        if (appHomeDir == null) {
863
            appHomeDir = System.getProperty("user.home");
864
        }
865

    
866
        appHomeDir += File.separator + appName;
867
        File parent = new File(appHomeDir);
868
        parent.mkdirs();
869
    }
870

    
871
    /**
872
     * @param args
873
     * @throws IOException
874
     */
875
    private void configureLogging(String appName, String applicationClasifier) throws IOException {
876
        // Configurar el log4j
877

    
878
        String pathname;
879
        if (StringUtils.isBlank(applicationClasifier)) {
880
            pathname = appHomeDir + File.separator + appName + ".log";
881
        } else {
882
            pathname = appHomeDir + File.separator + appName + "-" + applicationClasifier + ".log";
883
        }
884
        URL config = Launcher.class.getClassLoader().getResource("log4j.properties");
885
        if (config == null) {
886
            config = Launcher.class.getClassLoader().getResource("default-log4j/log4j.properties");
887
        }
888
        PropertyConfigurator.configure(config);
889
        PatternLayout l = new PatternLayout("%p %t %C - %m%n");
890
        RollingFileAppender fa = new RollingFileAppender(l, pathname, false);
891
        fa.setMaxFileSize("512KB");
892
        fa.setMaxBackupIndex(3);
893
        org.apache.log4j.Logger.getRootLogger().addAppender(fa);
894
        logger.info("Loadded log4j.properties from " + config.toString());
895
        if (StringUtils.isBlank(applicationClasifier)) {
896
            logger.info("Application " + appName);
897
        } else {
898
            logger.info("Application " + appName + "-" + applicationClasifier);
899
        }
900
    }
901
    
902
    public static String getApplicationName() {
903
        return appName;
904
    }
905

    
906
    private class NotificationAppender extends AppenderSkeleton {
907

    
908
        @Override
909
        protected void append(LoggingEvent event) {
910
            if (event.getLevel() == org.apache.log4j.Level.ERROR
911
                    || event.getLevel() == org.apache.log4j.Level.FATAL) {
912

    
913
                Throwable th = null;
914
                ThrowableInformation thi = event.getThrowableInformation();
915
                if (thi != null) {
916
                    th = thi.getThrowable();
917
                }
918
                NotificationManager.dispatchError(event.getRenderedMessage(), th);
919
                return;
920
            }
921
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
922
            // NotificationManager.dispatchWarning(event.getRenderedMessage(),
923
            // null);
924
            // return;
925
            // }
926
        }
927

    
928
        @Override
929
        public void close() {
930
            // TODO Auto-generated method stub
931

    
932
        }
933

    
934
        @Override
935
        public boolean requiresLayout() {
936
            // TODO Auto-generated method stub
937
            return false;
938
        }
939

    
940
    }
941

    
942
    /**
943
     * Return the directory applicaction is installed.
944
     */
945
    public static String getApplicationDirectory() {
946
        return getApplicationFolder().getAbsolutePath();
947
    }
948

    
949
    public static File getApplicationFolder() {
950
        // TODO: check if there is a better way to handle this
951
        return new File(System.getProperty("user.dir"));
952
    }
953

    
954
    private void registerIcons() {
955
        IconTheme theme = PluginServices.getIconTheme();
956
        ClassLoader loader = Launcher.class.getClassLoader();
957

    
958
        String[][] icons = {
959
            // MultiSplashWindow
960
            {"main", "splash-default"},
961
            // NewStatusBar
962
            {"main", "statusbar-info"},
963
            {"main", "statusbar-warning"},
964
            {"main", "statusbar-error"}
965
        };
966
        for (int i = 0; i < icons.length; i++) {
967
            try {
968
                IconThemeHelper.registerIcon(icons[i][0], icons[i][1], Launcher.class);
969
            } catch (Exception e) {
970
                logger.info("Can't register icon '" + icons[i][0] + "' (" + icons[i][1] + ").");
971
            }
972
        }
973
        theme.setDefaultIcon(loader.getResource("images/main/default-icon.png"));
974
    }
975

    
976
    private Properties loadProperties(File f) {
977
        FileInputStream fin = null;
978
        Properties p = null;
979
        try {
980
            fin = new FileInputStream(f);
981
            p = new Properties();
982
            p.load(fin);
983
        } catch (IOException ex) {
984
            // Do nothing
985
        }
986
        return p;
987
    }
988

    
989
    /**
990
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
991
     * la aplicaci?n.
992
     *
993
     * @return Theme
994
     */
995
    private Theme getTheme(String pluginsDirectory) {
996
        File infoFile = new File(Launcher.getApplicationFolder(), "package.info");
997
        File themeFile = null;
998
        List<Theme> themes = new ArrayList<Theme>();
999

    
1000
        // Try to get theme from args
1001
        String name = PluginServices.getArgumentByName("andamiTheme");
1002
        if (name != null) {
1003
            themeFile = new File(name);
1004
            logger.info("search andami-theme in {}", themeFile.getAbsolutePath());
1005
            if (themeFile.exists()) {
1006
                Theme theme = new Theme(loadProperties(infoFile));
1007
                theme.readTheme(themeFile);
1008
                logger.info("andami-theme found in {}", themeFile.getAbsolutePath());
1009
                return theme;
1010
            }
1011
        }
1012

    
1013
        // Try to get theme from a plugin
1014
        File pluginsDir = new File(pluginsDirectory);
1015
        if (!pluginsDir.isAbsolute()) {
1016
            pluginsDir = new File(getApplicationFolder(), pluginsDirectory);
1017
        }
1018
        if (pluginsDir.exists()) {
1019
            logger.info("search andami-theme in plugins folder '" + pluginsDir.getAbsolutePath() + "'.");
1020
            File[] pluginDirs = pluginsDir.listFiles();
1021
            if (pluginDirs.length > 0) {
1022
                for (int i = 0; i < pluginDirs.length; i++) {
1023
                    File pluginThemeFile = new File(pluginDirs[i],
1024
                            "theme" + File.separator + "andami-theme.xml");
1025
                    if (pluginThemeFile.exists()) {
1026
                        Theme theme = new Theme(loadProperties(infoFile));
1027
                        theme.readTheme(pluginThemeFile);
1028
                        themes.add(theme);
1029
                    }
1030
                }
1031
            }
1032
        }
1033

    
1034
        // Try to get theme from dir gvSIG in user home
1035
        themeFile = new File(getAppHomeDir(), "theme" + File.separator
1036
                + "andami-theme.xml");
1037
        logger.info("search andami-theme in user's home {}", themeFile
1038
                .getAbsolutePath());
1039
        if (themeFile.exists()) {
1040
            Theme theme = new Theme(loadProperties(infoFile));
1041
            theme.readTheme(themeFile);
1042
            themes.add(theme);
1043
        }
1044

    
1045
        // Try to get theme from the instalation dir of gvSIG.
1046
        themeFile = new File(getApplicationDirectory(), "theme"
1047
                + File.separator + "andami-theme.xml");
1048
        logger.info("search andami-theme in installation folder {}", themeFile
1049
                .getAbsolutePath());
1050
        if (themeFile.exists()) {
1051
            Theme theme = new Theme(loadProperties(infoFile));
1052
            theme.readTheme(themeFile);
1053
            themes.add(theme);
1054
        }
1055

    
1056
        Collections.sort(themes, new Comparator<Theme>() {
1057
            public int compare(Theme t1, Theme t2) {
1058
                return t2.getPriority() - t1.getPriority();
1059
            }
1060
        });
1061
        if (logger.isInfoEnabled()) {
1062
            logger.info("Found andami-themes in:");
1063
            for (Theme theme : themes) {
1064
                logger.info(" - " + theme.getPriority() + ", " + theme.getSource().getAbsolutePath());
1065
            }
1066
        }
1067
        Theme theme = themes.get(0);
1068
        logger.info("Using theme '" + theme.getSource() + "'.");
1069
        return theme;
1070
    }
1071

    
1072
    /**
1073
     * Establece los datos que tengamos guardados respecto de la configuracion
1074
     * del proxy.
1075
     */
1076
    private void configureProxy() {
1077
        String host = prefs.get("firewall.http.host", "");
1078
        String port = prefs.get("firewall.http.port", "");
1079

    
1080
        System.getProperties().put("http.proxyHost", host);
1081
        System.getProperties().put("http.proxyPort", port);
1082

    
1083
        // Ponemos el usuario y clave del proxy, si existe
1084
        String proxyUser = prefs.get("firewall.http.user", null);
1085
        String proxyPassword = prefs.get("firewall.http.password", null);
1086
        if (proxyUser != null) {
1087
            System.getProperties().put("http.proxyUserName", proxyUser);
1088
            System.getProperties().put("http.proxyPassword", proxyPassword);
1089

    
1090
            Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
1091
        } else {
1092
            Authenticator.setDefault(new ProxyAuth("", ""));
1093
        }
1094
    }
1095

    
1096
    /**
1097
     * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana
1098
     * principal de Andami. TODO Pendiente de ver como se asigna un
1099
     * pluginServices para el launcher.
1100
     *
1101
     * @author LWS
1102
     */
1103
    private void restoreMDIStatus(XMLEntity xml) {
1104
        if (xml == null) {
1105
            xml = new XMLEntity();
1106
        }
1107
        // ====================================
1108
        // restore frame size
1109
        Dimension sz = new Dimension(
1110
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[0],
1111
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[1]);
1112
        if (xml.contains(MainFrame.MAIN_FRAME_SIZE)) {
1113
            int[] wh = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_SIZE);
1114
            sz = new Dimension(wh[0], wh[1]);
1115
        }
1116
        frame.setSize(sz);
1117
        // ==========================================
1118
        // restore frame location
1119
        Point pos = new Point(
1120
                MainFrame.MAIN_FRAME_POS_DEFAULT[0],
1121
                MainFrame.MAIN_FRAME_POS_DEFAULT[1]);
1122
        if (xml.contains(MainFrame.MAIN_FRAME_POS)) {
1123
            int[] xy = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_POS);
1124
            pos = new Point(xy[0], xy[1]);
1125
        }
1126
        frame.setLocation(pos);
1127
        // =============================================
1128
        // restore frame state (Maximized, minimized, etc);
1129
        int state = MainFrame.MAIN_FRAME_EXT_STATE_DEFAULT;
1130
        if (xml.contains(MainFrame.MAIN_FRAME_EXT_STATE)) {
1131
            state = xml.getIntProperty(MainFrame.MAIN_FRAME_EXT_STATE);
1132
        }
1133
        frame.setExtendedState(state);
1134
    }
1135

    
1136
    private XMLEntity saveMDIStatus() {
1137
        XMLEntity xml = new XMLEntity();
1138
        // save frame size
1139
        int[] wh = new int[2];
1140
        wh[0] = frame.getWidth();
1141
        wh[1] = frame.getHeight();
1142
        xml.putProperty(MainFrame.MAIN_FRAME_SIZE, wh);
1143
        // save frame location
1144
        int[] xy = new int[2];
1145
        xy[0] = frame.getX();
1146
        xy[1] = frame.getY();
1147
        xml.putProperty(MainFrame.MAIN_FRAME_POS, xy);
1148
        // save frame status
1149
        xml.putProperty(MainFrame.MAIN_FRAME_EXT_STATE,
1150
                frame.getExtendedState());
1151
        return xml;
1152
    }
1153

    
1154
    private boolean validJVM() {
1155
        if (!SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_4)) {
1156
            logger.warn("gvSIG requires Java version 1.4 or higher.");
1157
            logger.warn("The Java HOME is '" + SystemUtils.getJavaHome().getAbsolutePath() + "'.");
1158
            return false;
1159
        }
1160
        if (SystemUtils.isJavaAwtHeadless()) {
1161
            logger.warn("The java used by gvSIG does not contain the libraries for access to the graphical interface (AWT-headless)");
1162
            logger.warn("The Java HOME is '" + SystemUtils.getJavaHome().getAbsolutePath() + "'.");
1163
            return false;
1164
        }
1165
        return true;
1166
    }
1167

    
1168
    private void loadPluginsPersistence() throws ConfigurationException {
1169
        XMLEntity entity = persistenceFromXML();
1170

    
1171
        for (int i = 0; i < entity.getChildrenCount(); i++) {
1172
            XMLEntity plugin = entity.getChild(i);
1173
            String pName = plugin
1174
                    .getStringProperty("com.iver.andami.pluginName");
1175

    
1176
            if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
1177
                pName = "org.gvsig.app";
1178
            }
1179
            if (pluginsServices.get(pName) != null) {
1180
                ((PluginServices) pluginsServices.get(pName))
1181
                        .setPersistentXML(plugin);
1182
            } else {
1183
                if (pName.startsWith("Andami.Launcher")) {
1184
                    restoreMDIStatus(plugin);
1185
                }
1186
            }
1187
        }
1188
    }
1189

    
1190
    /**
1191
     * Salva la persistencia de los plugins.
1192
     *
1193
     * @author LWS
1194
     */
1195
    private void savePluginPersistence() {
1196
        Iterator<String> i = pluginsConfig.keySet().iterator();
1197

    
1198
        XMLEntity entity = new XMLEntity();
1199

    
1200
        while (i.hasNext()) {
1201
            String pName = i.next();
1202
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
1203
            XMLEntity ent = ps.getPersistentXML();
1204

    
1205
            if (ent != null) {
1206
                ent.putProperty("com.iver.andami.pluginName", pName);
1207
                entity.addChild(ent);
1208
            }
1209
        }
1210
        XMLEntity ent = saveMDIStatus();
1211
        if (ent != null) {
1212
            ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
1213
            entity.addChild(ent);
1214
        }
1215
        try {
1216
            persistenceToXML(entity);
1217
        } catch (ConfigurationException e1) {
1218
            this
1219
                    .addError(
1220
                            Messages
1221
                            .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1222
                            e1);
1223
        }
1224
    }
1225

    
1226
    private void installPluginsLabels() {
1227
        Iterator<String> i = pluginsConfig.keySet().iterator();
1228

    
1229
        while (i.hasNext()) {
1230
            String name = i.next();
1231
            PluginConfig pc = pluginsConfig.get(name);
1232
            PluginServices ps = (PluginServices) pluginsServices.get(name);
1233

    
1234
            LabelSet[] ls = pc.getLabelSet();
1235

    
1236
            for (int j = 0; j < ls.length; j++) {
1237
                PluginClassLoader loader = ps.getClassLoader();
1238

    
1239
                try {
1240
                    Class clase = loader.loadClass(ls[j].getClassName());
1241
                    frame.setStatusBarLabels(clase, ls[j].getLabel());
1242
                } catch (Throwable e) {
1243
                    this.addError(
1244
                            Messages.getString("Launcher.labelset_class"), e);
1245
                }
1246
            }
1247
        }
1248
    }
1249

    
1250
    private String configureSkin(XMLEntity xml, String defaultSkin) {
1251
        if (defaultSkin == null) {
1252
            for (int i = 0; i < xml.getChildrenCount(); i++) {
1253
                if (xml.getChild(i).contains("Skin-Selected")) {
1254
                    String className = xml.getChild(i).getStringProperty(
1255
                            "Skin-Selected");
1256
                    return className;
1257
                }
1258
            }
1259
        }
1260
        // return "com.iver.core.mdiManager.NewSkin";
1261
        return defaultSkin;
1262
    }
1263

    
1264
    private void fixSkin(SkinExtension skinExtension,
1265
            PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1266
        // now insert the skin selected.
1267
        MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1268
                // MDIManagerFactory.setSkinExtension(se,
1269
        // ps.getClassLoader());
1270

    
1271
        Class<? extends IExtension> skinClass;
1272

    
1273
        try {
1274
            skinClass = (Class<? extends IExtension>) pluginClassLoader
1275
                    .loadClass(skinExtension.getClassName());
1276

    
1277
            IExtension skinInstance = skinClass.newInstance();
1278
            ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1279
                    skinInstance, ExtensionDecorator.INACTIVE);
1280
            classesExtensions.put(skinClass, newExtensionDecorator);
1281
        } catch (ClassNotFoundException e) {
1282
            logger.error(Messages
1283
                    .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1284
                    e);
1285
            throw new MDIManagerLoadException(e);
1286
        } catch (InstantiationException e) {
1287
            logger
1288
                    .error(
1289
                            Messages
1290
                            .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1291
                            e);
1292
            throw new MDIManagerLoadException(e);
1293
        } catch (IllegalAccessException e) {
1294
            logger
1295
                    .error(
1296
                            Messages
1297
                            .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1298
                            e);
1299
            throw new MDIManagerLoadException(e);
1300
        }
1301

    
1302
    }
1303

    
1304
    /**
1305
     * DOCUMENT ME!
1306
     *
1307
     * @throws MDIManagerLoadException
1308
     */
1309
    private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1310
        XMLEntity entity = null;
1311
        try {
1312
            entity = persistenceFromXML();
1313
        } catch (ConfigurationException e1) {
1314
            // TODO Auto-generated catch block
1315
            e1.printStackTrace();
1316
        }
1317
        Iterator<String> i = pluginsConfig.keySet().iterator();
1318

    
1319
        SkinExtension skinExtension = null;
1320
        PluginClassLoader pluginClassLoader = null;
1321
        List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1322
        while (i.hasNext()) {
1323
            String name = i.next();
1324
            PluginConfig pc = pluginsConfig.get(name);
1325
            PluginServices ps = pluginsServices.get(name);
1326

    
1327
            if (pc.getExtensions().getSkinExtension() != null) {
1328
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1329
                // logger.warn(Messages.getString(
1330
                // "Launcher.Dos_skin_extension"));
1331
                // }
1332

    
1333
                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1334
                for (int numExten = 0; numExten < se.length; numExten++) {
1335
                    skinExtensions.add(se[numExten]);
1336
                }
1337
                for (int j = 0; j < se.length; j++) {
1338
                    String configuredSkin = this.configureSkin(entity,
1339
                            defaultSkin);
1340
                    if ((configuredSkin != null)
1341
                            && configuredSkin.equals(se[j].getClassName())) {
1342
                        skinExtension = se[j];
1343
                        pluginClassLoader = ps.getClassLoader();
1344
                    }
1345
                }
1346
            }
1347
        }
1348

    
1349
        if ((skinExtension != null) && (pluginClassLoader != null)) {
1350
            // configured skin was found
1351
            fixSkin(skinExtension, pluginClassLoader);
1352
        } else {
1353
            if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1354
                // try first NewSkin (from CorePlugin)
1355
                skinPlugin("com.iver.core.mdiManager.NewSkin");
1356
            } else if (skinExtensions.size() > 0) {
1357
                // try to load the first skin found
1358
                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1359
                skinPlugin((String) se.getClassName());
1360
            } else {
1361
                throw new MDIManagerLoadException("No Skin-Extension installed");
1362
            }
1363
        }
1364

    
1365
    }
1366

    
1367
    private static void frameIcon(Theme theme) {
1368
        Iterator<String> i = pluginsConfig.keySet().iterator();
1369

    
1370
        while (i.hasNext()) {
1371
            String pName = i.next();
1372
            PluginConfig pc = pluginsConfig.get(pName);
1373
            if (pc.getIcon() != null) {
1374
                if (theme.getIcon() != null) {
1375
                    frame.setIconImage(theme.getIcon().getImage());
1376
                } else {
1377

    
1378
                    ImageIcon icon = PluginServices.getIconTheme().get(
1379
                            pc.getIcon().getSrc());
1380
                    frame.setIconImage(icon.getImage());
1381

    
1382
                }
1383
                if (theme.getName() != null) {
1384
                    frame.setTitlePrefix(theme.getName());
1385
                } else {
1386
                    frame.setTitlePrefix(pc.getIcon().getText());
1387
                }
1388
                if (theme.getBackgroundImage() != null) {
1389

    
1390
                    PluginServices.getMDIManager().setBackgroundImage(
1391
                            theme.getBackgroundImage(), theme.getTypeDesktop());
1392
                }
1393
            }
1394
        }
1395
    }
1396

    
1397
    private void initializeExtensions() {
1398

    
1399
        List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1400
                pluginsOrdered.size());
1401
        classLoaders.add(getClass().getClassLoader());
1402
        Iterator<String> iter = pluginsOrdered.iterator();
1403

    
1404
                // logger.debug("Initializing plugins libraries: ");
1405
        // while (iter.hasNext()) {
1406
        // String pName = (String) iter.next();
1407
        // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1408
        // classLoaders.add(ps.getClassLoader());
1409
        // }
1410
        //
1411
        // // Create the libraries initializer and
1412
        // // initialize the plugin libraries
1413
        // new DefaultLibrariesInitializer(
1414
        // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1415
        // .fullInitialize();
1416
        //
1417
        // // Remove them all, we don't need them anymore
1418
        // classLoaders.clear();
1419
        // classLoaders = null;
1420
        logger.info("Initializing plugins: ");
1421
        // iter = pluginsOrdered.iterator();
1422
        while (iter.hasNext()) {
1423
            String pName = (String) iter.next();
1424
            logger.info("Initializing plugin " + pName);
1425
            PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1426
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
1427

    
1428
            Extension[] exts = pc.getExtensions().getExtension();
1429

    
1430
            TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1431
                    new ExtensionComparator());
1432

    
1433
            for (int j = 0; j < exts.length; j++) {
1434
                if (!exts[j].getActive()) {
1435
                    continue;
1436
                }
1437

    
1438
                if (orderedExtensions.contains(exts[j])) {
1439
                    logger.warn("Two extensions with the same priority ("
1440
                            + exts[j].getClassName() + ")");
1441
                }
1442

    
1443
                orderedExtensions.add(exts[j]);
1444
            }
1445

    
1446
            Iterator<Extension> e = orderedExtensions.iterator();
1447

    
1448
            logger.info("Initializing extensions of plugin " + pName + ": ");
1449
            while (e.hasNext()) {
1450
                Extension extension = e.next();
1451
                org.gvsig.andami.plugins.IExtension extensionInstance;
1452

    
1453
                try {
1454
                    logger.info("Initializing " + extension.getClassName()
1455
                            + "...");
1456
                    message(extension.getClassName() + "...");
1457
                    Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1458
                            .getClassLoader().loadClass(
1459
                                    extension.getClassName());
1460
                    extensionInstance = extensionClass.newInstance();
1461
                    if (extensionInstance instanceof org.gvsig.andami.plugins.Extension) {
1462
                        ((org.gvsig.andami.plugins.Extension) extensionInstance).setPlugin(ps);
1463
                    } else {
1464
                        logger.warn("The extension " + extensionClass.getName() + " don't extends of Extension.");
1465
                    }
1466

    
1467
                                        // CON DECORATOR
1468
                    // ANTES: classesExtensions.put(extensionClass,
1469
                    // extensionInstance);
1470
                    // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1471
                    // instancia para
1472
                    // poder ampliar con nuevas propiedades (AlwaysVisible, por
1473
                    // ejemplo)
1474
                    // Para crear la nueva clase ExtensionDecorator, le pasamos
1475
                    // como par?metro
1476
                    // la extensi?n original que acabamos de crear
1477
                    // 0-> Inactivo, controla la extension
1478
                    // 1-> Siempre visible
1479
                    // 2-> Invisible
1480
                    ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1481
                            extensionInstance, ExtensionDecorator.INACTIVE);
1482
                    classesExtensions
1483
                            .put(extensionClass, newExtensionDecorator);
1484

    
1485
                    extensionInstance.initialize();
1486
                    extensions.add(extensionInstance);
1487

    
1488
                } catch (NoClassDefFoundError e1) {
1489
                    this.addError("Can't find class extension ("
1490
                            + extension.getClassName() + ")", e1);
1491
                } catch (Throwable e1) {
1492
                    this.addError("Can't initialize extension '"
1493
                            + extension.getClassName() + "'.", e1);
1494
                }
1495
            }
1496
        }
1497
    }
1498

    
1499
    private void postInitializeExtensions() {
1500
        logger.info("PostInitializing extensions: ");
1501

    
1502
        for (int i = 0; i < extensions.size(); i++) {
1503
            org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1504
                    .get(i);
1505
            String name = extensionInstance.getClass().getName();
1506
            logger.info("PostInitializing " + name + "...");
1507
            message(name + "...");
1508
            try {
1509
                extensionInstance.postInitialize();
1510
            } catch (Throwable ex) {
1511
                this.addError("postInitialize of extension '"
1512
                        + extensionInstance.getClass().getName() + "' failed",
1513
                        ex);
1514
            }
1515
        }
1516
    }
1517

    
1518
    private void registerActionOfExtensions(ActionInfoManager actionManager,
1519
            Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1520
        ActionInfo actionInfo;
1521
        while (extensiones.hasMoreElements()) {
1522
            SkinExtensionType extension = extensiones.nextElement();
1523
            Class<? extends IExtension> classExtension;
1524
            try {
1525
                classExtension = (Class<? extends IExtension>) loader
1526
                        .loadClass(extension.getClassName());
1527

    
1528
                Enumeration<Action> actions = extension.enumerateAction();
1529
                while (actions.hasMoreElements()) {
1530
                    Action action = actions.nextElement();
1531
                    if (action.getName() == null) {
1532
                        logger.info("invalid action name (null) in " + extension.getClassName() + " of " + loader.toString());
1533
                    } else {
1534
                        actionInfo = actionManager.createAction(
1535
                                classExtension, action.getName(),
1536
                                action.getLabel(), action.getActionCommand(),
1537
                                action.getIcon(), action.getAccelerator(), action.getPosition(),
1538
                                action.getTooltip());
1539
                        actionManager.registerAction(actionInfo);
1540
                        if (action.getPosition() < 100000000) {
1541
                            logger.info("Invalid position in action (" + actionInfo.toString() + ").");
1542
                            action.setPosition(action.getPosition() + 1000000000);
1543
                        }
1544
                    }
1545
                }
1546

    
1547
                Enumeration<Menu> menus = extension.enumerateMenu();
1548
                while (menus.hasMoreElements()) {
1549
                    Menu menu = menus.nextElement();
1550
                    if (!menu.getIs_separator()) {
1551
                        actionInfo = actionManager.createAction(
1552
                                classExtension, menu.getName(), menu.getText(),
1553
                                menu.getActionCommand(), menu.getIcon(),
1554
                                menu.getKey(), menu.getPosition(),
1555
                                menu.getTooltip());
1556
                        actionInfo = actionManager.registerAction(actionInfo);
1557
                        if (actionInfo != null) {
1558
                            menu.setActionCommand(actionInfo.getCommand());
1559
                            menu.setTooltip(actionInfo.getTooltip());
1560
                            menu.setIcon(actionInfo.getIconName());
1561
                            menu.setPosition(actionInfo.getPosition());
1562
                            menu.setKey(actionInfo.getAccelerator());
1563
                            menu.setName(actionInfo.getName());
1564
                        }
1565
                    }
1566
                    if (menu.getPosition() < 100000000) {
1567
                        logger.info("Invalid position in menu (" + menu.getText() + ").");
1568
                        menu.setPosition(menu.getPosition() + 1000000000);
1569
                    }
1570

    
1571
                }
1572
                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1573
                while (toolBars.hasMoreElements()) {
1574
                    ToolBar toolBar = toolBars.nextElement();
1575

    
1576
                    Enumeration<ActionTool> actionTools = toolBar
1577
                            .enumerateActionTool();
1578
                    while (actionTools.hasMoreElements()) {
1579
                        ActionTool actionTool = actionTools.nextElement();
1580
                        actionInfo = actionManager.createAction(
1581
                                classExtension, actionTool.getName(),
1582
                                actionTool.getText(),
1583
                                actionTool.getActionCommand(),
1584
                                actionTool.getIcon(),
1585
                                null,
1586
                                actionTool.getPosition(),
1587
                                actionTool.getTooltip());
1588
                        actionInfo = actionManager.registerAction(actionInfo);
1589
                        if (actionInfo != null) {
1590
                            actionTool.setActionCommand(actionInfo.getCommand());
1591
                            actionTool.setTooltip(actionInfo.getTooltip());
1592
                            actionTool.setIcon(actionInfo.getIconName());
1593
                            actionTool.setPosition(actionInfo.getPosition());
1594
                            actionTool.setName(actionInfo.getName());
1595
                        }
1596
                    }
1597

    
1598
                    Enumeration<SelectableTool> selectableTool = toolBar
1599
                            .enumerateSelectableTool();
1600
                    while (selectableTool.hasMoreElements()) {
1601
                        SelectableTool actionTool = selectableTool
1602
                                .nextElement();
1603
                        actionInfo = actionManager.createAction(
1604
                                classExtension, actionTool.getName(),
1605
                                actionTool.getText(),
1606
                                actionTool.getActionCommand(),
1607
                                actionTool.getIcon(),
1608
                                null,
1609
                                actionTool.getPosition(),
1610
                                actionTool.getTooltip());
1611
                        actionInfo = actionManager.registerAction(actionInfo);
1612
                        if (actionInfo != null) {
1613
                            actionTool.setActionCommand(actionInfo.getCommand());
1614
                            actionTool.setTooltip(actionInfo.getTooltip());
1615
                            actionTool.setIcon(actionInfo.getIconName());
1616
                            actionTool.setPosition(actionInfo.getPosition());
1617
                            actionTool.setName(actionInfo.getName());
1618
                        }
1619
                    }
1620
                }
1621
            } catch (ClassNotFoundException e) {
1622
                logger.warn(
1623
                        "Can't register actions of extension '"
1624
                        + extension.getClassName() + "'", e);
1625
            }
1626
        }
1627
    }
1628

    
1629
    @SuppressWarnings("unchecked")
1630
    private void registerActions() {
1631
        logger.info("registerActions");
1632

    
1633
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1634
        Iterator<String> it = pluginsConfig.keySet().iterator();
1635

    
1636
        while (it.hasNext()) {
1637
            String pluginName = it.next();
1638
            PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1639
            PluginServices pluginService = pluginsServices.get(pluginName);
1640
            PluginClassLoader loader = pluginService.getClassLoader();
1641

    
1642
            logger.info("registerActions of plugin '" + pluginName + "'.");
1643

    
1644
            Extensions extensionConfig = pluginConfig.getExtensions();
1645

    
1646
            Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1647
            registerActionOfExtensions(actionManager, extensiones, loader);
1648

    
1649
            Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1650
            registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1651

    
1652
            PopupMenus pluginPopupMenus = pluginConfig.getPopupMenus();
1653
            if (pluginPopupMenus != null) {
1654
                PopupMenu[] menus1 = pluginPopupMenus.getPopupMenu();
1655
                for (int j = 0; j < menus1.length; j++) {
1656
                    PopupMenu popupMenu = menus1[j];
1657
                    Enumeration<Menu> menus2 = popupMenu.enumerateMenu();
1658
                    while (menus2.hasMoreElements()) {
1659
                        Menu menu = menus2.nextElement();
1660
                        if (!menu.getIs_separator()) {
1661
                            if (menu.getName() == null) {
1662
                                logger.info("Null name for popmenu '" + menu.getText() + "' in plugin " + pluginService.getPluginName());
1663
                            } else {
1664
                                ActionInfo actionInfo = actionManager.getAction(menu.getName());
1665
                                if (actionInfo != null) {
1666
                                    menu.setActionCommand(actionInfo.getCommand());
1667
                                    menu.setTooltip(actionInfo.getTooltip());
1668
                                    menu.setIcon(actionInfo.getIconName());
1669
                                    menu.setPosition(actionInfo.getPosition());
1670
                                    menu.setText(actionInfo.getLabel());
1671
                                    menu.setKey(actionInfo.getAccelerator());
1672
                                }
1673
                            }
1674
                        }
1675
                    }
1676
                }
1677
            }
1678

    
1679
        }
1680
    }
1681

    
1682
    private TreeSet<SortableMenu> getOrderedMenus() {
1683

    
1684
        TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1685
                new MenuComparator());
1686

    
1687
        Iterator<String> i = pluginsConfig.keySet().iterator();
1688

    
1689
        while (i.hasNext()) {
1690
            String pName = i.next();
1691
            try {
1692
                PluginServices ps = pluginsServices.get(pName);
1693
                PluginConfig pc = pluginsConfig.get(pName);
1694

    
1695
                Extension[] exts = pc.getExtensions().getExtension();
1696

    
1697
                for (int j = 0; j < exts.length; j++) {
1698
                    if (!exts[j].getActive()) {
1699
                        continue;
1700
                    }
1701

    
1702
                    Menu[] menus = exts[j].getMenu();
1703

    
1704
                    for (int k = 0; k < menus.length; k++) {
1705
                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1706
                                exts[j], menus[k]);
1707

    
1708
                        if (orderedMenus.contains(sm)) {
1709
                            this
1710
                                    .addError(Messages
1711
                                            .getString("Launcher.Two_menus_with_the_same_position")
1712
                                            + " - "
1713
                                            + menus[k].getText()
1714
                                            + " - " + exts[j].getClassName());
1715
                        }
1716

    
1717
                        orderedMenus.add(sm);
1718
                    }
1719
                }
1720

    
1721
                // Se instalan las extensiones de MDI
1722
                SkinExtension[] skinExts = pc.getExtensions()
1723
                        .getSkinExtension();
1724
                for (int j = 0; j < skinExts.length; j++) {
1725

    
1726
                    if (skinExts[j] != null) {
1727
                        Menu[] menu = skinExts[j].getMenu();
1728

    
1729
                        for (int k = 0; k < menu.length; k++) {
1730
                            SortableMenu sm = new SortableMenu(ps
1731
                                    .getClassLoader(), skinExts[j], menu[k]);
1732

    
1733
                            if (orderedMenus.contains(sm)) {
1734
                                this
1735
                                        .addError(Messages
1736
                                                .getString("Launcher.Two_menus_with_the_same_position")
1737
                                                + skinExts[j].getClassName());
1738
                            }
1739

    
1740
                            orderedMenus.add(sm);
1741
                        }
1742
                    }
1743
                }
1744

    
1745
            } catch (Throwable e) {
1746
                addError("Error initializing menus of plugin '" + pName + "'",
1747
                        e);
1748
            }
1749

    
1750
        }
1751

    
1752
        return orderedMenus;
1753
    }
1754

    
1755
    private void installPluginsMenus() {
1756
        logger.info("installPluginsMenus");
1757

    
1758
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1759

    
1760
        // Se itera por los menus ordenados
1761
        Iterator<SortableMenu> e = orderedMenus.iterator();
1762

    
1763
        // Se ordenan los menues
1764
        while (e.hasNext()) {
1765
            try {
1766
                SortableMenu sm = e.next();
1767
                logger.debug(sm.menu.getPosition() + ":" + sm.menu.getText() + ":" + sm.loader.getPluginName() + ":" + sm.extension.getClassName());
1768
                frame.addMenu(sm.loader, sm.extension, sm.menu);
1769
            } catch (Throwable ex) {
1770
                this.addError(
1771
                        Messages.getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1772
                        ex
1773
                );
1774
            }
1775
        }
1776
    }
1777

    
1778
    public class PluginMenuItem {
1779

    
1780
        private Menu menu;
1781
        private PluginClassLoader loader;
1782
        private SkinExtensionType extension;
1783

    
1784
        PluginMenuItem(PluginClassLoader loader,
1785
                SkinExtensionType extension, Menu menu) {
1786
            this.menu = menu;
1787
            this.loader = loader;
1788
            this.extension = extension;
1789
        }
1790

    
1791
        public PluginServices getPlugin() {
1792
            String pluginName = loader.getPluginName();
1793
            return PluginServices.getPluginServices(pluginName);
1794
        }
1795

    
1796
        public String getExtensionName() {
1797
            return this.extension.getClassName();
1798
        }
1799

    
1800
        public IExtension getExtension() {
1801
            Class<?> extensionClass;
1802
            try {
1803
                extensionClass = loader.loadClass(this.extension.getClassName());
1804
            } catch (ClassNotFoundException e) {
1805
                return null;
1806
            }
1807
            return PluginServices.getExtension(extensionClass);
1808
        }
1809

    
1810
        public String getText() {
1811
            return this.menu.getText();
1812
        }
1813

    
1814
        public long getPosition() {
1815
            return this.menu.getPosition();
1816
        }
1817

    
1818
        public String getName() {
1819
            return this.menu.getName();
1820
        }
1821

    
1822
        public boolean isParent() {
1823
            return menu.getIs_separator();
1824
        }
1825

    
1826
        public String getPluginName() {
1827
            return this.loader.getPluginName();
1828
        }
1829

    
1830
        public ActionInfo getAction() {
1831
            ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1832
            return manager.getAction(this.menu.getName());
1833
        }
1834
    }
1835

    
1836
    public List<PluginMenuItem> getPluginMenuItems() {
1837
        List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1838

    
1839
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1840
        Iterator<SortableMenu> e = orderedMenus.iterator();
1841
        while (e.hasNext()) {
1842
            SortableMenu sm = e.next();
1843
            PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1844
            menuItems.add(item);
1845
        }
1846
        return menuItems;
1847
    }
1848

    
1849
    /**
1850
     * Installs the menus, toolbars, actiontools, selectable toolbars and
1851
     * combos. The order in which they are shown is determined here.
1852
     */
1853
    private void installPluginsControls() {
1854
        logger.info("installPluginsControls (toolbars)");
1855

    
1856
        Iterator<String> i = pluginsConfig.keySet().iterator();
1857

    
1858
        Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1859
        Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1860
        Set<Extension> orderedExtensions = new TreeSet<Extension>(
1861
                new ExtensionComparator());
1862

    
1863
                // First of all, sort the extensions.
1864
        // We need to iterate on the plugins, and iterate on each plugin's
1865
        // extensions
1866
        // (each plugin may contain one or more extensions)
1867
        while (i.hasNext()) { // iterate on the plugins
1868
            String pName = i.next();
1869
            try {
1870
                PluginConfig pc = pluginsConfig.get(pName);
1871
                PluginServices ps = pluginsServices.get(pName);
1872

    
1873
                Extension[] exts = pc.getExtensions().getExtension();
1874

    
1875
                for (int j = 0; j < exts.length; j++) { // iterate on the
1876
                    // extensions
1877
                    String cname = "unknow";
1878
                    try {
1879
                        cname = exts[j].getClassName();
1880
                        if (exts[j].getActive()
1881
                                && !cname.equals(LibraryExtension.class
1882
                                        .getName())) {
1883
                            if (orderedExtensions.contains(exts[j])) {
1884
                                this
1885
                                        .addError(Messages
1886
                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1887
                                                + cname);
1888
                            }
1889

    
1890
                            orderedExtensions.add(exts[j]);
1891
                            extensionPluginServices.put(exts[j], ps);
1892
                            extensionPluginConfig.put(exts[j], pc);
1893
                        }
1894
                    } catch (Throwable e) {
1895
                        addError("Error initializing controls of plugin '"
1896
                                + pName + "' extension '" + cname + "'", e);
1897
                    }
1898
                }
1899
            } catch (Throwable e) {
1900
                addError("Error initializing controls of plugin '" + pName
1901
                        + "'", e);
1902
            }
1903
        }
1904

    
1905
        TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1906
                new ToolComparator());
1907
        Iterator<Extension> e = orderedExtensions.iterator();
1908

    
1909
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1910
        // selectabletools)
1911
        // and load the combo-scales and combo-buttons for the status bar
1912
        while (e.hasNext()) {
1913
            Extension ext = e.next();
1914
            String extName = "unknow";
1915
            try {
1916
                extName = ext.getClassName();
1917
                ToolBar[] toolbars = ext.getToolBar();
1918

    
1919
                // get tools from toolbars
1920
                for (int k = 0; k < toolbars.length; k++) {
1921
                    ActionTool[] tools = toolbars[k].getActionTool();
1922

    
1923
                    for (int t = 0; t < tools.length; t++) {
1924
                        SortableTool sm = new SortableTool(
1925
                                (extensionPluginServices.get(ext))
1926
                                .getClassLoader(), ext, toolbars[k],
1927
                                tools[t]);
1928
                        orderedTools.add(sm);
1929
                    }
1930

    
1931
                    SelectableTool[] sTools = toolbars[k].getSelectableTool();
1932

    
1933
                    for (int t = 0; t < sTools.length; t++) {
1934
                        SortableTool sm = new SortableTool(
1935
                                (extensionPluginServices.get(ext))
1936
                                .getClassLoader(), ext, toolbars[k],
1937
                                sTools[t]);
1938
                        orderedTools.add(sm);
1939
                    }
1940
                }
1941

    
1942
                // get controls for statusBar
1943
                PluginServices ps = extensionPluginServices.get(ext);
1944
                PluginClassLoader loader = ps.getClassLoader();
1945

    
1946
                // ArrayList componentList = new ArrayList();
1947
                ComboScale[] comboScaleArray = ext.getComboScale();
1948
                for (int k = 0; k < comboScaleArray.length; k++) {
1949
                    org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1950
                    String label = comboScaleArray[k].getLabel();
1951
                    if (label != null) {
1952
                        combo.setLabel(label);
1953
                    }
1954
                    String name = comboScaleArray[k].getName();
1955
                    if (name != null) {
1956
                        combo.setName(name);
1957
                    }
1958
                    String[] elementsString = ((String) comboScaleArray[k]
1959
                            .getElements()).split(";");
1960
                    long[] elements = new long[elementsString.length];
1961
                    for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
1962
                        try {
1963
                            elements[currentElem] = Long
1964
                                    .parseLong(elementsString[currentElem]);
1965
                        } catch (NumberFormatException nfex1) {
1966
                            this
1967
                                    .addError(ext.getClassName()
1968
                                            + " -- "
1969
                                            + Messages
1970
                                            .getString("error_parsing_comboscale_elements"));
1971
                            elements[currentElem] = 0;
1972
                        }
1973
                    }
1974
                    combo.setItems(elements);
1975
                    try {
1976
                        long value = Long.parseLong((String) comboScaleArray[k]
1977
                                .getValue());
1978
                        combo.setScale(value);
1979
                    } catch (NumberFormatException nfex2) {
1980
                        this
1981
                                .addError(ext.getClassName()
1982
                                        + " -- "
1983
                                        + Messages
1984
                                        .getString("error_parsing_comboscale_value"));
1985
                    }
1986
                    try {
1987
                        frame.addStatusBarControl(loader.loadClass(ext
1988
                                .getClassName()), combo);
1989
                    } catch (ClassNotFoundException e1) {
1990
                        this
1991
                                .addError(
1992
                                        Messages
1993
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1994
                                        e1);
1995
                    }
1996
                }
1997

    
1998
                ComboButton[] comboButtonArray = ext.getComboButton();
1999
                for (int k = 0; k < comboButtonArray.length; k++) {
2000
                    ComboButtonElement[] elementList = comboButtonArray[k]
2001
                            .getComboButtonElement();
2002
                    org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
2003
                    String name = comboButtonArray[k].getName();
2004
                    if (name != null) {
2005
                        combo.setName(name);
2006
                    }
2007
                    for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
2008
                        ComboButtonElement element = elementList[currentElement];
2009
                        ImageIcon icon;
2010
                        URL iconLocation = loader
2011
                                .getResource(element.getIcon());
2012
                        if (iconLocation == null) {
2013
                            this.addError(Messages.getString("Icon_not_found_")
2014
                                    + element.getIcon());
2015
                        } else {
2016
                            icon = new ImageIcon(iconLocation);
2017
                            JButton button = new JButton(icon);
2018
                            combo.addButton(button);
2019
                            button.setActionCommand(element.getActionCommand());
2020
                        }
2021
                    }
2022
                    try {
2023
                        frame.addStatusBarControl(loader.loadClass(ext
2024
                                .getClassName()), combo);
2025
                    } catch (ClassNotFoundException e1) {
2026
                        this
2027
                                .addError(
2028
                                        Messages
2029
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2030
                                        e1);
2031
                    }
2032
                }
2033
            } catch (Throwable e2) {
2034
                addError(
2035
                        "Error initializing tools and status bars of extension '"
2036
                        + extName + "'", e2);
2037
            }
2038
        }
2039

    
2040
                // Add the tools from MDI extensions to the ordered tool-list, so that
2041
        // we get a sorted list containing all the tools
2042
        i = pluginsConfig.keySet().iterator();
2043
        while (i.hasNext()) {
2044
            String pName = (String) i.next();
2045
            try {
2046
                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
2047
                PluginServices ps = (PluginServices) pluginsServices.get(pName);
2048

    
2049
                SkinExtension[] skinExts = pc.getExtensions()
2050
                        .getSkinExtension();
2051
                for (int j = 0; j < skinExts.length; j++) {
2052

    
2053
                    if (skinExts[j] != null) {
2054
                        ToolBar[] toolbars = skinExts[j].getToolBar();
2055

    
2056
                        for (int k = 0; k < toolbars.length; k++) {
2057
                            ActionTool[] tools = toolbars[k].getActionTool();
2058

    
2059
                            for (int t = 0; t < tools.length; t++) {
2060
                                SortableTool stb = new SortableTool(ps
2061
                                        .getClassLoader(), skinExts[j],
2062
                                        toolbars[k], tools[t]);
2063
                                orderedTools.add(stb);
2064
                            }
2065

    
2066
                            SelectableTool[] sTools = toolbars[k]
2067
                                    .getSelectableTool();
2068

    
2069
                            for (int t = 0; t < sTools.length; t++) {
2070
                                SortableTool stb = new SortableTool(ps
2071
                                        .getClassLoader(), skinExts[j],
2072
                                        toolbars[k], sTools[t]);
2073
                                orderedTools.add(stb);
2074
                            }
2075
                        }
2076
                    }
2077
                }
2078
                // Install popup menus
2079
                PopupMenus pus = pc.getPopupMenus();
2080
                if (pus != null) {
2081
                    PopupMenu[] menus = pus.getPopupMenu();
2082
                    for (int j = 0; j < menus.length; j++) {
2083
                        String menuName = "(unknow)";
2084
                        try {
2085
                            menuName = menus[j].getName();
2086
                            frame.addPopupMenu(ps.getClassLoader(), menus[j]);
2087
                        } catch (Throwable ex) {
2088
                            addError("Error adding popup menu' " + menuName + "' in plugin '" + pName + "'.");
2089
                        }
2090
                    }
2091
                }
2092
            } catch (Throwable e3) {
2093
                addError("Error initializing skins of the plugin '" + pName
2094
                        + "'", e3);
2095
            }
2096
        }
2097

    
2098
                // loop on the ordered extension list, to add them to the interface in
2099
        // an ordered way
2100
        Iterator<SortableTool> t = orderedTools.iterator();
2101
        while (t.hasNext()) {
2102
            SortableTool stb = t.next();
2103
            try {
2104
                if (stb.actiontool != null) {
2105
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2106
                            stb.actiontool);
2107
                } else {
2108
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2109
                            stb.selectabletool);
2110
                }
2111
            } catch (ClassNotFoundException ex) {
2112
                this
2113
                        .addError(
2114
                                Messages
2115
                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
2116
                                ex);
2117
            } catch (Throwable e2) {
2118
                addError("Error adding tools to the interface of extension '"
2119
                        + stb.extension.getClassName() + "'", e2);
2120
            }
2121
        }
2122
    }
2123

    
2124
    /**
2125
     * Adds new plugins to the the andami-config file.
2126
     */
2127
    private void updateAndamiConfig() {
2128
        Set<String> olds = new HashSet<String>();
2129

    
2130
        Plugin[] plugins = andamiConfig.getPlugin();
2131

    
2132
        for (int i = 0; i < plugins.length; i++) {
2133
            olds.add(plugins[i].getName());
2134
        }
2135

    
2136
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2137

    
2138
        while (i.hasNext()) {
2139
            PluginServices ps = i.next();
2140

    
2141
            if (!olds.contains(ps.getPluginName())) {
2142
                Plugin p = new Plugin();
2143
                p.setName(ps.getPluginName());
2144
                p.setUpdate(false);
2145

    
2146
                andamiConfig.addPlugin(p);
2147
            }
2148
        }
2149
    }
2150

    
2151
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2152
        URL[] urls = null;
2153

    
2154
        String libfolderPath = pluginConfig.getLibraries().getLibraryDir();
2155
        File libFolderFile = new File(pluginConfig.getPluginFolder(), libfolderPath);
2156

    
2157
        File[] files = libFolderFile.listFiles(new FileFilter() {
2158

    
2159
            public boolean accept(File pathname) {
2160
                return (pathname.getName().toUpperCase().endsWith(".JAR")
2161
                        || pathname.getName().toUpperCase().endsWith(".ZIP"));
2162
            }
2163
        });
2164
        if (files == null) {
2165
            urls = new URL[0];
2166
        } else {
2167
            urls = new URL[files.length];
2168
            for (int j = 0; j < files.length; j++) {
2169
                try {
2170
                    urls[j] = new URL("file:" + files[j]);
2171
                } catch (MalformedURLException e) {
2172
                    logger.warn("Can't add file '" + files[j] + "' to the classpath of plugin '" + pluginConfig.getPluginName() + "'.");
2173
                }
2174
            }
2175
        }
2176
        return urls;
2177
    }
2178

    
2179
    private static class OrderedPlugins extends ArrayList<String> {
2180
        
2181
        private List<String> problems = new ArrayList<String>();
2182
        private int retries = 0;
2183
        private PluginsConfig pluginsConfig = null;
2184
        private List<String> deprcatedPluginNames = null;
2185
        
2186
        OrderedPlugins(PluginsConfig pluginsConfig, List<String>deprcatedPluginNames) {
2187
            super();
2188
            this.pluginsConfig = pluginsConfig;
2189
            this.deprcatedPluginNames = deprcatedPluginNames;
2190
            List<String> pluginNames = new ArrayList<String>();
2191
            for (String pluginName : pluginsConfig.keySet()) {
2192
                pluginNames.add(pluginName);
2193
            }
2194
            Collections.sort(pluginNames);
2195
            for (String pluginName : pluginNames) {
2196
                this.add(pluginName);
2197
            }
2198
        }
2199
        
2200
        public List<String> getProblems() {
2201
            return this.problems;
2202
        }
2203
 
2204
        private void addProblem(String msg) {
2205
           this.problems.add(msg);
2206
        }
2207
    
2208
        public boolean add(String pluginName) {
2209
            return this.add(pluginName,new ArrayList<String>());
2210
        }
2211
        
2212
        private boolean add(String pluginName, List<String>processing) {
2213
            pluginName = this.pluginsConfig.getMainKey(pluginName);
2214
            if( this.contains(pluginName) ) {
2215
                return true;
2216
            }
2217
            if( processing.contains(pluginName) ) {
2218
                this.addProblem("Dependencias ciclicas procesando '"+pluginName+"'.");
2219
                return true;
2220
            }
2221
            PluginConfig pluginConfig = this.pluginsConfig.get(pluginName);
2222
            Depends[] dependencies = pluginConfig.getDepends();
2223
            if( dependencies.length==0 ) {
2224
               super.add(pluginName);
2225
               return true;
2226
            }
2227
            if( this.retries > 100 ) {
2228
               this.addProblem("Posible dependencias ciclicas procesando '"+pluginName+"'." );
2229
               return false;
2230
            }
2231
            processing.add(pluginName);
2232
            boolean dependenciesAvailables = true;
2233
            for (Depends dependency : dependencies) {
2234
                String dependencyName = dependency.getPluginName();
2235
                if (deprcatedPluginNames.contains(dependencyName)) {
2236
                    this.addProblem("Plugin '" + pluginName + "' use a deprecated plugin name '" + dependencyName + "' as dependency. Must use '" + pluginsConfig.getMainKey(dependencyName) + "'.");
2237
                }                
2238
                PluginConfig dependencyConfig = this.pluginsConfig.get(dependencyName);
2239
                if( dependencyConfig == null) {
2240
                  if( dependency.getOptional() ) {
2241
                    this.addProblem("Plugin '" + pluginName + "', declare an optional dependency '" + dependencyName + "' that not found.");
2242
                    continue;
2243
                  }
2244
                  dependenciesAvailables = false;
2245
                  this.addProblem("Plugin '"+pluginName+"' declara a dependency '"+dependencyName+"' that not found.");
2246
                  continue;
2247
                }
2248
                this.retries++;
2249
                if( ! (this.add(dependencyName, processing)) ) {
2250
                  dependenciesAvailables = false;
2251
                }
2252
                this.retries--;
2253
            }
2254
            if( dependenciesAvailables ) {
2255
                super.add(pluginName);
2256
            } else {
2257
              this.addProblem("Plugin '"+pluginName+"' no disponible, alguna dependencia no resuelta.");
2258
              return false;
2259
            }
2260
            return true;
2261
        }      
2262
    }
2263
            
2264
    private void loadPluginServices() {
2265
        OrderedPlugins orderedPlugins = new OrderedPlugins(pluginsConfig, getDeprecatedPluginNames());
2266
        
2267
        if( !orderedPlugins.getProblems().isEmpty() ) {
2268
            for (String problem : orderedPlugins.getProblems()) {
2269
                logger.warn(problem);
2270
            }
2271
        }
2272

    
2273
        for (String pluginName : orderedPlugins) {
2274
            PluginConfig config = pluginsConfig.get(pluginName);
2275

    
2276
            URL[] urls = getPluginClasspathURLs(config);
2277
            
2278
            List<PluginClassLoader> loaders = new ArrayList<PluginClassLoader>();
2279
            for (Depends dependency : config.getDepends()) {
2280
                String dependencyName = dependency.getPluginName();
2281
                PluginServices dependencyPluginService = pluginsServices.get(dependencyName);
2282
                if( dependencyPluginService == null ) {
2283
                    if( dependency.getOptional() ) {
2284
                        logger.info("Procesing plugin '"+pluginName+", optional dependency not found ("+dependencyName+").");
2285
                    } else {
2286
                        logger.warn("Procesing plugin '"+pluginName+", dependency not found ("+dependencyName+").");
2287
                    }
2288
                    continue;
2289
                }
2290
                loaders.add(dependencyPluginService.getClassLoader());
2291
            }
2292
            try {
2293
                PluginClassLoader loader = new PluginClassLoader(
2294
                        urls,
2295
                        config.getPluginFolder().getAbsolutePath(),
2296
                        Launcher.class.getClassLoader(),
2297
                        loaders
2298
                );
2299
                PluginServices ps = new PluginServices(
2300
                        loader,
2301
                        PluginsConfig.getAlternativeNames(config)
2302
                );
2303
                logger.info("Plugin '" + pluginName + "' created");
2304
                pluginsServices.put(ps.getPluginName(), ps);
2305
                pluginsOrdered.add(pluginName);
2306
            } catch (IOException ex) {
2307
                logger.warn("Can't create PluginServices for '" + pluginName + "'.", ex);
2308
            }
2309
        }
2310
        
2311
        // Se eliminan los plugins que no fueron instalados
2312
        List<String> pluginsToRemove = new ArrayList<String>();
2313
        for (String pluginName : pluginsConfig.keySet()) {
2314
            PluginServices pluginService = pluginsServices.get(pluginName);
2315
            if( pluginService == null ) {
2316
                pluginsToRemove.add(pluginName);
2317
            } 
2318
        }
2319
        for (String pluginName : pluginsToRemove) {
2320
            logger.warn("Removed plugin "+pluginName+".");
2321
            pluginsConfig.remove(pluginName);
2322
       }
2323
    }
2324
 
2325
    /*
2326
    private void dumpPluginsDependencyInformation() {
2327
        logger.info("Plugin dependency information");
2328
        Iterator<String> i = pluginsConfig.keySet().iterator();
2329
        while (i.hasNext()) {
2330
            String pluginName = i.next();
2331
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2332
            logger.info("  Plugin " + pluginName);
2333
            Depends[] dependencies = config.getDepends();
2334
            for (int j = 0; j < dependencies.length; j++) {
2335
                Depends dependency = dependencies[j];
2336
                String dependencyName = dependency.getPluginName();
2337
                logger.info("    Dependency " + dependencyName);
2338
            }
2339
        }
2340
    }
2341
    */
2342
    private void pluginsMessages() {
2343
        Iterator<String> iterator = pluginsOrdered.iterator();
2344
        PluginConfig config;
2345
        PluginServices ps;
2346

    
2347
        while (iterator.hasNext()) {
2348
            String pluginName = iterator.next();
2349
            config = pluginsConfig.get(pluginName);
2350
            ps = pluginsServices.get(pluginName);
2351

    
2352
            if ((config.getResourceBundle() != null)
2353
                    && !config.getResourceBundle().getName().equals("")) {
2354
                // add the locale files associated with the plugin
2355
                org.gvsig.i18n.Messages.addResourceFamily(config
2356
                        .getResourceBundle().getName(), ps.getClassLoader(),
2357
                        pluginName);
2358
                org.gvsig.i18n.Messages.addResourceFamily("i18n." + config
2359
                        .getResourceBundle().getName(), ps.getClassLoader(),
2360
                        pluginName);
2361
            }
2362
        }
2363
    }
2364

    
2365
    static public PluginServices getPluginServices(String name) {
2366
        return (PluginServices) pluginsServices.get(name);
2367
    }
2368

    
2369
    static String getPluginsDir() {
2370
        return andamiConfig.getPluginsDirectory();
2371
    }
2372

    
2373
    static File getPluginFolder(String pluginName) {
2374
        return pluginsConfig.get(pluginName).getPluginFolder();
2375
    }
2376

    
2377
    static void setPluginsDir(String s) {
2378
        andamiConfig.setPluginsDirectory(s);
2379
    }
2380

    
2381
    static MDIFrame getMDIFrame() {
2382
        return frame;
2383
    }
2384

    
2385
    private PluginsConfig loadPluginConfigs() {
2386
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
2387
        List<File> repositoriesFolders = installerManager.getLocalAddonRepositories("plugin");
2388
        for (File repositoryFolder : repositoriesFolders) {
2389
            logger.info("Loading plugins configuration from repository folder " + repositoryFolder.getAbsolutePath() + ".");
2390

    
2391
            if (!repositoryFolder.exists()) {
2392
                logger.warn("Plugins repository folder not found '" + repositoryFolder.getAbsolutePath() + "'.");
2393
                continue;
2394
            }
2395

    
2396
            File[] pluginsFolders = repositoryFolder.listFiles();
2397
            if (pluginsFolders.length == 0) {
2398
                logger.info("Plugins repository folder is empty '" + repositoryFolder.getAbsolutePath() + "'.");
2399
                continue;
2400
            }
2401

    
2402
            for (int i = 0; i < pluginsFolders.length; i++) {
2403
                File pluginFolder = pluginsFolders[i];
2404
                if (!pluginFolder.isDirectory()) {
2405
                    continue;
2406
                }
2407
                String pluginName = pluginFolder.getName();
2408
                File pluginConfigFile = new File(pluginFolder, "config.xml");
2409
                if (!pluginConfigFile.exists()) {
2410
                    logger.info("Plugin '" + pluginName + "' not has a config.xml file (" + pluginConfigFile.getAbsolutePath() + ".");
2411
                    continue;
2412
                }
2413
                try {
2414
                    FileInputStream is = new FileInputStream(pluginConfigFile);
2415
                    Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2416
                    if (xml == null) {
2417
                        // the encoding was not correctly detected, use system default
2418
                        xml = new FileReader(pluginConfigFile);
2419
                    } else {
2420
                        // use a buffered reader to improve performance
2421
                        xml = new BufferedReader(xml);
2422
                    }
2423
                    PluginConfig pluginConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2424
                    pluginConfig.setPluginName(pluginName);
2425
                    pluginConfig.setPluginFolder(pluginFolder);
2426
                    pluginsConfig.put(pluginName, pluginConfig);
2427

    
2428
                } catch (FileNotFoundException e) {
2429
                    logger.info("Can't read plugin config file from plugin '" + pluginName + "' ('" + pluginConfigFile.getAbsolutePath() + ").");
2430

    
2431
                } catch (MarshalException e) {
2432
                    logger.warn("Can't load plugin the config file from plugin '" + pluginName + "' is incorect. " + e.getMessage() + " ('" + pluginConfigFile.getAbsolutePath() + ").", e);
2433

    
2434
                } catch (ValidationException e) {
2435
                    logger.warn("Can't load plugin the config file from plugin '" + pluginName + "' is invalid. " + e.getMessage() + " ('" + pluginConfigFile.getAbsolutePath() + ").", e);
2436

    
2437
                }
2438
            }
2439
        }
2440
        return pluginsConfig;
2441
    }
2442

    
2443
    private static Locale getLocale(String language, String country,
2444
            String variant) {
2445
        if (variant != null) {
2446
            return new Locale(language, country, variant);
2447
        } else if (country != null) {
2448
            return new Locale(language, country);
2449
        } else if (language != null) {
2450
            return new Locale(language);
2451
        } else {
2452
            return new Locale("es");
2453
        }
2454
    }
2455

    
2456
    private static void andamiConfigToXML(String file) throws IOException,
2457
            MarshalException, ValidationException {
2458
                // write on a temporary file in order to not destroy current file if
2459
        // there is some problem while marshaling
2460
        File tmpFile = new File(file + "-"
2461
                + DateTime.getCurrentDate().getTime());
2462
        File xml = new File(file);
2463
        File parent = xml.getParentFile();
2464
        parent.mkdirs();
2465

    
2466
        BufferedOutputStream os = new BufferedOutputStream(
2467
                new FileOutputStream(tmpFile));
2468
        OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2469
        andamiConfig.marshal(writer);
2470
        writer.close();
2471

    
2472
                // if marshaling process finished correctly, move the file to the
2473
        // correct one
2474
        xml.delete();
2475
        if (!tmpFile.renameTo(xml)) {
2476
            // if rename was not succesful, try copying it
2477
            FileChannel sourceChannel = new FileInputStream(tmpFile)
2478
                    .getChannel();
2479
            FileChannel destinationChannel = new FileOutputStream(xml)
2480
                    .getChannel();
2481
            sourceChannel.transferTo(0, sourceChannel.size(),
2482
                    destinationChannel);
2483
            sourceChannel.close();
2484
            destinationChannel.close();
2485
        }
2486
    }
2487

    
2488
    private static void andamiConfigFromXML(String file)
2489
            throws ConfigurationException {
2490
        File xml = new File(file);
2491

    
2492
        InputStreamReader reader = null;
2493
        try {
2494
            // Se lee la configuraci?n
2495
            reader = XMLEncodingUtils.getReader(xml);
2496
            andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2497
        } catch (FileNotFoundException e) {
2498
            // Si no existe se ponen los valores por defecto
2499
            andamiConfig = getDefaultAndamiConfig();
2500
        } catch (MarshalException e) {
2501
            // try to close the stream, maybe it remains open
2502
            if (reader != null) {
2503
                try {
2504
                    reader.close();
2505
                } catch (IOException e1) {
2506
                }
2507
            }
2508
                        // if there was a problem reading the file, backup it and create a
2509
            // new one with default values
2510
            String backupFile = file + "-"
2511
                    + DateTime.getCurrentDate().getTime();
2512
            NotificationManager
2513
                    .addError(
2514
                            Messages
2515
                            .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2516
                            + backupFile, new ConfigurationException(e));
2517
            xml.renameTo(new File(backupFile));
2518
            andamiConfig = getDefaultAndamiConfig();
2519
        } catch (ValidationException e) {
2520
            throw new ConfigurationException(e);
2521
        }
2522
    }
2523

    
2524
    private static AndamiConfig getDefaultAndamiConfig() {
2525
        AndamiConfig andamiConfig = new AndamiConfig();
2526

    
2527
        Andami andami = new Andami();
2528
        andami.setUpdate(true);
2529
        andamiConfig.setAndami(andami);
2530
        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2531
        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2532
        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2533

    
2534
        if (System.getProperty("javawebstart.version") != null) // Es java web
2535
        // start)
2536
        {
2537
            andamiConfig
2538
                    .setPluginsDirectory(new File(appHomeDir, "extensiones")
2539
                            .getAbsolutePath());
2540
        } else {
2541
            andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2542
                    .getAbsolutePath());
2543
        }
2544

    
2545
        andamiConfig.setPlugin(new Plugin[0]);
2546
        return andamiConfig;
2547
    }
2548

    
2549
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
2550
        File xml = getPluginsPersistenceFile(true);
2551

    
2552
        if (xml.exists()) {
2553
            InputStreamReader reader = null;
2554

    
2555
            try {
2556
                reader = XMLEncodingUtils.getReader(xml);
2557
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2558
                return new XMLEntity(tag);
2559
            } catch (FileNotFoundException e) {
2560
                throw new ConfigurationException(e);
2561
            } catch (MarshalException e) {
2562

    
2563
                                // try to reopen with default encoding (for backward
2564
                // compatibility)
2565
                try {
2566
                    reader = new FileReader(xml);
2567
                    XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2568
                    return new XMLEntity(tag);
2569

    
2570
                } catch (MarshalException ex) {
2571
                    // try to close the stream, maybe it remains open
2572
                    if (reader != null) {
2573
                        try {
2574
                            reader.close();
2575
                        } catch (IOException e1) {
2576
                        }
2577
                    }
2578
                    // backup the old file
2579
                    String backupFile = getPluginsPersistenceFile(true)
2580
                            .getPath()
2581
                            + "-" + DateTime.getCurrentDate().getTime();
2582
                    NotificationManager
2583
                            .addError(
2584
                                    Messages
2585
                                    .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2586
                                    + backupFile,
2587
                                    new ConfigurationException(e));
2588
                    xml.renameTo(new File(backupFile));
2589
                    // create a new, empty configuration
2590
                    return new XMLEntity();
2591
                } catch (FileNotFoundException ex) {
2592
                    return new XMLEntity();
2593
                } catch (ValidationException ex) {
2594
                    throw new ConfigurationException(e);
2595
                }
2596
            } catch (ValidationException e) {
2597
                throw new ConfigurationException(e);
2598
            }
2599
        } else {
2600
            return new XMLEntity();
2601
        }
2602
    }
2603

    
2604
    private static File getPluginsPersistenceFile(boolean read) {
2605
        if (read) {
2606
            File pluginsPersistenceFile = new File(getAppHomeDir(),
2607
                    "plugins-persistence-2_0.xml");
2608
            if (pluginsPersistenceFile.exists()) {
2609
                return pluginsPersistenceFile;
2610
            }
2611
            pluginsPersistenceFile = new File(getAppHomeDir(),
2612
                    "plugins-persistence.xml");
2613
            if (pluginsPersistenceFile.exists()) {
2614
                return pluginsPersistenceFile;
2615
            }
2616
        }
2617
        return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2618

    
2619
    }
2620

    
2621
    private static void persistenceToXML(XMLEntity entity)
2622
            throws ConfigurationException {
2623
                // write on a temporary file in order to not destroy current file if
2624
        // there is some problem while marshaling
2625
        File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2626
                + "-" + DateTime.getCurrentDate().getTime());
2627

    
2628
        File xml = getPluginsPersistenceFile(false);
2629
        OutputStreamWriter writer = null;
2630

    
2631
        try {
2632
            writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2633
                    CASTORENCODING);
2634
            entity.getXmlTag().marshal(writer);
2635
            writer.close();
2636

    
2637
                        // if marshaling process finished correctly, move the file to the
2638
            // correct one
2639
            xml.delete();
2640
            if (!tmpFile.renameTo(xml)) {
2641
                // if rename was not succesful, try copying it
2642
                FileChannel sourceChannel = new FileInputStream(tmpFile)
2643
                        .getChannel();
2644
                FileChannel destinationChannel = new FileOutputStream(xml)
2645
                        .getChannel();
2646
                sourceChannel.transferTo(0, sourceChannel.size(),
2647
                        destinationChannel);
2648
                sourceChannel.close();
2649
                destinationChannel.close();
2650

    
2651
            }
2652
        } catch (FileNotFoundException e) {
2653
            throw new ConfigurationException(e);
2654
        } catch (MarshalException e) {
2655
            // try to close the stream, maybe it remains open
2656
            if (writer != null) {
2657
                try {
2658
                    writer.close();
2659
                } catch (IOException e1) {
2660
                }
2661
            }
2662
        } catch (ValidationException e) {
2663
            throw new ConfigurationException(e);
2664
        } catch (IOException e) {
2665
            throw new ConfigurationException(e);
2666
        }
2667
    }
2668

    
2669
    static MDIFrame getFrame() {
2670
        return frame;
2671
    }
2672

    
2673
    /**
2674
     * Gracefully closes the application. It shows dialogs to save data, finish
2675
     * processes, etc, then it terminates the extensions, removes temporal files
2676
     * and finally exits.
2677
     */
2678
    public synchronized static void closeApplication() {
2679
        TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2680
        terminationProcess.run();
2681
    }
2682

    
2683
    static HashMap getClassesExtensions() {
2684
        return classesExtensions;
2685
    }
2686

    
2687
    private static Extensions[] getExtensions() {
2688
        List<Extensions> array = new ArrayList<Extensions>();
2689
        Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2690

    
2691
        while (iter.hasNext()) {
2692
            array.add(iter.next().getExtensions());
2693
        }
2694

    
2695
        return array.toArray(new Extensions[array.size()]);
2696
    }
2697

    
2698
    public static Iterator getExtensionIterator() {
2699
        return extensions.iterator();
2700
    }
2701

    
2702
    public static HashMap getPluginConfig() {
2703
        return pluginsConfig;
2704
    }
2705

    
2706
    public static Extension getExtension(String s) {
2707
        Extensions[] exts = getExtensions();
2708

    
2709
        for (int i = 0; i < exts.length; i++) {
2710
            for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2711
                if (exts[i].getExtension(j).getClassName().equals(s)) {
2712
                    return exts[i].getExtension(j);
2713
                }
2714
            }
2715
        }
2716

    
2717
        return null;
2718
    }
2719

    
2720
    public static AndamiConfig getAndamiConfig() {
2721
        return andamiConfig;
2722
    }
2723

    
2724
    private static class ExtensionComparator implements Comparator {
2725

    
2726
        public int compare(Object o1, Object o2) {
2727
            Extension e1 = (Extension) o1;
2728
            Extension e2 = (Extension) o2;
2729

    
2730
            if (!e1.hasPriority() && !e2.hasPriority()) {
2731
                return -1;
2732
            }
2733

    
2734
            if (e1.hasPriority() && !e2.hasPriority()) {
2735
                return Integer.MIN_VALUE;
2736
            }
2737

    
2738
            if (e2.hasPriority() && !e1.hasPriority()) {
2739
                return Integer.MAX_VALUE;
2740
            }
2741

    
2742
            if (e1.getPriority() != e2.getPriority()) {
2743
                return e2.getPriority() - e1.getPriority();
2744
            } else {
2745
                return (e2.toString().compareTo(e1.toString()));
2746
            }
2747
        }
2748
    }
2749

    
2750
    private static class MenuComparator implements Comparator<SortableMenu> {
2751

    
2752
        private static ExtensionComparator extComp = new ExtensionComparator();
2753

    
2754
        public int compare(SortableMenu e1, SortableMenu e2) {
2755

    
2756
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2757
                if (e1.extension instanceof SkinExtensionType) {
2758
                    return 1;
2759
                } else if (e2.extension instanceof SkinExtensionType) {
2760
                    return -1;
2761
                } else {
2762
                    return extComp.compare(e1.extension, e2.extension);
2763
                }
2764
            }
2765

    
2766
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2767
                return Integer.MIN_VALUE;
2768
            }
2769

    
2770
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2771
                return Integer.MAX_VALUE;
2772
            }
2773

    
2774
            if (e1.menu.getPosition() == e2.menu.getPosition()) {
2775
                                // we don't return 0 unless both objects are the same, otherwise
2776
                // the objects get overwritten in the treemap
2777
                return (e1.toString().compareTo(e2.toString()));
2778
            }
2779
            if (e1.menu.getPosition() > e2.menu.getPosition()) {
2780
                return Integer.MAX_VALUE;
2781
            }
2782
            return Integer.MIN_VALUE;
2783

    
2784
        }
2785
    }
2786

    
2787
    private static class SortableMenu {
2788

    
2789
        public PluginClassLoader loader;
2790
        public Menu menu;
2791
        public SkinExtensionType extension;
2792

    
2793
        public SortableMenu(PluginClassLoader loader,
2794
                SkinExtensionType skinExt, Menu menu2) {
2795
            extension = skinExt;
2796
            menu = menu2;
2797
            this.loader = loader;
2798
        }
2799

    
2800
    }
2801

    
2802
    private static class SortableTool {
2803

    
2804
        public PluginClassLoader loader;
2805
        public ToolBar toolbar;
2806
        public ActionTool actiontool;
2807
        public SelectableTool selectabletool;
2808
        public SkinExtensionType extension;
2809

    
2810
        public SortableTool(PluginClassLoader loader,
2811
                SkinExtensionType skinExt, ToolBar toolbar2,
2812
                ActionTool actiontool2) {
2813
            extension = skinExt;
2814
            toolbar = toolbar2;
2815
            actiontool = actiontool2;
2816
            this.loader = loader;
2817
        }
2818

    
2819
        public SortableTool(PluginClassLoader loader,
2820
                SkinExtensionType skinExt, ToolBar toolbar2,
2821
                SelectableTool selectabletool2) {
2822
            extension = skinExt;
2823
            toolbar = toolbar2;
2824
            selectabletool = selectabletool2;
2825
            this.loader = loader;
2826
        }
2827
    }
2828

    
2829
    private static class ToolBarComparator implements Comparator<SortableTool> {
2830

    
2831
        private static ExtensionComparator extComp = new ExtensionComparator();
2832

    
2833
        public int compare(SortableTool e1, SortableTool e2) {
2834

    
2835
                        // if the toolbars have the same name, they are considered to be
2836
            // the same toolbar, so we don't need to do further comparing
2837
            if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2838
                return 0;
2839
            }
2840

    
2841
            if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2842
                if (e1.extension instanceof SkinExtensionType) {
2843
                    return 1;
2844
                } else if (e2.extension instanceof SkinExtensionType) {
2845
                    return -1;
2846
                } else {
2847
                    return extComp.compare(e1.extension, e2.extension);
2848
                }
2849
            }
2850

    
2851
            if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2852
                return Integer.MIN_VALUE;
2853
            }
2854

    
2855
            if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2856
                return Integer.MAX_VALUE;
2857
            }
2858
            if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2859
                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2860
            }
2861

    
2862
            if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2863
                    && e1.toolbar.getSelectableTool().equals(
2864
                            e2.toolbar.getSelectableTool())) {
2865
                return 0;
2866
            }
2867
            return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2868
        }
2869
    }
2870

    
2871
    /**
2872
     * <p>
2873
     * This class is used to compare tools (selectabletool and actiontool),
2874
     * using the "position" attribute.
2875
     * </p>
2876
     * <p>
2877
     * The ordering criteria are:
2878
     * </p>
2879
     * <ul>
2880
     * <li>If the tools are placed in different toolbars, they use the toolbars'
2881
     * order. (using the ToolBarComparator).</li>
2882
     * <li></li>
2883
     * <li>If any of the tools has not 'position' attribute, the tool which
2884
     * <strong>has</strong> the attribute will be placed first.</li>
2885
     * <li>If both tools have the same position (or they don't have a 'position'
2886
     * attribute), the priority of the extensions where the tool is
2887
     * defined.</li>
2888
     * </ul>
2889
     *
2890
     * @author cesar
2891
     * @version $Revision: 40305 $
2892
     */
2893
    private static class ToolComparator implements Comparator<SortableTool> {
2894

    
2895
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2896

    
2897
        public int compare(SortableTool e1, SortableTool e2) {
2898
            // compare the toolbars which contain the tools
2899
            long result = toolBarComp.compare(e1, e2);
2900
            if (result != 0) { // if the toolbars are different, use their order
2901
                return result > 0 ? 1 : -1;
2902
            }
2903
            // otherwise, compare the tools
2904
            long e1Position = -1, e2Position = -1;
2905

    
2906
            if (e1.actiontool != null) {
2907
                if (e1.actiontool.hasPosition()) {
2908
                    e1Position = e1.actiontool.getPosition();
2909
                }
2910
            } else if (e1.selectabletool != null) {
2911
                if (e1.selectabletool.hasPosition()) {
2912
                    e1Position = e1.selectabletool.getPosition();
2913
                }
2914
            }
2915

    
2916
            if (e2.actiontool != null) {
2917
                if (e2.actiontool.hasPosition()) {
2918
                    e2Position = e2.actiontool.getPosition();
2919
                }
2920
            } else if (e2.selectabletool != null) {
2921
                if (e2.selectabletool.hasPosition()) {
2922
                    e2Position = e2.selectabletool.getPosition();
2923
                }
2924
            }
2925

    
2926
            if ((e1Position == -1) && (e2Position != -1)) {
2927
                return 1;
2928
            }
2929
            if ((e1Position != -1) && (e2Position == -1)) {
2930
                return -1;
2931
            }
2932
            if ((e1Position != -1) && (e2Position != -1)) {
2933
                result = e1Position - e2Position;
2934
                                // we don't return 0 unless both objects are the same, otherwise
2935
                // the objects get overwritten in the treemap
2936
                if (result != 0) {
2937
                    return result > 0 ? 1 : -1;
2938
                }
2939
            }
2940
            return e1.toString().compareTo(e2.toString());
2941
        }
2942
    }
2943

    
2944
    public static String getDefaultLookAndFeel() {
2945
        String osName = (String) System.getProperty("os.name");
2946

    
2947
        if ((osName.length() > 4)
2948
                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2949
            return nonWinDefaultLookAndFeel;
2950
        }
2951
        if (osName.toLowerCase().startsWith("mac os x")) {
2952
            return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2953
        }
2954

    
2955
        return UIManager.getSystemLookAndFeelClassName();
2956
    }
2957

    
2958
    /**
2959
     * Gets the ISO 839 two-characters-long language code matching the provided
2960
     * language code (which may be an ISO 839-2/T three-characters-long code or
2961
     * an ISO 839-1 two-characters-long code).
2962
     *
2963
     * If the provided parameter is already two characters long, it returns the
2964
     * parameter without any modification.
2965
     *
2966
     * @param langCode A language code representing either an ISO 839-2/T
2967
     * language code or an ISO 839-1 code.
2968
     * @return A two-characters-long code specifying an ISO 839 language code.
2969
     */
2970
    private static String normalizeLanguageCode(String langCode) {
2971
        final String fileName = "iso_639.tab";
2972
        if (langCode.length() == 2) {
2973
            return langCode;
2974
        } else if (langCode.length() == 3) {
2975
            if (langCode.equals("va") || langCode.equals("val")) { // special
2976
                // case
2977
                // for
2978
                // Valencian
2979
                return "ca";
2980
            }
2981
            URL isoCodes = Launcher.class.getClassLoader()
2982
                    .getResource(fileName);
2983
            if (isoCodes != null) {
2984
                try {
2985
                    BufferedReader reader = new BufferedReader(
2986
                            new InputStreamReader(isoCodes.openStream(),
2987
                                    "ISO-8859-1"));
2988
                    String line;
2989

    
2990
                    while ((line = reader.readLine()) != null) {
2991
                        String[] language = line.split("\t");
2992
                        if (language[0].equals(langCode)) {
2993
                                                        // the three
2994
                            // characters code
2995
                            return language[2]; // third column i the two
2996
                            // characters code
2997
                        }
2998
                    }
2999
                } catch (IOException ex) {
3000
                    logger.error(Messages
3001
                            .getString("Error_reading_isocodes_file"), ex);
3002
                    return "es";
3003
                }
3004
            } else {
3005
                logger.error(Messages.getString("Error_reading_isocodes_file"));
3006
                return "es";
3007
            }
3008
        }
3009
        return "es";
3010
    }
3011

    
3012
    /**
3013
     * Configures the locales (languages and local resources) to be used by the
3014
     * application.
3015
     *
3016
     * First it tries to get the locale from the command line parameters, then
3017
     * the andami-config file is checked.
3018
     *
3019
     * The locale name is normalized to get a two characters language code as
3020
     * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
3021
     * also accepted from the command line or the configuration file).
3022
     *
3023
     * Finally, the gvsig-i18n library and the default locales for Java and
3024
     * Swing are configured.
3025
     *
3026
     */
3027
    private static void configureLocales(String[] args) {
3028
        // Configurar el locale
3029
        String localeStr = null;
3030

    
3031
        localeStr = PluginServices.getArgumentByName("language");
3032
        if (localeStr == null) {
3033
            localeStr = andamiConfig.getLocaleLanguage();
3034
        }
3035
        localeStr = normalizeLanguageCode(localeStr);
3036
        locale = getLocale(
3037
                localeStr,
3038
                andamiConfig.getLocaleCountry(),
3039
                andamiConfig.getLocaleVariant()
3040
        );
3041
        org.gvsig.i18n.Messages.setCurrentLocale(locale);
3042
        JComponent.setDefaultLocale(locale);
3043
        /*
3044
         org.gvsig.i18n.Messages.addLocale(locale);
3045
         // add english and spanish as fallback languages
3046
         if ( localeStr.equals("es") || localeStr.equals("ca")
3047
         || localeStr.equals("gl") || localeStr.equals("eu")
3048
         || localeStr.equals("va") ) {
3049
         // prefer Spanish for languages spoken in Spain
3050
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3051
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3052
         } else {
3053
         // prefer English for the rest
3054
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3055
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3056
         }
3057
         */
3058
        // Create classloader for the i18n resources in the
3059
        // andami and user i18n folder. Those values will have
3060
        // precedence over any other values added afterwards
3061
        File appI18nFolder = new File(getApplicationFolder(), "i18n");
3062
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
3063
        if (!userI18nFolder.exists()) {
3064
            try {
3065
                FileUtils.forceMkdir(userI18nFolder);
3066
            } catch (IOException e) {
3067
                logger.info("Can't create i18n folder in gvSIG home (" + userI18nFolder + ").", e);
3068
            }
3069
        }
3070
//        logger.info("Loading i18n resources from the application and user "
3071
//                + "folders: {}, {}", appI18nFolder, userI18nFolder);
3072

    
3073
        URL[] i18nURLs = getURLsFromI18nFolders(userI18nFolder, appI18nFolder);
3074
        ClassLoader i18nClassLoader = URLClassLoader.newInstance(i18nURLs, null);
3075
        logger.info("loading resources from classloader " + i18nClassLoader.toString() + ".");
3076
        org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
3077
                "Andami Launcher");
3078

    
3079
        // Finally load the andami own i18n resources
3080
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
3081
                "Andami Launcher");
3082
    }
3083

    
3084
    private static URL[] getURLsFromI18nFolders(File userFolder, File appFolder) {
3085
        List<URL> urls = new ArrayList<URL>();
3086
        File[] files = new File[]{userFolder, appFolder};
3087
        for (int n1 = 0; n1 < files.length; n1++) {
3088
            File folder = files[n1];
3089
//                try {
3090
//                    urls.add(folder.toURI().toURL());
3091
//                } catch (MalformedURLException ex) {
3092
//                    logger.warn("Can't convert file to url (file="+userFolder.getAbsolutePath()+").", ex);
3093
//                    return null;
3094
//                }
3095
            File[] subFiles = folder.listFiles();
3096
            for (int n2 = 0; n2 < subFiles.length; n2++) {
3097
                File subFolder = subFiles[n2];
3098
                if ("andami".equalsIgnoreCase(subFolder.getName())) {
3099
                    // Skip andami and add the last.
3100
                    continue;
3101
                }
3102
                if (subFolder.isDirectory()) {
3103
                    try {
3104
                        urls.add(subFolder.toURI().toURL());
3105
                    } catch (MalformedURLException ex) {
3106
                        logger.warn("Can't convert file to url (file=" + subFolder.getAbsolutePath() + ").", ex);
3107
                        return null;
3108
                    }
3109
                }
3110
            }
3111
        }
3112
        File folder = new File(appFolder, "andami");
3113
        try {
3114
            urls.add(folder.toURI().toURL());
3115
        } catch (MalformedURLException ex) {
3116
            logger.warn("Can't convert file to url (file=" + folder.getAbsolutePath() + ").", ex);
3117
            return null;
3118
        }
3119
        return urls.toArray(new URL[urls.size()]);
3120
    }
3121

    
3122
    /**
3123
     * Gets Home Directory location of the application into users home folder.
3124
     *
3125
     * May be set from outside the aplication by means of
3126
     * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
3127
     *
3128
     * @return
3129
     */
3130
    public static String getAppHomeDir() {
3131
        return appHomeDir;
3132
    }
3133

    
3134
    public static File getApplicationHomeFolder() {
3135
        return new File(getAppHomeDir());
3136
    }
3137

    
3138
    /**
3139
     * Sets Home Directory location of the application. May be set from outside
3140
     * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3141
     * the name of the application
3142
     *
3143
     * @param appHomeDir
3144
     */
3145
    public static void setAppHomeDir(String appHomeDir) {
3146
        Launcher.appHomeDir = appHomeDir;
3147
    }
3148

    
3149
    /**
3150
     * Initialize the extesion that have to take the control of the state of
3151
     * action controls of the UI of all extensions. <br>
3152
     * <br>
3153
     * For use this option you have to add an argument to the command line like
3154
     * this: <br>
3155
     * <br>
3156
     * -exclusiveUI={pathToExtensionClass} <br>
3157
     *
3158
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3159
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3160
     */
3161
    private static void initializeExclusiveUIExtension() {
3162
        String name = PluginServices.getArgumentByName("exclusiveUI");
3163
        if (name == null) {
3164
            return;
3165
        }
3166

    
3167
        Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3168
                .iterator();
3169
        int charIndex;
3170
        Class<? extends IExtension> key;
3171
        while (iter.hasNext()) {
3172
            key = iter.next();
3173
            charIndex = key.getName().indexOf(name);
3174
            // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3175
            if (charIndex == 0) {
3176
                IExtension ext = classesExtensions.get(key);
3177
                if (ext instanceof ExtensionDecorator) {
3178
                    ext = ((ExtensionDecorator) ext).getExtension();
3179
                }
3180
                if (ext instanceof ExclusiveUIExtension) {
3181
                    PluginServices
3182
                            .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3183
                }
3184
                break;
3185
            }
3186
        }
3187

    
3188
        logger
3189
                .error(Messages
3190
                        .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3191
                        + " '" + name + "'");
3192
    }
3193

    
3194
    public static void initIconThemes() {
3195
        PluginsManager pluginsManager = PluginsLocator.getManager();
3196
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3197

    
3198
        File f = new File(pluginsManager.getApplicationHomeFolder(), "icon-theme");
3199
        if (!f.exists()) {
3200
            try {
3201
                f.mkdir();
3202
            } catch (Exception ex) {
3203
                // Do nothing
3204
            }
3205
        }
3206
        iconManager.getRepository().add(f, "_User");
3207

    
3208
        f = new File(pluginsManager.getApplicationFolder(), "icon-theme");
3209
        if (!f.exists()) {
3210
            try {
3211
                f.mkdir();
3212
            } catch (Exception ex) {
3213
                // Do nothing
3214
            }
3215
        }
3216
        iconManager.getRepository().add(f, "_Global");
3217

    
3218
        Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3219
        String defaultThemeID = prefs.get("default-theme", null);
3220
        if (defaultThemeID != null) {
3221
            IconTheme iconTheme = iconManager.get(defaultThemeID);
3222
            if (iconTheme != null) {
3223
                iconManager.setCurrent(iconTheme);
3224
            }
3225
        }
3226
    }
3227

    
3228
    public static void manageUnsavedData(String prompt) throws Exception {
3229
        final UnsavedDataPanel panel = new UnsavedDataPanel(prompt);
3230
        final List<IUnsavedData> unsavedData = PluginsLocator.getManager().getUnsavedData();
3231
        panel.setUnsavedData(unsavedData);
3232

    
3233
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3234

    
3235
            public void cancel(UnsavedDataPanel panel) {
3236
                panel.setVisible(false);
3237
            }
3238

    
3239
            public void discard(UnsavedDataPanel panel) {
3240
                panel.setVisible(false);
3241
            }
3242

    
3243
            public void accept(UnsavedDataPanel panel) {
3244
                panel.setVisible(false);
3245

    
3246
                try {
3247
                    PluginsLocator.getManager().saveUnsavedData(panel.getSelectedsUnsavedDataList());
3248
                } catch (UnsavedDataException e) {
3249
                    StringBuilder msg = new StringBuilder();
3250
                    msg.append(PluginServices.getText(this, "The_following_resources_could_not_be_saved"));
3251
                    msg.append("\n");
3252
                    for (Iterator iterator = e.getUnsavedData().iterator(); iterator.hasNext();) {
3253
                        IUnsavedData unsavedData = (IUnsavedData) iterator.next();
3254
                        msg.append(unsavedData.getResourceName());
3255
                        msg.append(" -- ");
3256
                        msg.append(unsavedData.getDescription());
3257
                        msg.append("\n");
3258
                    }
3259
                    JOptionPane.showMessageDialog(panel, msg, PluginServices.getText(this, "Resources_was_not_saved"), JOptionPane.ERROR_MESSAGE);
3260
                }
3261
            }
3262
        });
3263

    
3264
        //TODO: mostrar panel WindowManager
3265
        ToolsSwingLocator.getWindowManager().showWindow(
3266
                panel,
3267
                PluginServices.getText(panel, "Resource_was_not_saved"),
3268
                MODE.DIALOG);
3269

    
3270
    }
3271

    
3272
    /**
3273
     * Manages Andami termination process
3274
     *
3275
     * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3276
     */
3277
    public class TerminationProcess {
3278

    
3279
        private boolean proceed = false;
3280
        private UnsavedDataPanel panel = null;
3281

    
3282
        public void run() {
3283
            try {
3284
                int exit = manageUnsavedData();
3285
                if ((exit == JOptionPane.NO_OPTION)
3286
                        || (exit == JOptionPane.CLOSED_OPTION)) {
3287
                    // the user doesn't want to exit
3288
                    return;
3289
                }
3290
                closeAndami();
3291
            } catch (Exception e) {
3292
                logger.warn("It is not possible to close the application", e);
3293
                                // It is not possible to close the application.
3294
                // this exception has been registered before
3295
            }
3296
        }
3297

    
3298
        /**
3299
         * Finishes the application without asking user if want or not to save
3300
         * unsaved data.
3301
         */
3302
        public void closeAndami() {
3303
            PluginsManager pluginsManager = PluginsLocator.getManager();
3304
            pluginsManager.executeShutdownTasks();
3305

    
3306
            try {
3307
                saveAndamiConfig();
3308
            } catch (Exception ex) {
3309
                logger.error(
3310
                        "There was an error exiting application, can't save andami-config.xml",
3311
                        ex
3312
                );
3313
            }
3314

    
3315
            try {
3316
                // Persistencia de los plugins
3317
                savePluginPersistence();
3318
                savePluginsProperties();
3319
            } catch (Exception ex) {
3320
                logger.error(
3321
                        "There was an error exiting application, can't save plugins properties",
3322
                        ex
3323
                );
3324
            }
3325

    
3326
            // Finalize all the extensions
3327
            finalizeExtensions();
3328

    
3329
            try {
3330
                // Clean any temp data created
3331
                Utilities.cleanUpTempFiles();
3332
            } catch (Exception ex) {
3333
                logger.error(
3334
                        "There was an error exiting application, can't remove temporary files",
3335
                        ex
3336
                );
3337
            }
3338

    
3339
            logger.info("Quiting application.");
3340

    
3341
            // Para la depuraci?n de memory leaks
3342
            System.gc();
3343

    
3344
            System.exit(0);
3345
        }
3346

    
3347
        public void saveAndamiConfig() {
3348
            // Configuraci?n de Andami
3349
            try {
3350
                andamiConfigToXML(andamiConfigPath);
3351
            } catch (MarshalException e) {
3352
                logger
3353
                        .error(
3354
                                Messages
3355
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3356
                                e);
3357
            } catch (ValidationException e) {
3358
                logger
3359
                        .error(
3360
                                Messages
3361
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3362
                                e);
3363
            } catch (IOException e) {
3364
                logger
3365
                        .error(
3366
                                Messages
3367
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3368
                                e);
3369
            }
3370
        }
3371

    
3372
        private void savePluginsProperties() {
3373
            PluginsManager manager = PluginsLocator.getManager();
3374
            List<PluginServices> plugins = manager.getPlugins();
3375
            for (PluginServices plugin : plugins) {
3376
                if (plugin != null) {
3377
                    plugin.savePluginProperties();
3378
                }
3379
            }
3380
        }
3381

    
3382
        /**
3383
         * Exectutes the terminate method for all the extensions, in the reverse
3384
         * order they were initialized
3385
         *
3386
         */
3387
        private void finalizeExtensions() {
3388
            for (int i = extensions.size() - 1; i >= 0; i--) {
3389
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3390
                        .get(i);
3391
                String extensionName = "(unknow)";
3392
                try {
3393
                    extensionName = extensionInstance.getClass().getName();
3394
                    extensionInstance.terminate();
3395
                } catch (Exception ex) {
3396
                    logger.error(MessageFormat.format(
3397
                            "There was an error extension ending {0}",
3398
                            extensionName), ex);
3399
                }
3400
            }
3401
        }
3402

    
3403
        private IUnsavedData[] getUnsavedData() throws Exception {
3404
            List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3405
            IExtension exclusiveExtension = PluginServices
3406
                    .getExclusiveUIExtension();
3407

    
3408
            for (int i = extensions.size() - 1; i >= 0; i--) {
3409
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3410
                        .get(i);
3411
                IExtensionStatus status = null;
3412
                if (exclusiveExtension != null) {
3413
                    status = exclusiveExtension.getStatus(extensionInstance);
3414
                } else {
3415
                    status = extensionInstance.getStatus();
3416
                }
3417
                if (status != null) {
3418
                    try {
3419
                        if (status.hasUnsavedData()) {
3420
                            IUnsavedData[] array = status.getUnsavedData();
3421
                            for (int element = 0; element < array.length; element++) {
3422
                                unsavedDataList.add(array[element]);
3423
                            }
3424
                        }
3425
                    } catch (Exception e) {
3426
                        logger.info("Error calling the hasUnsavedData method",
3427
                                new Exception());
3428
                        int option = JOptionPane
3429
                                .showConfirmDialog(
3430
                                        frame,
3431
                                        Messages
3432
                                        .getString("error_getting_unsaved_data"),
3433
                                        Messages.getString("MDIFrame.salir"),
3434
                                        JOptionPane.YES_NO_OPTION);
3435
                        if (option == JOptionPane.NO_OPTION) {
3436
                            throw e;
3437
                        }
3438
                    }
3439
                }
3440
            }
3441
            return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3442
                    .size()]);
3443
        }
3444

    
3445
        public UnsavedDataPanel getUnsavedDataPanel() {
3446
            if (panel == null) {
3447
                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3448
            }
3449
            return panel;
3450
        }
3451

    
3452
        /**
3453
         * Checks if the extensions have some unsaved data, and shows a dialog
3454
         * to allow saving it. This dialog also allows to don't exit Andami.
3455
         *
3456
         * @return true if the user confirmed he wishes to exit, false otherwise
3457
         * @throws Exception
3458
         */
3459
        public int manageUnsavedData() throws Exception {
3460
            IUnsavedData[] unsavedData = getUnsavedData();
3461

    
3462
            // there was no unsaved data
3463
            if (unsavedData.length == 0) {
3464
                int option = JOptionPane
3465
                        .showConfirmDialog(frame, Messages
3466
                                .getString("MDIFrame.quiere_salir"), Messages
3467
                                .getString("MDIFrame.salir"),
3468
                                JOptionPane.YES_NO_OPTION);
3469
                return option;
3470
            }
3471

    
3472
            UnsavedDataPanel panel = getUnsavedDataPanel();
3473
            panel.setUnsavedDataArray(unsavedData);
3474

    
3475
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3476

    
3477
                public void cancel(UnsavedDataPanel panel) {
3478
                    proceed(false);
3479
                    PluginServices.getMDIManager().closeWindow(panel);
3480

    
3481
                }
3482

    
3483
                public void discard(UnsavedDataPanel panel) {
3484
                    proceed(true);
3485
                    PluginServices.getMDIManager().closeWindow(panel);
3486

    
3487
                }
3488

    
3489
                public void accept(UnsavedDataPanel panel) {
3490
                    IUnsavedData[] unsavedDataArray = panel
3491
                            .getSelectedsUnsavedData();
3492
                    boolean saved;
3493
                    for (int i = 0; i < unsavedDataArray.length; i++) {
3494
                        try {
3495
                            saved = unsavedDataArray[i].saveData();
3496
                        } catch (Exception ex) {
3497
                            PluginServices.getLogger().error(
3498
                                    "Error saving"
3499
                                    + unsavedDataArray[i]
3500
                                    .getResourceName(), ex);
3501
                            saved = false;
3502
                        }
3503
                        if (!saved) {
3504
                            JOptionPane
3505
                                    .showMessageDialog(
3506
                                            panel,
3507
                                            PluginServices
3508
                                            .getText(this,
3509
                                                    "The_following_resource_could_not_be_saved_")
3510
                                            + "\n"
3511
                                            + unsavedDataArray[i]
3512
                                            .getResourceName()
3513
                                            + " -- "
3514
                                            + unsavedDataArray[i]
3515
                                            .getDescription(),
3516
                                            PluginServices.getText(this,
3517
                                                    "unsaved_resources"),
3518
                                            JOptionPane.ERROR_MESSAGE);
3519

    
3520
                            try {
3521
                                unsavedDataArray = getUnsavedData();
3522
                            } catch (Exception e) {
3523
                                // This exception has been registered before
3524
                            }
3525
                            panel.setUnsavedDataArray(unsavedDataArray);
3526
                            return;
3527
                        }
3528
                    }
3529
                    proceed(true);
3530
                    PluginServices.getMDIManager().closeWindow(panel);
3531
                }
3532
            });
3533

    
3534
            PluginServices.getMDIManager().addWindow(panel);
3535
            if (proceed) {
3536
                return JOptionPane.YES_OPTION;
3537
            } else {
3538
                return JOptionPane.NO_OPTION;
3539
            }
3540
        }
3541

    
3542
        private void proceed(boolean proceed) {
3543
            this.proceed = proceed;
3544
        }
3545

    
3546
    }
3547

    
3548
    public static TerminationProcess getTerminationProcess() {
3549
        return (new Launcher()).new TerminationProcess();
3550
    }
3551

    
3552
    private PackageInfo getPackageInfo(String pluginsFolder) {
3553
        try {
3554
            PluginsManager pm = PluginsLocator.getManager();
3555
            return pm.getPackageInfo();
3556
        } catch (Exception e) {
3557
            logger.info("Can't locate PackageInfo from plugin org.gvsig.app", e);
3558
            return null;
3559
        }
3560
    }
3561

    
3562
    /**
3563
     * Launch the gvSIG package installer.
3564
     *
3565
     * @throws Exception if there is any error
3566
     */
3567
    private void doInstall(String[] args) throws Exception {
3568
        String installURL = null;
3569
        String installURLFile = null;
3570
        String gvSIGVersion = null;
3571
        String[] myArgs = new String[3];
3572
        PackageInfo packageInfo = null;
3573

    
3574
        Options options = new Options();
3575
        options.addOption("i", "install", false, "install");
3576
        options.addOption("u", "installURL", true, "installURL");
3577
        options.addOption("f", "installURLFile", true, "installURLFile");
3578
        options.addOption("v", "installVersion", true, "installVersion");
3579
        options.addOption("A", "applicationName", true, "application name, default is gvSIG");
3580
        options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3581
        options.addOption("l", "language", true, "language");
3582

    
3583
        // This options are managed by the gvSIG.sh but need to be declared here to avoid
3584
        // errors.
3585
        options.addOption(null, "debug", false, "Activate the JVM remote debug");
3586
        options.addOption(null, "pause", false, "Pause when activate JVM debug");
3587

    
3588
        /*
3589
         * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3590
         *
3591
         * --install
3592
         * --applicationName=gvSIG
3593
         * --language=es
3594
         * --pluginsFolder=gvSIG/extensiones
3595
         *
3596
         * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3597
         * --installVersion=2.0.0
3598
         * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3599
         * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3600
         *
3601
         */
3602
        CommandLineParser parser = new PosixParser();
3603
        CommandLine line = null;
3604
        try {
3605
            line = parser.parse(options, args);
3606
            boolean hasAllMandatoryOptions = true;
3607
            if (!line.hasOption("install")) {
3608
                hasAllMandatoryOptions = false;
3609
            }
3610

    
3611
            if (line.hasOption("installVersion")) {
3612
                gvSIGVersion = line.getOptionValue("installVersion");
3613
            }
3614
            if (line.hasOption("applicationName")) {
3615
                myArgs[0] = line.getOptionValue("applicationName");
3616
            } else {
3617
                myArgs[0] = "gvSIG";
3618
            }
3619
            if (line.hasOption("pluginsFolder")) {
3620
                myArgs[1] = line.getOptionValue("pluginsFolder");
3621
            } else {
3622
                myArgs[1] = "gvSIG/extensiones";
3623
            }
3624
            if (line.hasOption("language")) {
3625
                myArgs[2] = "language=" + line.getOptionValue("language");
3626
            } else {
3627
                // prevent null
3628
                myArgs[2] = Locale.getDefault().toString();
3629
            }
3630

    
3631
            if (line.hasOption("installURL")) {
3632
                installURL = line.getOptionValue("installURL");
3633
            } else {
3634
                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3635
            }
3636

    
3637
            if (line.hasOption("installURLFile")) {
3638
                installURLFile = line.getOptionValue("installURLFile");
3639
            } else {
3640
                installURLFile = "gvsig-installer-urls.config";
3641
            }
3642

    
3643
            if (!hasAllMandatoryOptions) {
3644
                System.err.println(Messages.get("usage") + ": Launcher "
3645
                        + "--install "
3646
                        + "[--applicationName=appName] "
3647
                        + "[--pluginsFolder=plugins-directory] "
3648
                        + "[--installURLFile=File] "
3649
                        + "[--installURL=URL] "
3650
                        + "[--language=locale]"
3651
                );
3652
                return;
3653
            }
3654
        } catch (ParseException exp) {
3655
            System.err.println("Unexpected exception:" + exp.getMessage());
3656
            System.exit(-1);
3657
        }
3658

    
3659
        initializeApp(myArgs, "installer");
3660

    
3661
        new DefaultLibrariesInitializer().fullInitialize(true);
3662

    
3663
        initializeInstallerManager();
3664

    
3665
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
3666
        
3667
//        try {
3668
//            logger.info("Loading plugins configurations");
3669
//            this.loadPluginConfigs();
3670
//        } catch (Throwable ex) {
3671
//            logger.warn("Can't load plugins configurations", ex);
3672
//        }
3673
//
3674
//        try {
3675
//            logger.info("Loading plugins");
3676
//            this.loadPluginServices();
3677
//        } catch (Throwable ex) {
3678
//            logger.warn("Can't load plugins", ex);
3679
//        }
3680

    
3681
        AndamiConfig config = getAndamiConfig();
3682

    
3683
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3684

    
3685
        initializeLibraries();
3686

    
3687
        packageInfo = getPackageInfo(myArgs[1]);
3688

    
3689
        // set the gvSIG version to the install manager, to compose the download URL
3690
        if (packageInfo != null) {
3691
            installerManager.setVersion(packageInfo.getVersion());
3692
        } else {
3693
            installerManager.setVersion(gvSIGVersion);
3694
        }
3695
        if (!installURL.contains(";")
3696
                && !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION)
3697
                && !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION)) {
3698
            if (packageInfo != null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA)
3699
                    || packageInfo.getState().startsWith(InstallerManager.STATE.RC)
3700
                    || packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL))) {
3701
                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";
3702
            }
3703
        }
3704
        // Configure default index download URL
3705
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3706

    
3707
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3708

    
3709
        // Launch installer
3710
        PluginsManager manager = PluginsLocator.getManager();
3711

    
3712
        AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3713
                .getSwingInstallerManager().createInstallPackageWizard(
3714
                        manager.getApplicationFolder(),
3715
                        manager.getInstallFolder());
3716
        installPackageWizard.setWizardActionListener(new InstallerWizardActionListener() {
3717
            public void finish(InstallerWizardPanel installerWizard) {
3718
                logger.info("Finish installation.");
3719
                System.exit(0);
3720
            }
3721

    
3722
            public void cancel(InstallerWizardPanel installerWizard) {
3723
                logger.info("Cancel installation.");
3724
                System.exit(0);
3725
            }
3726
        });
3727

    
3728
        // the wizard will show the Typical or Advanced mode option.
3729
        installPackageWizard.setAskTypicalOrCustom(true);
3730
        // default packages will be selected.
3731
        installPackageWizard.setSelectDefaultPackages(true);
3732

    
3733
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3734

    
3735
        frame.addWindowListener(new WindowListener() {
3736
            public void windowOpened(WindowEvent we) {
3737
                logger.info("Open window installation.");
3738
            }
3739

    
3740
            public void windowClosing(WindowEvent we) {
3741
                logger.info("Closing installation.");
3742
                System.exit(0);
3743
            }
3744

    
3745
            public void windowClosed(WindowEvent we) {
3746
                logger.info("Close installation.");
3747
                System.exit(0);
3748
            }
3749

    
3750
            public void windowIconified(WindowEvent we) {
3751
            }
3752

    
3753
            public void windowDeiconified(WindowEvent we) {
3754
            }
3755

    
3756
            public void windowActivated(WindowEvent we) {
3757
                logger.info("Activate window installation.");
3758
            }
3759

    
3760
            public void windowDeactivated(WindowEvent we) {
3761
                logger.info("Deactivate window installation.");
3762
            }
3763
        });
3764
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3765

    
3766
        frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3767

    
3768
        URL iconURL = getClass().getResource("/images/main/install-icon.png");
3769
        if( iconURL!=null ) {
3770
            ImageIcon icon = new ImageIcon(iconURL);
3771
            frame.setIconImage(icon.getImage());
3772
        }
3773
        frame.pack();
3774
        frame.setLocationRelativeTo(null);
3775

    
3776
        frame.setVisible(true);
3777
    }
3778

    
3779
    public static String getInformation() {
3780
        return getInformation(null);
3781
    }
3782

    
3783
    private static final int INFO_OS_NAME = 0;
3784
    private static final int INFO_OS_ARCH = 1;
3785
    private static final int INFO_OS_VERSION = 2;
3786
    private static final int INFO_OS_ADITIONAL = 3;
3787
    private static final int INFO_JRE_VENDOR = 4;
3788
    private static final int INFO_JRE_VERSION = 5;
3789
    private static final int INFO_JRE_HOME = 6;
3790
    private static final int INFO_PROXY_HOST = 7;
3791
    private static final int INFO_PROXY_PORT = 8;
3792
    private static final int INFO_PROXY_USER = 9;
3793
    private static final int INFO_PROXY_PASSWORD = 10;
3794
    private static final int INFO_APP_LOCALE = 11;
3795
    private static final int INFO_APP_FOLDER = 12;
3796
    private static final int INFO_APP_HOME = 13;
3797
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3798
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3799
    private static final int INFO_APP_THEME = 16;
3800
    private static final int INFO_APP_SKIN = 17;
3801
    private static final int INFO_PACKAGES = 18;
3802

    
3803
    public static String getInformation(PackageInfo[] pkgs) {
3804

    
3805
        String template = "OS\n"
3806
                + "    name    : {" + INFO_OS_NAME + "}\n"
3807
                + "    arch    : {" + INFO_OS_ARCH + "}\n"
3808
                + "    version : {" + INFO_OS_VERSION + "} \n"
3809
                + "{" + INFO_OS_ADITIONAL + "}"
3810
                + "JRE\n"
3811
                + "    vendor  : {" + INFO_JRE_VENDOR + "}\n"
3812
                + "    version : {" + INFO_JRE_VERSION + "}\n"
3813
                + "    home    : {" + INFO_JRE_HOME + "}\n"
3814
                + "HTTP Proxy\n"
3815
                + "    http.proxyHost     : {" + INFO_PROXY_HOST + "}\n"
3816
                + "    http.proxyPort     : {" + INFO_PROXY_PORT + "}\n"
3817
                + "    http.proxyUserName : {" + INFO_PROXY_USER + "}\n"
3818
                + "    http.proxyPassword : {" + INFO_PROXY_PASSWORD + "}\n"
3819
                + "Application\n"
3820
                + "    locale language         : {" + INFO_APP_LOCALE + "}\n"
3821
                + "    application forlder     : {" + INFO_APP_FOLDER + "}\n"
3822
                + "    application home forlder: {" + INFO_APP_HOME + "}\n"
3823
                + "    install forlder         : {" + INFO_APP_INSTALL_FOLDER + "}\n"
3824
                + "    plugins forlder         : {" + INFO_APP_PLUGINS_FOLDER + "}\n"
3825
                + "    theme                   : {" + INFO_APP_THEME + "}\n"
3826
                + "    Skin                    : {" + INFO_APP_SKIN + "}\n"
3827
                + "Installed packages\n"
3828
                + "{" + INFO_PACKAGES + "}";
3829

    
3830
        String values[] = new String[INFO_PACKAGES + 1];
3831

    
3832
        PluginsManager pluginmgr = PluginsLocator.getManager();
3833
        LocaleManager localemgr = PluginsLocator.getLocaleManager();
3834

    
3835
        Properties props = System.getProperties();
3836

    
3837
        // OS information
3838
        values[INFO_OS_NAME] = props.getProperty("os.name");
3839
        values[INFO_OS_ARCH] = props.getProperty("os.arch");
3840
        values[INFO_OS_VERSION] = props.getProperty("os.version");
3841

    
3842
        if (values[INFO_OS_NAME].startsWith("Linux")) {
3843
            try {
3844
                StringWriter writer = new StringWriter();
3845

    
3846
                String[] command = {"lsb_release", "-a"};
3847
                Process p = Runtime.getRuntime().exec(command);
3848
                InputStream is = p.getInputStream();
3849
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
3850
                String line;
3851
                while ((line = reader.readLine()) != null) {
3852
                    writer.write("    " + line + "\n");
3853
                }
3854
                values[INFO_OS_ADITIONAL] = writer.toString();
3855
            } catch (Exception ex) {
3856
                logger.warn("Can't get detailled os information (lsb_release -a).", ex);
3857
            }
3858
        }
3859

    
3860
        values[INFO_JRE_VENDOR] = props.getProperty("java.vendor");
3861
        values[INFO_JRE_VERSION] = props.getProperty("java.version");
3862
        values[INFO_JRE_HOME] = props.getProperty("java.home");
3863
        values[INFO_PROXY_HOST] = props.getProperty("http.proxyHost");
3864
        values[INFO_PROXY_PORT] = props.getProperty("http.proxyPort");
3865
        values[INFO_PROXY_USER] = props.getProperty("http.proxyUserName");
3866

    
3867
        if (props.get("http.proxyPassword") == null) {
3868
            values[INFO_PROXY_PASSWORD] = "(null)";
3869
        } else {
3870
            values[INFO_PROXY_PASSWORD] = "***********";
3871
        }
3872

    
3873
        try {
3874
            values[INFO_APP_SKIN] = MDIManagerFactory.getSkinExtension().getClassName();
3875
        } catch (Throwable e) {
3876
            values[INFO_APP_SKIN] = "(unknow)";
3877
        }
3878
        values[INFO_APP_LOCALE] = localemgr.getCurrentLocale().toString();
3879
        values[INFO_APP_FOLDER] = pluginmgr.getApplicationFolder().getAbsolutePath();
3880
        values[INFO_APP_HOME] = pluginmgr.getApplicationHomeFolder().getAbsolutePath();
3881
        values[INFO_APP_INSTALL_FOLDER] = pluginmgr.getInstallFolder().getAbsolutePath();
3882
        values[INFO_APP_PLUGINS_FOLDER] = StringUtils.join(pluginmgr.getPluginsFolders());
3883
        values[INFO_APP_THEME] = Launcher.theme.getSource().getAbsolutePath();
3884

    
3885
        try {
3886
            if (pkgs == null) {
3887
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3888
                pkgs = installmgr.getInstalledPackages();
3889
            }
3890
            StringWriter writer = new StringWriter();
3891
            for (int i = 0; i < pkgs.length; i++) {
3892
                writer.write("    ");
3893
                writer.write(pkgs[i].toStringCompact());
3894
                writer.write("\n");
3895
            }
3896
            values[INFO_PACKAGES] = writer.toString();
3897

    
3898
        } catch (Throwable e) {
3899
            logger.warn("Can't get installed package information.", e);
3900
        }
3901

    
3902
        String s = MessageFormat.format(template, values);
3903
        return s;
3904
    }
3905

    
3906
    private void logger_info(String msg) {
3907
        String info[] = msg.split("\n");
3908
        for (int i = 0; i < info.length; i++) {
3909
            logger.info(info[i]);
3910
        }
3911
    }
3912

    
3913
    private void saveEnvironInformation(PackageInfo[] pkgs) {
3914
        PluginsManager manager = PluginsLocator.getManager();
3915
        File fout = new File(manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3916
        try {
3917
            FileUtils.write(fout, getInformation(pkgs));
3918
        } catch (IOException e) {
3919
            logger.info("Can't create '" + fout.getAbsolutePath() + "'");
3920
        }
3921
    }
3922

    
3923
    private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3924
        final Set<String> incompatiblePlugins = new HashSet<String>();
3925

    
3926
        // Add installed packages to a Map to optimize searchs
3927
        final Map<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
3928
        for (int i = 0; i < installedPackages.length; i++) {
3929
            packages.put(installedPackages[i].getCode(), installedPackages[i]);
3930
        }
3931
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
3932
        while (it.hasNext()) {
3933
            List<String> pluginNames = new ArrayList<String>();
3934
            Entry<String, PluginConfig> entry = it.next();
3935
            PluginConfig pluginConfig = entry.getValue();
3936
            pluginNames.add(entry.getKey());
3937

    
3938
                        // Locate the package for this plugin.
3939
            // Be care whith alias
3940
            String[] aliases = pluginsConfig.getAliases(pluginConfig);
3941
            if (aliases != null) {
3942
                for (int i = 0; i < aliases.length; i++) {
3943
                    pluginNames.add(aliases[i]);
3944
                }
3945
            }
3946
            PackageInfo pkg = null;
3947
            for (int n = 0; n < pluginNames.size(); n++) {
3948
                pkg = packages.get(pluginNames.get(n));
3949
                if (pkg != null) {
3950
                    break;
3951
                }
3952
            }
3953

    
3954
            // If package is found verify dependencies
3955
            if (pkg != null) {
3956
                Dependencies dependencies = pkg.getDependencies();
3957
                for (int i = 0; i < dependencies.size(); i++) {
3958
                    Dependency dependency = (Dependency) dependencies.get(i);
3959
                    if (Dependency.CONFLICT.equalsIgnoreCase(dependency.getType())) {
3960
                        String code = dependency.getCode();
3961
                        if (pluginsConfig.get(code) != null) {
3962
                            incompatiblePlugins.add(pkg.getCode());
3963
                            incompatiblePlugins.add(code);
3964
                        }
3965
                    }
3966
                }
3967
            }
3968
        }
3969
        if (incompatiblePlugins.isEmpty()) {
3970
            return;
3971
        }
3972
        splashWindow.toBack();
3973
        DisablePluginsConflictingDialog dlg = new DisablePluginsConflictingDialog(packages, incompatiblePlugins);
3974
        dlg.setVisible(true);
3975
        splashWindow.toFront();
3976
        switch (dlg.getAction()) {
3977
            case DisablePluginsConflictingDialog.CLOSE:
3978
                System.exit(0);
3979
                break;
3980
            case DisablePluginsConflictingDialog.CONTINUE:
3981
                break;
3982
        }
3983
        List<String> pluginsToDissable = dlg.getPluginNamesToDisable();
3984
        if (pluginsToDissable == null) {
3985
            return;
3986
        }
3987

    
3988
        Iterator<String> it2 = pluginsToDissable.iterator();
3989
        while (it2.hasNext()) {
3990
            String pluginName = it2.next();
3991
            logger.info("Dissabling plugin '" + pluginName + "' by user action.");
3992
            pluginsConfig.remove(pluginName);
3993
        }
3994
    }
3995

    
3996
    private class DisablePluginsConflictingDialog extends JDialog {
3997

    
3998
        public static final int CONTINUE = 0;
3999
        public static final int CLOSE = 1;
4000

    
4001
        private DisablePluginsConflictingLayoutPanel contents;
4002
        private int action = 0;
4003
        private List<Item> incompatiblePlugins = null;
4004
        private Map<String, PackageInfo> packages;
4005

    
4006
        private class Item {
4007

    
4008
            private String code;
4009
            private PackageInfo pkg;
4010

    
4011
            public Item(String code, PackageInfo pkg) {
4012
                this.code = code;
4013
                this.pkg = pkg;
4014
            }
4015

    
4016
            public String toString() {
4017
                if (this.pkg == null) {
4018
                    return code;
4019
                }
4020
                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
4021
            }
4022

    
4023
            public String getCode() {
4024
                if (pkg == null) {
4025
                    return code;
4026
                }
4027
                return pkg.getCode();
4028
            }
4029
        }
4030

    
4031
        DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
4032
            super((Frame) null, "", true);
4033
            this.setTitle(translate("_Conflicting_plugins"));
4034

    
4035
            this.packages = packages;
4036

    
4037
            this.incompatiblePlugins = new ArrayList<Item>();
4038
            Item item = null;
4039
            Iterator<String> it = incompatiblePlugins.iterator();
4040
            while (it.hasNext()) {
4041
                String code = it.next();
4042
                item = new Item(code, packages.get(code));
4043
                this.incompatiblePlugins.add(item);
4044
                logger.info("Found plugin '" + item.getCode() + "' incopatibles with each other.");
4045
            }
4046
            initComponents();
4047
        }
4048

    
4049
        private void initComponents() {
4050
            this.contents = new DisablePluginsConflictingLayoutPanel();
4051

    
4052
            doTranslations();
4053

    
4054
            this.contents.buttonClose.addActionListener(new ActionListener() {
4055
                public void actionPerformed(ActionEvent arg0) {
4056
                    doClose();
4057
                }
4058
            });
4059
            this.contents.buttonContinue.addActionListener(new ActionListener() {
4060
                public void actionPerformed(ActionEvent arg0) {
4061
                    doContinue();
4062
                }
4063
            });
4064
            this.contents.pluginList.setModel(new DefaultListModel(this.incompatiblePlugins));
4065
            ListSelectionModel sm = this.contents.pluginList.getSelectionModel();
4066
            sm.setSelectionMode(sm.MULTIPLE_INTERVAL_SELECTION);
4067
            this.setContentPane(this.contents);
4068
            this.pack();
4069

    
4070
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
4071
            setLocation((screenSize.width / 2) - (this.getWidth() / 2),
4072
                    (screenSize.height / 2) - (this.getHeight() / 2));
4073
        }
4074

    
4075
        private void doTranslations() {
4076
            DisablePluginsConflictingLayoutPanel c = this.contents;
4077
            c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
4078
            c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
4079
            c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
4080
            c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
4081
            c.buttonClose.setText(translate("_Close"));
4082
            c.buttonContinue.setText(translate("_Continue"));
4083
        }
4084

    
4085
        private String translate(String msg) {
4086
            return PluginServices.getText(this, msg);
4087
        }
4088

    
4089
        private void doClose() {
4090
            this.action = CLOSE;
4091
            this.setVisible(false);
4092
        }
4093

    
4094
        private void doContinue() {
4095
            this.action = CONTINUE;
4096
            this.setVisible(false);
4097
        }
4098

    
4099
        public int getAction() {
4100
            return this.action;
4101
        }
4102

    
4103
        public List<String> getPluginNamesToDisable() {
4104
            if (this.action == CLOSE) {
4105
                return null;
4106
            }
4107
            Object[] selecteds = null;
4108
            selecteds = (Object[]) this.contents.pluginList.getSelectedValues();
4109
            if (selecteds == null || selecteds.length < 1) {
4110
                return null;
4111
            }
4112
            List<String> values = new ArrayList<String>();
4113
            for (int i = 0; i < selecteds.length; i++) {
4114
                values.add(((Item) selecteds[i]).getCode());
4115
            }
4116
            return values;
4117
        }
4118
    }
4119

    
4120
    private void initializeIdentityManagement(File pluginsFolder) {
4121
        File identityManagementConfigFile = null;
4122
        PluginServices plugin = null;
4123
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
4124
        while (it.hasNext()) {
4125
            Entry<String, PluginConfig> entry = it.next();
4126
            File pluginFolder = new File(pluginsFolder, entry.getKey());
4127
            File f = new File(pluginFolder, "identity-management.ini");
4128
            if (f.exists()) {
4129
                if (identityManagementConfigFile != null) {
4130
                    logger.warn("Too many identity-managemnt plugins. Disable all.");
4131
                } else {
4132
                    identityManagementConfigFile = f;
4133
                    plugin = PluginServices.getPluginServices(entry.getKey());
4134
                }
4135
            }
4136
        }
4137
        if(plugin != null){
4138
                new DefaultLibrariesInitializer(plugin.getClassLoader()).fullInitialize(true);
4139
        }
4140
        
4141
        if (identityManagementConfigFile == null || plugin == null) {
4142
            return;
4143
        }
4144
        if (!identityManagementConfigFile.canRead()) {
4145
            return;
4146
        }
4147
        PropertiesConfiguration identityManagementConfig = null;
4148
        try {
4149
            identityManagementConfig = new PropertiesConfiguration(identityManagementConfigFile);
4150
        } catch (Exception ex) {
4151
            logger.warn("Can't open identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.", ex);
4152
            return;
4153
        }
4154
        String identityManagerClassName = identityManagementConfig.getString("IdentityManager", null);
4155
        String identityManagementInitializerClassName = identityManagementConfig.getString("IdentityManagementInitializer", null);
4156
        try {
4157
            if (identityManagerClassName != null) {
4158
                Class identityManagerClass = plugin.getClassLoader().loadClass(identityManagerClassName);
4159
                ToolsLocator.registerIdentityManager(identityManagerClass);
4160
            } else {
4161
                logger.info("Entry IdentityManager not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4162
            }
4163

    
4164
            if (identityManagementInitializerClassName != null) {
4165
                Class identityManagerInitializerClass = plugin.getClassLoader().loadClass(identityManagementInitializerClassName);
4166
                Runnable identityManagerInitializer = (Runnable) identityManagerInitializerClass.newInstance();
4167
                identityManagerInitializer.run();
4168
            } else {
4169
                logger.info("Entry IdentityManagementInitializer not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4170
            }
4171

    
4172
        } catch (Exception ex) {
4173
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4174
            return;
4175
        }
4176
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4177
    }
4178

    
4179
}