Statistics
| Revision:

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

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.lang3.JavaVersion;
101
import org.apache.commons.lang3.StringUtils;
102
import org.apache.commons.lang3.SystemUtils;
103
import org.apache.log4j.AppenderSkeleton;
104
import org.apache.log4j.PatternLayout;
105
import org.apache.log4j.PropertyConfigurator;
106
import org.apache.log4j.RollingFileAppender;
107
import org.apache.log4j.spi.LoggingEvent;
108
import org.apache.log4j.spi.ThrowableInformation;
109
import org.exolab.castor.xml.MarshalException;
110
import org.exolab.castor.xml.ValidationException;
111

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

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

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

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

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

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

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

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

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

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

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

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

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

    
299
            return item;
300
        }
301

    
302
    }
303

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

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

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

    
323
    }
324

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

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

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

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

    
353
    protected static ListBaseException launcherrors = null;
354

    
355
    protected static Theme theme = null;
356

    
357
    private List<String> deprecatedPluginNames = null;
358

    
359
    private static final class ProxyAuth extends Authenticator {
360

    
361
        private PasswordAuthentication auth;
362

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

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

    
372
    private static Launcher launcherInstance;
373

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

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

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

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

    
406
    public static class LaunchException extends ListBaseException {
407

    
408
        private static final long serialVersionUID = 4541192746962684705L;
409

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

    
416
    }
417

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

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

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

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

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

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

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

    
461
        initializeApp(args, null);
462

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
695
        splashWindow.close();
696

    
697
        frame.setCursor(Cursor.DEFAULT_CURSOR);
698

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

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

    
710
    }
711

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

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

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

    
741
    }
742

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

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

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

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

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

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

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

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

    
821
        configureLocales(args);
822

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

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

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

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

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

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

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

    
905
    private class NotificationAppender extends AppenderSkeleton {
906

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

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

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

    
931
        }
932

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

    
939
    }
940

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1197
        XMLEntity entity = new XMLEntity();
1198

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

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

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

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

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

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

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

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

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

    
1270
        Class<? extends IExtension> skinClass;
1271

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

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

    
1301
    }
1302

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

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

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

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

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

    
1364
    }
1365

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

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

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

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

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

    
1396
    private void initializeExtensions() {
1397

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1643
            Extensions extensionConfig = pluginConfig.getExtensions();
1644

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

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

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

    
1678
        }
1679
    }
1680

    
1681
    private TreeSet<SortableMenu> getOrderedMenus() {
1682

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1749
        }
1750

    
1751
        return orderedMenus;
1752
    }
1753

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

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

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

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

    
1777
    public class PluginMenuItem {
1778

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2618
    }
2619

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2716
        return null;
2717
    }
2718

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

    
2723
    private static class ExtensionComparator implements Comparator {
2724

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

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

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

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

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

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

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

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

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

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

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

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

    
2783
        }
2784
    }
2785

    
2786
    private static class SortableMenu {
2787

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

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

    
2799
    }
2800

    
2801
    private static class SortableTool {
2802

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2954
        return UIManager.getSystemLookAndFeelClassName();
2955
    }
2956

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3269
    }
3270

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

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

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

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

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

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

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

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

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

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

    
3343
            System.exit(0);
3344
        }
3345

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

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

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

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

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

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

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

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

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

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

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

    
3480
                }
3481

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

    
3486
                }
3487

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

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

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

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

    
3545
    }
3546

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

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

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

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

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

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

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

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

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

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

    
3658
        initializeApp(myArgs, "installer");
3659

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

    
3662
        initializeInstallerManager();
3663

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

    
3680
        AndamiConfig config = getAndamiConfig();
3681

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

    
3684
        initializeLibraries();
3685

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3775
        frame.setVisible(true);
3776
    }
3777

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

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

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

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

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

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

    
3834
        Properties props = System.getProperties();
3835

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3995
    private class DisablePluginsConflictingDialog extends JDialog {
3996

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

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

    
4005
        private class Item {
4006

    
4007
            private String code;
4008
            private PackageInfo pkg;
4009

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

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

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

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

    
4034
            this.packages = packages;
4035

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

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

    
4051
            doTranslations();
4052

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

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

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

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

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

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

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

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

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

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

    
4167
        } catch (Exception ex) {
4168
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4169
            return;
4170
        }
4171
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4172
    }
4173

    
4174
}