Statistics
| Revision:

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

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.WindowAdapter;
36
import java.awt.event.WindowEvent;
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.prefs.Preferences;
79

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

    
91

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

    
111
import org.gvsig.andami.actioninfo.ActionInfo;
112
import org.gvsig.andami.actioninfo.ActionInfoManager;
113
import org.gvsig.andami.config.generate.Andami;
114
import org.gvsig.andami.config.generate.AndamiConfig;
115
import org.gvsig.andami.config.generate.Plugin;
116
import org.gvsig.andami.impl.DefaultArguments;
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.InstallWizardPanel;
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
    private static Arguments arguments;
207

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

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

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

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

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

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

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

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

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

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

    
301
            return item;
302
        }
303

    
304
    }
305

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

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

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

    
325
    }
326

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

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

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

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

    
355
    protected static ListBaseException launcherrors = null;
356

    
357
    protected static Theme theme = null;
358

    
359
    private List<String> deprecatedPluginNames = null;
360

    
361
    private static final class ProxyAuth extends Authenticator {
362

    
363
        private PasswordAuthentication auth;
364

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

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

    
374
    private static Launcher launcherInstance;
375

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

    
383
    public static void main(final String[] args) throws Exception {
384
        arguments = new DefaultArguments(args);
385

    
386
        final Launcher launcher = getInstance();
387
        try {
388
            if (arguments.contains("install")) {
389
                launcher.doInstall(args);
390
            } else {
391
                launcher.doMain(args);
392
            }
393
        } catch (Exception e) {
394
            logger.error("excepcion al arrancar", e);
395
            System.exit(-1);
396
        }
397
    }
398

    
399
    protected void downloadExtensions(String extDir) {
400
        // do nothing
401
    }
402

    
403
    public static class LaunchException extends ListBaseException {
404

    
405
        private static final long serialVersionUID = 4541192746962684705L;
406

    
407
        public LaunchException() {
408
            super("Errors in initialization of application.",
409
                    "_errors_in_initialization_of_application",
410
                    serialVersionUID);
411
        }
412

    
413
    }
414

    
415
    protected void addError(Throwable ex) {
416
        if (launcherrors == null) {
417
            launcherrors = new LaunchException();
418
        }
419
        launcherrors.add(ex);
420
    }
421

    
422
    protected void addError(String msg, Throwable cause) {
423
        logger.error(msg, cause);
424
        this.addError(new RuntimeException(msg, cause));
425
    }
426

    
427
    protected void addError(String msg) {
428
        this.addError(msg, null);
429
    }
430

    
431
    private String translate(String msg) {
432
        return PluginServices.getText(Launcher.class, msg);
433
    }
434

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

    
449
    public static Arguments getArguments() {
450
        return arguments;
451
    }
452

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

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

    
462
        initializeApp(args, null);
463

    
464
        // Solucionamos el problema de permisos que se produc?do con Java
465
        // Web Start con este codigo.
466
        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
684
        message(translate("SplashWindow.enable_controls"));
685
        SwingUtilities.invokeAndWait(new Runnable() {
686
            public void run() {
687
                try {
688
                    frame.enableControls();
689
                } 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
        // Hacemos visibles los argumentos como una propiedad est?tica
802
        // de plugin services para quien lo quiera usar (por ejemplo, para
803
        // cargar un proyecto por l?nea de comandos)
804
        PluginServices.setArguments(args);
805

    
806
        getOrCreateConfigFolder();
807
        configureLogging(appName, applicationClasifier);
808
        if (!validJVM()) {
809
            logger.error("Not a valid JRE. Exit application.");
810
            System.exit(-1);
811
        }
812

    
813
        ToolsLocator.registerDefaultToolsLibraries();
814

    
815
        ToolsLocator.getFoldersManager().cleanTemporaryFiles();
816

    
817
        if (args.length < 2) {
818
            loadAndamiConfig("gvSIG/extensiones"); // Valor por defecto
819
        } else {
820
            loadAndamiConfig(args[1]);
821
        }
822

    
823
        configureLocales();
824

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

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

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

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

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

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

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

    
903
    public static String getApplicationName() {
904
        return appName;
905
    }
906

    
907
    private class NotificationAppender extends AppenderSkeleton {
908

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

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

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

    
933
        }
934

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

    
941
    }
942

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1199
        XMLEntity entity = new XMLEntity();
1200

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

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

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

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

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

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

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

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

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

    
1272
        Class<? extends IExtension> skinClass;
1273

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

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

    
1303
    }
1304

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

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

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

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

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

    
1366
    }
1367

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

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

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

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

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

    
1398
    private void initializeExtensions() {
1399

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1645
            Extensions extensionConfig = pluginConfig.getExtensions();
1646

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

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

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

    
1680
        }
1681
    }
1682

    
1683
    private TreeSet<SortableMenu> getOrderedMenus() {
1684

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1751
        }
1752

    
1753
        return orderedMenus;
1754
    }
1755

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

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

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

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

    
1779
    public class PluginMenuItem {
1780

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1850
    private List<ToolBar> getOrderedToolBars() {
1851
        Map<String, ToolBar> toolbars = new HashMap<>();
1852

    
1853
        Iterator<String> pluginNames = pluginsConfig.keySet().iterator();
1854
        while (pluginNames.hasNext()) {
1855
            String pluginName = pluginNames.next();
1856
            String extensionName = "unknow";
1857
            try {
1858
                PluginConfig pc = pluginsConfig.get(pluginName);
1859
                Extension[] extensions = pc.getExtensions().getExtension();
1860
                for (Extension extension : extensions) {
1861
                    extensionName = extension.getClassName();
1862
                    ToolBar[] extensionToolbars = extension.getToolBar();
1863
                    for (ToolBar toolbar : extensionToolbars) {
1864
                        ToolBar x = toolbars.get(toolbar.getName());
1865
                        if ( x!=null ) {
1866
                            if( !x.hasPosition() && toolbar.hasPosition() ) {
1867
                                toolbars.put(toolbar.getName(), toolbar);
1868
                            }
1869
                        } else {
1870
                            toolbars.put(toolbar.getName(), toolbar);
1871
                        }
1872
                    }
1873
                }
1874
            } catch (Exception ex) {
1875
                addError("Can't process tool-bars of extension '"+extensionName+"'.", ex);
1876
            }
1877
        }
1878
        for (Entry<String, ToolBar> entrySet : toolbars.entrySet()) {
1879
            ToolBar toolBar = entrySet.getValue();
1880
            if( toolBar.hasPosition() && toolBar.getPosition()<100 ) {
1881
                toolBar.setPosition( toolBar.getPosition()+11000);
1882
            }
1883
        }
1884
        List<ToolBar> toolBarsList = new ArrayList<>(toolbars.values());
1885
        Collections.sort(toolBarsList, new Comparator<ToolBar>() {
1886

    
1887
            @Override
1888
            public int compare(ToolBar o1, ToolBar o2) {
1889
                return Integer.compare(o1.getPosition(), o2.getPosition());
1890
            }
1891
        });
1892
        return toolBarsList;
1893
    }
1894

    
1895
    /**
1896
     * Installs the menus, toolbars, actiontools, selectable toolbars and
1897
     * combos. The order in which they are shown is determined here.
1898
     */
1899
    private void installPluginsControls() {
1900
        logger.info("installPluginsControls (toolbars)");
1901
        installPluginsControlsToToolsbar();
1902
        installPluginsControlsToStatusbar();
1903
    }
1904

    
1905
    private void installPluginsControlsToToolsbar() {
1906

    
1907
        Map<String,List<SortableTool>> toolsByToolbar = new HashMap<>();
1908
        // A?ade primero las toolbars ordenadas para garantizar el orden de estas
1909
        // Y inicializa las listas del Map.
1910
        for( ToolBar toolbar : getOrderedToolBars() ) {
1911
            frame.addToolBar(toolbar.getName(), toolbar.getDescription(), toolbar.getPosition());
1912
            ArrayList<SortableTool> tools = new ArrayList<>();
1913
            toolsByToolbar.put(toolbar.getName(),tools);
1914
        }
1915
        for( Entry<String, PluginConfig> entry : pluginsConfig.entrySet() ) {
1916
            String pluginName = entry.getKey();
1917
            PluginConfig pluginConfig = entry.getValue();
1918
            PluginServices plugin = pluginsServices.get(pluginName);
1919
            PluginClassLoader loader = plugin.getClassLoader();
1920
            Extension[] pluginExtensions = pluginConfig.getExtensions().getExtension();
1921
            for( Extension pluginExtension : pluginExtensions ) {
1922
                ToolBar[] pluginToolbars = pluginExtension.getToolBar();
1923
                for( ToolBar pluginToolbar : pluginToolbars ) {
1924
                    ActionTool[] actionTools = pluginToolbar.getActionTool();
1925
                    for( ActionTool actionTool : actionTools ) {
1926
                        List<SortableTool> toolbar = toolsByToolbar.get(pluginToolbar.getName());
1927
                        toolbar.add(new SortableTool(loader, pluginExtension, pluginToolbar, actionTool));
1928
                    }
1929
                    SelectableTool[] selectableTools = pluginToolbar.getSelectableTool();
1930
                    for( SelectableTool selectableTool : selectableTools ) {
1931
                        List<SortableTool> toolbar = toolsByToolbar.get(pluginToolbar.getName());
1932
                        toolbar.add(new SortableTool(loader, pluginExtension, pluginToolbar, selectableTool));
1933
                    }
1934
                }
1935
            }
1936
        }
1937
        for( Entry<String, List<SortableTool>> entry : toolsByToolbar.entrySet() ) {
1938
            String toolbarName = entry.getKey();
1939
            List<SortableTool> tools = entry.getValue();
1940
            Collections.sort(tools, new Comparator<SortableTool>() {
1941
                @Override
1942
                public int compare(SortableTool o1, SortableTool o2) {
1943
                    return Long.compare(o1.getPosition(), o2.getPosition());
1944
                }
1945
            });
1946

    
1947
            for( SortableTool tool : tools ) {
1948
                try {
1949
                    if (tool.actiontool != null) {
1950
                        frame.addTool(tool.loader, tool.extension,
1951
                            tool.toolbar, tool.actiontool
1952
                        );
1953
                    } else {
1954
                        frame.addTool(tool.loader, tool.extension,
1955
                            tool.toolbar, tool.selectabletool
1956
                        );
1957
                    }
1958
                } catch (Exception ex) {
1959
                }
1960
            }
1961
        }
1962
    }
1963

    
1964
    private void installPluginsControlsToStatusbar() {
1965
        Iterator<String> pluginNames = pluginsConfig.keySet().iterator();
1966

    
1967
        Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1968
        Set<Extension> orderedExtensions = new TreeSet<Extension>(new ExtensionComparator());
1969

    
1970
        while (pluginNames.hasNext()) {
1971
            String pluginName = pluginNames.next();
1972
            try {
1973
                PluginConfig pc = pluginsConfig.get(pluginName);
1974
                PluginServices ps = pluginsServices.get(pluginName);
1975

    
1976
                Extension[] exts = pc.getExtensions().getExtension();
1977

    
1978
                for (int j = 0; j < exts.length; j++) {
1979
                    String cname = "unknow";
1980
                    try {
1981
                        cname = exts[j].getClassName();
1982
                        if (exts[j].getActive() && !cname.equals(LibraryExtension.class.getName())) {
1983
                            if (orderedExtensions.contains(exts[j])) {
1984
                                this.addError(
1985
                                    Messages.getString("Launcher.Two_extensions_with_the_same_priority")
1986
                                    + cname
1987
                                );
1988
                            }
1989

    
1990
                            orderedExtensions.add(exts[j]);
1991
                            extensionPluginServices.put(exts[j], ps);
1992
                        }
1993
                    } catch (Throwable e) {
1994
                        addError("Error initializing controls of plugin '"
1995
                                + pluginName + "' extension '" + cname + "'", e);
1996
                    }
1997
                }
1998
            } catch (Throwable e) {
1999
                addError("Error initializing controls of plugin '" + pluginName
2000
                        + "'", e);
2001
            }
2002
        }
2003

    
2004
        Iterator<Extension> e = orderedExtensions.iterator();
2005

    
2006
        // load the combo-scales and combo-buttons for the status bar
2007
        while (e.hasNext()) {
2008
            Extension ext = e.next();
2009
            String extName = "unknow";
2010
            try {
2011
                extName = ext.getClassName();
2012

    
2013
                // get controls for statusBar
2014
                PluginServices ps = extensionPluginServices.get(ext);
2015
                PluginClassLoader loader = ps.getClassLoader();
2016

    
2017
                ComboScale[] comboScaleArray = ext.getComboScale();
2018
                for (int k = 0; k < comboScaleArray.length; k++) {
2019
                    org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
2020
                    String label = comboScaleArray[k].getLabel();
2021
                    if (label != null) {
2022
                        combo.setLabel(label);
2023
                    }
2024
                    String name = comboScaleArray[k].getName();
2025
                    if (name != null) {
2026
                        combo.setName(name);
2027
                    }
2028
                    String[] elementsString = ((String) comboScaleArray[k]
2029
                            .getElements()).split(";");
2030
                    long[] elements = new long[elementsString.length];
2031
                    for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
2032
                        try {
2033
                            elements[currentElem] = Long
2034
                                    .parseLong(elementsString[currentElem]);
2035
                        } catch (NumberFormatException nfex1) {
2036
                            this
2037
                                    .addError(ext.getClassName()
2038
                                            + " -- "
2039
                                            + Messages
2040
                                            .getString("error_parsing_comboscale_elements"));
2041
                            elements[currentElem] = 0;
2042
                        }
2043
                    }
2044
                    combo.setItems(elements);
2045
                    try {
2046
                        long value = Long.parseLong((String) comboScaleArray[k]
2047
                                .getValue());
2048
                        combo.setScale(value);
2049
                    } catch (NumberFormatException nfex2) {
2050
                        this
2051
                                .addError(ext.getClassName()
2052
                                        + " -- "
2053
                                        + Messages
2054
                                        .getString("error_parsing_comboscale_value"));
2055
                    }
2056
                    try {
2057
                        frame.addStatusBarControl(loader.loadClass(ext
2058
                                .getClassName()), combo);
2059
                    } catch (ClassNotFoundException e1) {
2060
                        this
2061
                                .addError(
2062
                                        Messages
2063
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2064
                                        e1);
2065
                    }
2066
                }
2067

    
2068
                ComboButton[] comboButtonArray = ext.getComboButton();
2069
                for (int k = 0; k < comboButtonArray.length; k++) {
2070
                    ComboButtonElement[] elementList = comboButtonArray[k]
2071
                            .getComboButtonElement();
2072
                    org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
2073
                    String name = comboButtonArray[k].getName();
2074
                    if (name != null) {
2075
                        combo.setName(name);
2076
                    }
2077
                    for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
2078
                        ComboButtonElement element = elementList[currentElement];
2079
                        ImageIcon icon;
2080
                        URL iconLocation = loader
2081
                                .getResource(element.getIcon());
2082
                        if (iconLocation == null) {
2083
                            this.addError(Messages.getString("Icon_not_found_")
2084
                                    + element.getIcon());
2085
                        } else {
2086
                            icon = new ImageIcon(iconLocation);
2087
                            JButton button = new JButton(icon);
2088
                            combo.addButton(button);
2089
                            button.setActionCommand(element.getActionCommand());
2090
                        }
2091
                    }
2092
                    try {
2093
                        frame.addStatusBarControl(loader.loadClass(ext
2094
                                .getClassName()), combo);
2095
                    } catch (ClassNotFoundException e1) {
2096
                        this
2097
                                .addError(
2098
                                        Messages
2099
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2100
                                        e1);
2101
                    }
2102
                }
2103
            } catch (Throwable e2) {
2104
                addError(
2105
                        "Error initializing tools and status bars of extension '"
2106
                        + extName + "'", e2);
2107
            }
2108
        }
2109

    
2110
    }
2111

    
2112
    /**
2113
     * Adds new plugins to the the andami-config file.
2114
     */
2115
    private void updateAndamiConfig() {
2116
        Set<String> olds = new HashSet<String>();
2117

    
2118
        Plugin[] plugins = andamiConfig.getPlugin();
2119

    
2120
        for (int i = 0; i < plugins.length; i++) {
2121
            olds.add(plugins[i].getName());
2122
        }
2123

    
2124
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2125

    
2126
        while (i.hasNext()) {
2127
            PluginServices ps = i.next();
2128

    
2129
            if (!olds.contains(ps.getPluginName())) {
2130
                Plugin p = new Plugin();
2131
                p.setName(ps.getPluginName());
2132
                p.setUpdate(false);
2133

    
2134
                andamiConfig.addPlugin(p);
2135
            }
2136
        }
2137
    }
2138

    
2139
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2140
        URL[] urls = null;
2141

    
2142
        String libfolderPath = pluginConfig.getLibraries().getLibraryDir();
2143
        File libFolderFile = new File(pluginConfig.getPluginFolder(), libfolderPath);
2144

    
2145
        File[] files = libFolderFile.listFiles(new FileFilter() {
2146

    
2147
            public boolean accept(File pathname) {
2148
                return (pathname.getName().toUpperCase().endsWith(".JAR")
2149
                        || pathname.getName().toUpperCase().endsWith(".ZIP"));
2150
            }
2151
        });
2152
        if (files == null) {
2153
            urls = new URL[0];
2154
        } else {
2155
            urls = new URL[files.length];
2156
            for (int j = 0; j < files.length; j++) {
2157
                try {
2158
                    urls[j] = new URL("file:" + files[j]);
2159
                } catch (MalformedURLException e) {
2160
                    logger.warn("Can't add file '" + files[j] + "' to the classpath of plugin '" + pluginConfig.getPluginName() + "'.");
2161
                }
2162
            }
2163
        }
2164
        return urls;
2165
    }
2166

    
2167
    private static class OrderedPlugins extends ArrayList<String> {
2168

    
2169
        private List<String> problems = new ArrayList<String>();
2170
        private int retries = 0;
2171
        private PluginsConfig pluginsConfig = null;
2172
        private List<String> deprcatedPluginNames = null;
2173

    
2174
        OrderedPlugins(PluginsConfig pluginsConfig, List<String>deprcatedPluginNames) {
2175
            super();
2176
            this.pluginsConfig = pluginsConfig;
2177
            this.deprcatedPluginNames = deprcatedPluginNames;
2178
            List<String> pluginNames = new ArrayList<String>();
2179
            for (String pluginName : pluginsConfig.keySet()) {
2180
                pluginNames.add(pluginName);
2181
            }
2182
            Collections.sort(pluginNames);
2183
            for (String pluginName : pluginNames) {
2184
                this.add(pluginName);
2185
            }
2186
        }
2187

    
2188
        public List<String> getProblems() {
2189
            return this.problems;
2190
        }
2191

    
2192
        private void addProblem(String msg) {
2193
           this.problems.add(msg);
2194
        }
2195

    
2196
        public boolean add(String pluginName) {
2197
            return this.add(pluginName,new ArrayList<String>());
2198
        }
2199

    
2200
        private boolean add(String pluginName, List<String>processing) {
2201
            pluginName = this.pluginsConfig.getMainKey(pluginName);
2202
            if( this.contains(pluginName) ) {
2203
                return true;
2204
            }
2205
            if( processing.contains(pluginName) ) {
2206
                this.addProblem("Dependencias ciclicas procesando '"+pluginName+"'.");
2207
                return true;
2208
            }
2209
            PluginConfig pluginConfig = this.pluginsConfig.get(pluginName);
2210
            Depends[] dependencies = pluginConfig.getDepends();
2211
            if( dependencies.length==0 ) {
2212
               super.add(pluginName);
2213
               return true;
2214
            }
2215
            if( this.retries > 100 ) {
2216
               this.addProblem("Posible dependencias ciclicas procesando '"+pluginName+"'." );
2217
               return false;
2218
            }
2219
            processing.add(pluginName);
2220
            boolean dependenciesAvailables = true;
2221
            for (Depends dependency : dependencies) {
2222
                String dependencyName = dependency.getPluginName();
2223
                if (deprcatedPluginNames.contains(dependencyName)) {
2224
                    this.addProblem("Plugin '" + pluginName + "' use a deprecated plugin name '" + dependencyName + "' as dependency. Must use '" + pluginsConfig.getMainKey(dependencyName) + "'.");
2225
                }
2226
                PluginConfig dependencyConfig = this.pluginsConfig.get(dependencyName);
2227
                if( dependencyConfig == null) {
2228
                  if( dependency.getOptional() ) {
2229
                    this.addProblem("Plugin '" + pluginName + "', declare an optional dependency '" + dependencyName + "' that not found.");
2230
                    continue;
2231
                  }
2232
                  dependenciesAvailables = false;
2233
                  this.addProblem("Plugin '"+pluginName+"' declara a dependency '"+dependencyName+"' that not found.");
2234
                  continue;
2235
                }
2236
                this.retries++;
2237
                if( ! (this.add(dependencyName, processing)) ) {
2238
                  dependenciesAvailables = false;
2239
                }
2240
                this.retries--;
2241
            }
2242
            if( dependenciesAvailables ) {
2243
                super.add(pluginName);
2244
            } else {
2245
              this.addProblem("Plugin '"+pluginName+"' no disponible, alguna dependencia no resuelta.");
2246
              return false;
2247
            }
2248
            return true;
2249
        }
2250
    }
2251

    
2252
    private void loadPluginServices() {
2253
        OrderedPlugins orderedPlugins = new OrderedPlugins(pluginsConfig, getDeprecatedPluginNames());
2254

    
2255
        if( !orderedPlugins.getProblems().isEmpty() ) {
2256
            for (String problem : orderedPlugins.getProblems()) {
2257
                logger.warn(problem);
2258
            }
2259
        }
2260

    
2261
        for (String pluginName : orderedPlugins) {
2262
            PluginConfig config = pluginsConfig.get(pluginName);
2263

    
2264
            URL[] urls = getPluginClasspathURLs(config);
2265

    
2266
            List<PluginClassLoader> loaders = new ArrayList<PluginClassLoader>();
2267
            for (Depends dependency : config.getDepends()) {
2268
                String dependencyName = dependency.getPluginName();
2269
                PluginServices dependencyPluginService = pluginsServices.get(dependencyName);
2270
                if( dependencyPluginService == null ) {
2271
                    if( dependency.getOptional() ) {
2272
                        logger.info("Procesing plugin '"+pluginName+", optional dependency not found ("+dependencyName+").");
2273
                    } else {
2274
                        logger.warn("Procesing plugin '"+pluginName+", dependency not found ("+dependencyName+").");
2275
                    }
2276
                    continue;
2277
                }
2278
                loaders.add(dependencyPluginService.getClassLoader());
2279
            }
2280
            try {
2281
                PluginClassLoader loader = new PluginClassLoader(
2282
                        urls,
2283
                        config.getPluginFolder().getAbsolutePath(),
2284
                        Launcher.class.getClassLoader(),
2285
                        loaders
2286
                );
2287
                PluginServices ps = new PluginServices(
2288
                        loader,
2289
                        PluginsConfig.getAlternativeNames(config)
2290
                );
2291
                logger.info("Plugin '" + pluginName + "' created");
2292
                pluginsServices.put(ps.getPluginName(), ps);
2293
                pluginsOrdered.add(pluginName);
2294
            } catch (IOException ex) {
2295
                logger.warn("Can't create PluginServices for '" + pluginName + "'.", ex);
2296
            }
2297
        }
2298

    
2299
        // Se eliminan los plugins que no fueron instalados
2300
        List<String> pluginsToRemove = new ArrayList<String>();
2301
        for (String pluginName : pluginsConfig.keySet()) {
2302
            PluginServices pluginService = pluginsServices.get(pluginName);
2303
            if( pluginService == null ) {
2304
                pluginsToRemove.add(pluginName);
2305
            }
2306
        }
2307
        for (String pluginName : pluginsToRemove) {
2308
            logger.warn("Removed plugin "+pluginName+".");
2309
            pluginsConfig.remove(pluginName);
2310
       }
2311
    }
2312

    
2313
    /*
2314
    private void dumpPluginsDependencyInformation() {
2315
        logger.info("Plugin dependency information");
2316
        Iterator<String> i = pluginsConfig.keySet().iterator();
2317
        while (i.hasNext()) {
2318
            String pluginName = i.next();
2319
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2320
            logger.info("  Plugin " + pluginName);
2321
            Depends[] dependencies = config.getDepends();
2322
            for (int j = 0; j < dependencies.length; j++) {
2323
                Depends dependency = dependencies[j];
2324
                String dependencyName = dependency.getPluginName();
2325
                logger.info("    Dependency " + dependencyName);
2326
            }
2327
        }
2328
    }
2329
    */
2330
    private void pluginsMessages() {
2331
        Iterator<String> iterator = pluginsOrdered.iterator();
2332
        PluginConfig config;
2333
        PluginServices ps;
2334

    
2335
        while (iterator.hasNext()) {
2336
            String pluginName = iterator.next();
2337
            config = pluginsConfig.get(pluginName);
2338
            ps = pluginsServices.get(pluginName);
2339

    
2340
            if ((config.getResourceBundle() != null)
2341
                    && !config.getResourceBundle().getName().equals("")) {
2342
                // add the locale files associated with the plugin
2343
                org.gvsig.i18n.Messages.addResourceFamily(config
2344
                        .getResourceBundle().getName(), ps.getClassLoader(),
2345
                        pluginName);
2346
                org.gvsig.i18n.Messages.addResourceFamily("i18n." + config
2347
                        .getResourceBundle().getName(), ps.getClassLoader(),
2348
                        pluginName);
2349
            }
2350
        }
2351
    }
2352

    
2353
    static public PluginServices getPluginServices(String name) {
2354
        return (PluginServices) pluginsServices.get(name);
2355
    }
2356

    
2357
    static String getPluginsDir() {
2358
        return andamiConfig.getPluginsDirectory();
2359
    }
2360

    
2361
    static File getPluginFolder(String pluginName) {
2362
        return pluginsConfig.get(pluginName).getPluginFolder();
2363
    }
2364

    
2365
    static void setPluginsDir(String s) {
2366
        andamiConfig.setPluginsDirectory(s);
2367
    }
2368

    
2369
    static MDIFrame getMDIFrame() {
2370
        return frame;
2371
    }
2372

    
2373
    private PluginsConfig loadPluginConfigs() {
2374
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
2375
        List<File> repositoriesFolders = installerManager.getLocalAddonRepositories("plugin");
2376
        for (File repositoryFolder : repositoriesFolders) {
2377
            logger.info("Loading plugins configuration from repository folder " + repositoryFolder.getAbsolutePath() + ".");
2378

    
2379
            if (!repositoryFolder.exists()) {
2380
                logger.warn("Plugins repository folder not found '" + repositoryFolder.getAbsolutePath() + "'.");
2381
                continue;
2382
            }
2383

    
2384
            File[] pluginsFolders = repositoryFolder.listFiles();
2385
            if (pluginsFolders.length == 0) {
2386
                logger.info("Plugins repository folder is empty '" + repositoryFolder.getAbsolutePath() + "'.");
2387
                continue;
2388
            }
2389

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

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

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

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

    
2425
                }
2426
            }
2427
        }
2428
        return pluginsConfig;
2429
    }
2430

    
2431
    private static Locale getLocale(String language, String country,
2432
            String variant) {
2433
        if (variant != null) {
2434
            return new Locale(language, country, variant);
2435
        } else if (country != null) {
2436
            return new Locale(language, country);
2437
        } else if (language != null) {
2438
            return new Locale(language);
2439
        } else {
2440
            return new Locale("es");
2441
        }
2442
    }
2443

    
2444
    private static void andamiConfigToXML(String file) throws IOException,
2445
            MarshalException, ValidationException {
2446
                // write on a temporary file in order to not destroy current file if
2447
        // there is some problem while marshaling
2448
        File tmpFile = new File(file + "-"
2449
                + DateTime.getCurrentDate().getTime());
2450
        File xml = new File(file);
2451
        File parent = xml.getParentFile();
2452
        parent.mkdirs();
2453

    
2454
        BufferedOutputStream os = new BufferedOutputStream(
2455
                new FileOutputStream(tmpFile));
2456
        OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2457
        andamiConfig.marshal(writer);
2458
        writer.close();
2459

    
2460
                // if marshaling process finished correctly, move the file to the
2461
        // correct one
2462
        xml.delete();
2463
        if (!tmpFile.renameTo(xml)) {
2464
            // if rename was not succesful, try copying it
2465
            FileChannel sourceChannel = new FileInputStream(tmpFile)
2466
                    .getChannel();
2467
            FileChannel destinationChannel = new FileOutputStream(xml)
2468
                    .getChannel();
2469
            sourceChannel.transferTo(0, sourceChannel.size(),
2470
                    destinationChannel);
2471
            sourceChannel.close();
2472
            destinationChannel.close();
2473
        }
2474
    }
2475

    
2476
    private static void andamiConfigFromXML(String file)
2477
            throws ConfigurationException {
2478
        File xml = new File(file);
2479

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

    
2512
    private static AndamiConfig getDefaultAndamiConfig() {
2513
        AndamiConfig andamiConfig = new AndamiConfig();
2514

    
2515
        Andami andami = new Andami();
2516
        andami.setUpdate(true);
2517
        andamiConfig.setAndami(andami);
2518
        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2519
        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2520
        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2521

    
2522
        if (System.getProperty("javawebstart.version") != null) // Es java web
2523
        // start)
2524
        {
2525
            andamiConfig
2526
                    .setPluginsDirectory(new File(appHomeDir, "extensiones")
2527
                            .getAbsolutePath());
2528
        } else {
2529
            andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2530
                    .getAbsolutePath());
2531
        }
2532

    
2533
        andamiConfig.setPlugin(new Plugin[0]);
2534
        return andamiConfig;
2535
    }
2536

    
2537
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
2538
        File xml = getPluginsPersistenceFile(true);
2539

    
2540
        if (xml.exists()) {
2541
            InputStreamReader reader = null;
2542

    
2543
            try {
2544
                reader = XMLEncodingUtils.getReader(xml);
2545
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2546
                return new XMLEntity(tag);
2547
            } catch (FileNotFoundException e) {
2548
                throw new ConfigurationException(e);
2549
            } catch (MarshalException e) {
2550

    
2551
                                // try to reopen with default encoding (for backward
2552
                // compatibility)
2553
                try {
2554
                    reader = new FileReader(xml);
2555
                    XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2556
                    return new XMLEntity(tag);
2557

    
2558
                } catch (MarshalException ex) {
2559
                    // try to close the stream, maybe it remains open
2560
                    if (reader != null) {
2561
                        try {
2562
                            reader.close();
2563
                        } catch (IOException e1) {
2564
                        }
2565
                    }
2566
                    // backup the old file
2567
                    String backupFile = getPluginsPersistenceFile(true)
2568
                            .getPath()
2569
                            + "-" + DateTime.getCurrentDate().getTime();
2570
                    NotificationManager
2571
                            .addError(
2572
                                    Messages
2573
                                    .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2574
                                    + backupFile,
2575
                                    new ConfigurationException(e));
2576
                    xml.renameTo(new File(backupFile));
2577
                    // create a new, empty configuration
2578
                    return new XMLEntity();
2579
                } catch (FileNotFoundException ex) {
2580
                    return new XMLEntity();
2581
                } catch (ValidationException ex) {
2582
                    throw new ConfigurationException(e);
2583
                }
2584
            } catch (ValidationException e) {
2585
                throw new ConfigurationException(e);
2586
            }
2587
        } else {
2588
            return new XMLEntity();
2589
        }
2590
    }
2591

    
2592
    private static File getPluginsPersistenceFile(boolean read) {
2593
        if (read) {
2594
            File pluginsPersistenceFile = new File(getAppHomeDir(),
2595
                    "plugins-persistence-2_0.xml");
2596
            if (pluginsPersistenceFile.exists()) {
2597
                return pluginsPersistenceFile;
2598
            }
2599
            pluginsPersistenceFile = new File(getAppHomeDir(),
2600
                    "plugins-persistence.xml");
2601
            if (pluginsPersistenceFile.exists()) {
2602
                return pluginsPersistenceFile;
2603
            }
2604
        }
2605
        return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2606

    
2607
    }
2608

    
2609
    private static void persistenceToXML(XMLEntity entity)
2610
            throws ConfigurationException {
2611
                // write on a temporary file in order to not destroy current file if
2612
        // there is some problem while marshaling
2613
        File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2614
                + "-" + DateTime.getCurrentDate().getTime());
2615

    
2616
        File xml = getPluginsPersistenceFile(false);
2617
        OutputStreamWriter writer = null;
2618

    
2619
        try {
2620
            writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2621
                    CASTORENCODING);
2622
            entity.getXmlTag().marshal(writer);
2623
            writer.close();
2624

    
2625
                        // if marshaling process finished correctly, move the file to the
2626
            // correct one
2627
            xml.delete();
2628
            if (!tmpFile.renameTo(xml)) {
2629
                // if rename was not succesful, try copying it
2630
                FileChannel sourceChannel = new FileInputStream(tmpFile)
2631
                        .getChannel();
2632
                FileChannel destinationChannel = new FileOutputStream(xml)
2633
                        .getChannel();
2634
                sourceChannel.transferTo(0, sourceChannel.size(),
2635
                        destinationChannel);
2636
                sourceChannel.close();
2637
                destinationChannel.close();
2638

    
2639
            }
2640
        } catch (FileNotFoundException e) {
2641
            throw new ConfigurationException(e);
2642
        } catch (MarshalException e) {
2643
            // try to close the stream, maybe it remains open
2644
            if (writer != null) {
2645
                try {
2646
                    writer.close();
2647
                } catch (IOException e1) {
2648
                }
2649
            }
2650
        } catch (ValidationException e) {
2651
            throw new ConfigurationException(e);
2652
        } catch (IOException e) {
2653
            throw new ConfigurationException(e);
2654
        }
2655
    }
2656

    
2657
    static MDIFrame getFrame() {
2658
        return frame;
2659
    }
2660

    
2661
    /**
2662
     * Gracefully closes the application. It shows dialogs to save data, finish
2663
     * processes, etc, then it terminates the extensions, removes temporal files
2664
     * and finally exits.
2665
     */
2666
    public synchronized static void closeApplication() {
2667
        TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2668
        terminationProcess.run();
2669
    }
2670

    
2671
    static HashMap getClassesExtensions() {
2672
        return classesExtensions;
2673
    }
2674

    
2675
    public static IExtension getExtensionByName(String extensionName) {
2676
        if( StringUtils.isEmpty(extensionName) ) {
2677
            return null;
2678
        }
2679
        for (Entry<Class<? extends IExtension>, ExtensionDecorator> entry : classesExtensions.entrySet()) {
2680
            Class<? extends IExtension> extensionClass = entry.getKey();
2681
            IExtension extension = entry.getValue();
2682
            if( extensionName.equals(extensionClass.getName()) ) {
2683
                while( extension instanceof ExtensionDecorator ) {
2684
                    extension = ((ExtensionDecorator)extension).getExtension();
2685
                }
2686
                return extension;
2687
            }
2688
        }
2689
        return null;
2690
    }
2691

    
2692
    private static Extensions[] getExtensions() {
2693
        List<Extensions> array = new ArrayList<Extensions>();
2694
        Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2695

    
2696
        while (iter.hasNext()) {
2697
            array.add(iter.next().getExtensions());
2698
        }
2699

    
2700
        return array.toArray(new Extensions[array.size()]);
2701
    }
2702

    
2703
    public static Iterator getExtensionIterator() {
2704
        return extensions.iterator();
2705
    }
2706

    
2707
    public static HashMap getPluginConfig() {
2708
        return pluginsConfig;
2709
    }
2710

    
2711
    public static Extension getExtension(String s) {
2712
        Extensions[] exts = getExtensions();
2713

    
2714
        for (int i = 0; i < exts.length; i++) {
2715
            for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2716
                if (exts[i].getExtension(j).getClassName().equals(s)) {
2717
                    return exts[i].getExtension(j);
2718
                }
2719
            }
2720
        }
2721

    
2722
        return null;
2723
    }
2724

    
2725
    public static AndamiConfig getAndamiConfig() {
2726
        return andamiConfig;
2727
    }
2728

    
2729
    private static class ExtensionComparator implements Comparator {
2730

    
2731
        public int compare(Object o1, Object o2) {
2732
            Extension e1 = (Extension) o1;
2733
            Extension e2 = (Extension) o2;
2734

    
2735
            if (!e1.hasPriority() && !e2.hasPriority()) {
2736
                return -1;
2737
            }
2738

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

    
2743
            if (e2.hasPriority() && !e1.hasPriority()) {
2744
                return Integer.MAX_VALUE;
2745
            }
2746

    
2747
            if (e1.getPriority() != e2.getPriority()) {
2748
                return e2.getPriority() - e1.getPriority();
2749
            } else {
2750
                return (e2.toString().compareTo(e1.toString()));
2751
            }
2752
        }
2753
    }
2754

    
2755
    private static class MenuComparator implements Comparator<SortableMenu> {
2756

    
2757
        private static ExtensionComparator extComp = new ExtensionComparator();
2758

    
2759
        public int compare(SortableMenu e1, SortableMenu e2) {
2760

    
2761
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2762
                if (e1.extension instanceof SkinExtensionType) {
2763
                    return 1;
2764
                } else if (e2.extension instanceof SkinExtensionType) {
2765
                    return -1;
2766
                } else {
2767
                    return extComp.compare(e1.extension, e2.extension);
2768
                }
2769
            }
2770

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

    
2775
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2776
                return Integer.MAX_VALUE;
2777
            }
2778

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

    
2789
        }
2790
    }
2791

    
2792
    private static class SortableMenu {
2793

    
2794
        public PluginClassLoader loader;
2795
        public Menu menu;
2796
        public SkinExtensionType extension;
2797

    
2798
        public SortableMenu(PluginClassLoader loader,
2799
                SkinExtensionType skinExt, Menu menu2) {
2800
            extension = skinExt;
2801
            menu = menu2;
2802
            this.loader = loader;
2803
        }
2804

    
2805
    }
2806

    
2807
    private static class SortableTool {
2808

    
2809
        public PluginClassLoader loader;
2810
        public ToolBar toolbar;
2811
        public ActionTool actiontool;
2812
        public SelectableTool selectabletool;
2813
        public SkinExtensionType extension;
2814

    
2815
        public SortableTool(PluginClassLoader loader,
2816
                SkinExtensionType skinExt, ToolBar toolbar2,
2817
                ActionTool actiontool2) {
2818
            extension = skinExt;
2819
            toolbar = toolbar2;
2820
            actiontool = actiontool2;
2821
            this.loader = loader;
2822
        }
2823

    
2824
        public SortableTool(PluginClassLoader loader,
2825
                SkinExtensionType skinExt, ToolBar toolbar2,
2826
                SelectableTool selectabletool2) {
2827
            extension = skinExt;
2828
            toolbar = toolbar2;
2829
            selectabletool = selectabletool2;
2830
            this.loader = loader;
2831
        }
2832

    
2833
        public long getPosition() {
2834
            if( this.actiontool!=null ) {
2835
                return this.actiontool.getPosition();
2836
            }
2837
            if( this.selectabletool!=null ) {
2838
                return this.selectabletool.getPosition();
2839
            }
2840
            return 0;
2841
        }
2842
    }
2843

    
2844
    private static class ToolBarComparator implements Comparator<SortableTool> {
2845

    
2846
        private static ExtensionComparator extComp = new ExtensionComparator();
2847

    
2848
        public int compare(SortableTool e1, SortableTool e2) {
2849

    
2850
                        // if the toolbars have the same name, they are considered to be
2851
            // the same toolbar, so we don't need to do further comparing
2852
            if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2853
                return 0;
2854
            }
2855

    
2856
            if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2857
                if (e1.extension instanceof SkinExtensionType) {
2858
                    return 1;
2859
                } else if (e2.extension instanceof SkinExtensionType) {
2860
                    return -1;
2861
                } else {
2862
                    return extComp.compare(e1.extension, e2.extension);
2863
                }
2864
            }
2865

    
2866
            if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2867
                return Integer.MIN_VALUE;
2868
            }
2869

    
2870
            if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2871
                return Integer.MAX_VALUE;
2872
            }
2873
            if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2874
                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2875
            }
2876

    
2877
            if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2878
                    && e1.toolbar.getSelectableTool().equals(
2879
                            e2.toolbar.getSelectableTool())) {
2880
                return 0;
2881
            }
2882
            return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2883
        }
2884
    }
2885

    
2886
    /**
2887
     * <p>
2888
     * This class is used to compare tools (selectabletool and actiontool),
2889
     * using the "position" attribute.
2890
     * </p>
2891
     * <p>
2892
     * The ordering criteria are:
2893
     * </p>
2894
     * <ul>
2895
     * <li>If the tools are placed in different toolbars, they use the toolbars'
2896
     * order. (using the ToolBarComparator).</li>
2897
     * <li></li>
2898
     * <li>If any of the tools has not 'position' attribute, the tool which
2899
     * <strong>has</strong> the attribute will be placed first.</li>
2900
     * <li>If both tools have the same position (or they don't have a 'position'
2901
     * attribute), the priority of the extensions where the tool is
2902
     * defined.</li>
2903
     * </ul>
2904
     *
2905
     * @author cesar
2906
     * @version $Revision: 40305 $
2907
     */
2908
    private static class ToolComparator implements Comparator<SortableTool> {
2909

    
2910
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2911

    
2912
        public int compare(SortableTool e1, SortableTool e2) {
2913
            // compare the toolbars which contain the tools
2914
            long result = toolBarComp.compare(e1, e2);
2915
            if (result != 0) { // if the toolbars are different, use their order
2916
                return result > 0 ? 1 : -1;
2917
            }
2918
            // otherwise, compare the tools
2919
            long e1Position = -1, e2Position = -1;
2920

    
2921
            if (e1.actiontool != null) {
2922
                if (e1.actiontool.hasPosition()) {
2923
                    e1Position = e1.actiontool.getPosition();
2924
                }
2925
            } else if (e1.selectabletool != null) {
2926
                if (e1.selectabletool.hasPosition()) {
2927
                    e1Position = e1.selectabletool.getPosition();
2928
                }
2929
            }
2930

    
2931
            if (e2.actiontool != null) {
2932
                if (e2.actiontool.hasPosition()) {
2933
                    e2Position = e2.actiontool.getPosition();
2934
                }
2935
            } else if (e2.selectabletool != null) {
2936
                if (e2.selectabletool.hasPosition()) {
2937
                    e2Position = e2.selectabletool.getPosition();
2938
                }
2939
            }
2940

    
2941
            if ((e1Position == -1) && (e2Position != -1)) {
2942
                return 1;
2943
            }
2944
            if ((e1Position != -1) && (e2Position == -1)) {
2945
                return -1;
2946
            }
2947
            if ((e1Position != -1) && (e2Position != -1)) {
2948
                result = e1Position - e2Position;
2949
                                // we don't return 0 unless both objects are the same, otherwise
2950
                // the objects get overwritten in the treemap
2951
                if (result != 0) {
2952
                    return result > 0 ? 1 : -1;
2953
                }
2954
            }
2955
            return e1.toString().compareTo(e2.toString());
2956
        }
2957
    }
2958

    
2959
    public static String getDefaultLookAndFeel() {
2960
        String osName = (String) System.getProperty("os.name");
2961

    
2962
        if ((osName.length() > 4)
2963
                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2964
            return nonWinDefaultLookAndFeel;
2965
        }
2966
        if (osName.toLowerCase().startsWith("mac os x")) {
2967
            return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2968
        }
2969

    
2970
        return UIManager.getSystemLookAndFeelClassName();
2971
    }
2972

    
2973
    /**
2974
     * Gets the ISO 839 two-characters-long language code matching the provided
2975
     * language code (which may be an ISO 839-2/T three-characters-long code or
2976
     * an ISO 839-1 two-characters-long code).
2977
     *
2978
     * If the provided parameter is already two characters long, it returns the
2979
     * parameter without any modification.
2980
     *
2981
     * @param langCode A language code representing either an ISO 839-2/T
2982
     * language code or an ISO 839-1 code.
2983
     * @return A two-characters-long code specifying an ISO 839 language code.
2984
     */
2985
    private static String normalizeLanguageCode(String langCode) {
2986
        final String fileName = "iso_639.tab";
2987
        if (langCode.length() == 2) {
2988
            return langCode;
2989
        } else if (langCode.length() == 3) {
2990
            if (langCode.equals("va") || langCode.equals("val")) { // special
2991
                // case
2992
                // for
2993
                // Valencian
2994
                return "ca";
2995
            }
2996
            URL isoCodes = Launcher.class.getClassLoader()
2997
                    .getResource(fileName);
2998
            if (isoCodes != null) {
2999
                try {
3000
                    BufferedReader reader = new BufferedReader(
3001
                            new InputStreamReader(isoCodes.openStream(),
3002
                                    "ISO-8859-1"));
3003
                    String line;
3004

    
3005
                    while ((line = reader.readLine()) != null) {
3006
                        String[] language = line.split("\t");
3007
                        if (language[0].equals(langCode)) {
3008
                                                        // the three
3009
                            // characters code
3010
                            return language[2]; // third column i the two
3011
                            // characters code
3012
                        }
3013
                    }
3014
                } catch (IOException ex) {
3015
                    logger.error(Messages
3016
                            .getString("Error_reading_isocodes_file"), ex);
3017
                    return "es";
3018
                }
3019
            } else {
3020
                logger.error(Messages.getString("Error_reading_isocodes_file"));
3021
                return "es";
3022
            }
3023
        }
3024
        return "es";
3025
    }
3026

    
3027
    /**
3028
     * Configures the locales (languages and local resources) to be used by the
3029
     * application.
3030
     *
3031
     * First it tries to get the locale from the command line parameters, then
3032
     * the andami-config file is checked.
3033
     *
3034
     * The locale name is normalized to get a two characters language code as
3035
     * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
3036
     * also accepted from the command line or the configuration file).
3037
     *
3038
     * Finally, the gvsig-i18n library and the default locales for Java and
3039
     * Swing are configured.
3040
     *
3041
     */
3042
    private static void configureLocales() {
3043
        // Configurar el locale
3044
        String localeStr = null;
3045

    
3046
        if( getArguments().contains("language") ) {
3047
            localeStr = getArguments().get("language");
3048
        } else {
3049
            localeStr = andamiConfig.getLocaleLanguage();
3050
        }
3051
        localeStr = normalizeLanguageCode(localeStr);
3052
        locale = getLocale(
3053
                localeStr,
3054
                andamiConfig.getLocaleCountry(),
3055
                andamiConfig.getLocaleVariant()
3056
        );
3057
        org.gvsig.i18n.Messages.setCurrentLocale(locale);
3058
        JComponent.setDefaultLocale(locale);
3059
        /*
3060
         org.gvsig.i18n.Messages.addLocale(locale);
3061
         // add english and spanish as fallback languages
3062
         if ( localeStr.equals("es") || localeStr.equals("ca")
3063
         || localeStr.equals("gl") || localeStr.equals("eu")
3064
         || localeStr.equals("va") ) {
3065
         // prefer Spanish for languages spoken in Spain
3066
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3067
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3068
         } else {
3069
         // prefer English for the rest
3070
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3071
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3072
         }
3073
         */
3074
        // Create classloader for the i18n resources in the
3075
        // andami and user i18n folder. Those values will have
3076
        // precedence over any other values added afterwards
3077
        File appI18nFolder = new File(getApplicationFolder(), "i18n");
3078
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
3079
        if (!userI18nFolder.exists()) {
3080
            try {
3081
                FileUtils.forceMkdir(userI18nFolder);
3082
            } catch (IOException e) {
3083
                logger.info("Can't create i18n folder in gvSIG home (" + userI18nFolder + ").", e);
3084
            }
3085
        }
3086
//        logger.info("Loading i18n resources from the application and user "
3087
//                + "folders: {}, {}", appI18nFolder, userI18nFolder);
3088

    
3089
        URL[] i18nURLs = getURLsFromI18nFolders(userI18nFolder, appI18nFolder);
3090
        ClassLoader i18nClassLoader = URLClassLoader.newInstance(i18nURLs, null);
3091
        logger.info("loading resources from classloader " + i18nClassLoader.toString() + ".");
3092
        org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
3093
                "Andami Launcher");
3094

    
3095
        // Finally load the andami own i18n resources
3096
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
3097
                "Andami Launcher");
3098
    }
3099

    
3100
    private static URL[] getURLsFromI18nFolders(File userFolder, File appFolder) {
3101
        List<URL> urls = new ArrayList<URL>();
3102
        File[] files = new File[]{userFolder, appFolder};
3103
        for (int n1 = 0; n1 < files.length; n1++) {
3104
            File folder = files[n1];
3105
//                try {
3106
//                    urls.add(folder.toURI().toURL());
3107
//                } catch (MalformedURLException ex) {
3108
//                    logger.warn("Can't convert file to url (file="+userFolder.getAbsolutePath()+").", ex);
3109
//                    return null;
3110
//                }
3111
            File[] subFiles = folder.listFiles();
3112
            for (int n2 = 0; n2 < subFiles.length; n2++) {
3113
                File subFolder = subFiles[n2];
3114
                if ("andami".equalsIgnoreCase(subFolder.getName())) {
3115
                    // Skip andami and add the last.
3116
                    continue;
3117
                }
3118
                if (subFolder.isDirectory()) {
3119
                    try {
3120
                        urls.add(subFolder.toURI().toURL());
3121
                    } catch (MalformedURLException ex) {
3122
                        logger.warn("Can't convert file to url (file=" + subFolder.getAbsolutePath() + ").", ex);
3123
                        return null;
3124
                    }
3125
                }
3126
            }
3127
        }
3128
        File folder = new File(appFolder, "andami");
3129
        try {
3130
            urls.add(folder.toURI().toURL());
3131
        } catch (MalformedURLException ex) {
3132
            logger.warn("Can't convert file to url (file=" + folder.getAbsolutePath() + ").", ex);
3133
            return null;
3134
        }
3135
        return urls.toArray(new URL[urls.size()]);
3136
    }
3137

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

    
3150
    public static File getApplicationHomeFolder() {
3151
        return new File(getAppHomeDir());
3152
    }
3153

    
3154
    /**
3155
     * Sets Home Directory location of the application. May be set from outside
3156
     * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3157
     * the name of the application
3158
     *
3159
     * @param appHomeDir
3160
     */
3161
    public static void setAppHomeDir(String appHomeDir) {
3162
        Launcher.appHomeDir = appHomeDir;
3163
    }
3164

    
3165
    /**
3166
     * Initialize the extesion that have to take the control of the state of
3167
     * action controls of the UI of all extensions. <br>
3168
     * <br>
3169
     * For use this option you have to add an argument to the command line like
3170
     * this: <br>
3171
     * <br>
3172
     * -exclusiveUI={pathToExtensionClass} <br>
3173
     *
3174
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3175
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3176
     */
3177
    private static void initializeExclusiveUIExtension() {
3178
        String name = PluginServices.getArgumentByName("exclusiveUI");
3179
        if (name == null) {
3180
            return;
3181
        }
3182

    
3183
        Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3184
                .iterator();
3185
        int charIndex;
3186
        Class<? extends IExtension> key;
3187
        while (iter.hasNext()) {
3188
            key = iter.next();
3189
            charIndex = key.getName().indexOf(name);
3190
            // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3191
            if (charIndex == 0) {
3192
                IExtension ext = classesExtensions.get(key);
3193
                if (ext instanceof ExtensionDecorator) {
3194
                    ext = ((ExtensionDecorator) ext).getExtension();
3195
                }
3196
                if (ext instanceof ExclusiveUIExtension) {
3197
                    PluginServices
3198
                            .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3199
                }
3200
                break;
3201
            }
3202
        }
3203

    
3204
        logger
3205
                .error(Messages
3206
                        .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3207
                        + " '" + name + "'");
3208
    }
3209

    
3210
    public static void initIconThemes() {
3211
        PluginsManager pluginsManager = PluginsLocator.getManager();
3212
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3213

    
3214
        File f = new File(pluginsManager.getApplicationHomeFolder(), "icon-theme");
3215
        if (!f.exists()) {
3216
            try {
3217
                f.mkdir();
3218
            } catch (Exception ex) {
3219
                // Do nothing
3220
            }
3221
        }
3222
        iconManager.getRepository().add(f, "_User");
3223

    
3224
        f = new File(pluginsManager.getApplicationFolder(), "icon-theme");
3225
        if (!f.exists()) {
3226
            try {
3227
                f.mkdir();
3228
            } catch (Exception ex) {
3229
                // Do nothing
3230
            }
3231
        }
3232
        iconManager.getRepository().add(f, "_Global");
3233

    
3234
        Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3235
        String defaultThemeID = prefs.get("default-theme", null);
3236
        if (defaultThemeID != null) {
3237
            IconTheme iconTheme = iconManager.get(defaultThemeID);
3238
            if (iconTheme != null) {
3239
                iconManager.setCurrent(iconTheme);
3240
            }
3241
        }
3242
    }
3243

    
3244
    public static void manageUnsavedData(String prompt) throws Exception {
3245
        final UnsavedDataPanel panel = new UnsavedDataPanel(prompt);
3246
        final List<IUnsavedData> unsavedData = PluginsLocator.getManager().getUnsavedData();
3247
        panel.setUnsavedData(unsavedData);
3248

    
3249
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3250

    
3251
            public void cancel(UnsavedDataPanel panel) {
3252
                panel.setVisible(false);
3253
            }
3254

    
3255
            public void discard(UnsavedDataPanel panel) {
3256
                panel.setVisible(false);
3257
            }
3258

    
3259
            public void accept(UnsavedDataPanel panel) {
3260
                panel.setVisible(false);
3261

    
3262
                try {
3263
                    PluginsLocator.getManager().saveUnsavedData(panel.getSelectedsUnsavedDataList());
3264
                } catch (UnsavedDataException e) {
3265
                    StringBuilder msg = new StringBuilder();
3266
                    msg.append(PluginServices.getText(this, "The_following_resources_could_not_be_saved"));
3267
                    msg.append("\n");
3268
                    for (Iterator iterator = e.getUnsavedData().iterator(); iterator.hasNext();) {
3269
                        IUnsavedData unsavedData = (IUnsavedData) iterator.next();
3270
                        msg.append(unsavedData.getResourceName());
3271
                        msg.append(" -- ");
3272
                        msg.append(unsavedData.getDescription());
3273
                        msg.append("\n");
3274
                    }
3275
                    JOptionPane.showMessageDialog(panel, msg, PluginServices.getText(this, "Resources_was_not_saved"), JOptionPane.ERROR_MESSAGE);
3276
                }
3277
            }
3278
        });
3279

    
3280
        //TODO: mostrar panel WindowManager
3281
        ToolsSwingLocator.getWindowManager().showWindow(
3282
                panel,
3283
                PluginServices.getText(panel, "Resource_was_not_saved"),
3284
                MODE.DIALOG);
3285

    
3286
    }
3287

    
3288
    /**
3289
     * Manages Andami termination process
3290
     *
3291
     * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3292
     */
3293
    public class TerminationProcess {
3294

    
3295
        private boolean proceed = false;
3296
        private UnsavedDataPanel panel = null;
3297

    
3298
        public void run() {
3299
            try {
3300
                int exit = manageUnsavedData();
3301
                if ((exit == JOptionPane.NO_OPTION)
3302
                        || (exit == JOptionPane.CLOSED_OPTION)) {
3303
                    // the user doesn't want to exit
3304
                    return;
3305
                }
3306
                closeAndami();
3307
            } catch (Exception e) {
3308
                logger.warn("It is not possible to close the application", e);
3309
                                // It is not possible to close the application.
3310
                // this exception has been registered before
3311
            }
3312
        }
3313

    
3314
        /**
3315
         * Finishes the application without asking user if want or not to save
3316
         * unsaved data.
3317
         */
3318
        public void closeAndami() {
3319
            PluginsManager pluginsManager = PluginsLocator.getManager();
3320
            pluginsManager.executeShutdownTasks();
3321

    
3322
            try {
3323
                saveAndamiConfig();
3324
            } catch (Exception ex) {
3325
                logger.error(
3326
                        "There was an error exiting application, can't save andami-config.xml",
3327
                        ex
3328
                );
3329
            }
3330

    
3331
            try {
3332
                // Persistencia de los plugins
3333
                savePluginPersistence();
3334
                savePluginsProperties();
3335
            } catch (Exception ex) {
3336
                logger.error(
3337
                        "There was an error exiting application, can't save plugins properties",
3338
                        ex
3339
                );
3340
            }
3341

    
3342
            // Finalize all the extensions
3343
            finalizeExtensions();
3344

    
3345
            try {
3346
                // Clean any temp data created
3347
                Utilities.cleanUpTempFiles();
3348
            } catch (Exception ex) {
3349
                logger.error(
3350
                        "There was an error exiting application, can't remove temporary files",
3351
                        ex
3352
                );
3353
            }
3354

    
3355
            logger.info("Quiting application.");
3356

    
3357
            // Para la depuraci?n de memory leaks
3358
            System.gc();
3359

    
3360
            System.exit(0);
3361
        }
3362

    
3363
        public void saveAndamiConfig() {
3364
            // Configuraci?n de Andami
3365
            try {
3366
                andamiConfigToXML(andamiConfigPath);
3367
            } catch (MarshalException e) {
3368
                logger
3369
                        .error(
3370
                                Messages
3371
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3372
                                e);
3373
            } catch (ValidationException e) {
3374
                logger
3375
                        .error(
3376
                                Messages
3377
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3378
                                e);
3379
            } catch (IOException e) {
3380
                logger
3381
                        .error(
3382
                                Messages
3383
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3384
                                e);
3385
            }
3386
        }
3387

    
3388
        private void savePluginsProperties() {
3389
            PluginsManager manager = PluginsLocator.getManager();
3390
            List<PluginServices> plugins = manager.getPlugins();
3391
            for (PluginServices plugin : plugins) {
3392
                if (plugin != null) {
3393
                    plugin.savePluginProperties();
3394
                }
3395
            }
3396
        }
3397

    
3398
        /**
3399
         * Exectutes the terminate method for all the extensions, in the reverse
3400
         * order they were initialized
3401
         *
3402
         */
3403
        private void finalizeExtensions() {
3404
            for (int i = extensions.size() - 1; i >= 0; i--) {
3405
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3406
                        .get(i);
3407
                String extensionName = "(unknow)";
3408
                try {
3409
                    extensionName = extensionInstance.getClass().getName();
3410
                    extensionInstance.terminate();
3411
                } catch (Exception ex) {
3412
                    logger.error(MessageFormat.format(
3413
                            "There was an error extension ending {0}",
3414
                            extensionName), ex);
3415
                }
3416
            }
3417
        }
3418

    
3419
        private IUnsavedData[] getUnsavedData() throws Exception {
3420
            List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3421
            IExtension exclusiveExtension = PluginServices
3422
                    .getExclusiveUIExtension();
3423

    
3424
            for (int i = extensions.size() - 1; i >= 0; i--) {
3425
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3426
                        .get(i);
3427
                IExtensionStatus status = null;
3428
                if (exclusiveExtension != null) {
3429
                    status = exclusiveExtension.getStatus(extensionInstance);
3430
                } else {
3431
                    status = extensionInstance.getStatus();
3432
                }
3433
                if (status != null) {
3434
                    try {
3435
                        if (status.hasUnsavedData()) {
3436
                            IUnsavedData[] array = status.getUnsavedData();
3437
                            for (int element = 0; element < array.length; element++) {
3438
                                unsavedDataList.add(array[element]);
3439
                            }
3440
                        }
3441
                    } catch (Exception e) {
3442
                        logger.info("Error calling the hasUnsavedData method",
3443
                                new Exception());
3444
                        int option = JOptionPane
3445
                                .showConfirmDialog(
3446
                                        frame,
3447
                                        Messages
3448
                                        .getString("error_getting_unsaved_data"),
3449
                                        Messages.getString("MDIFrame.salir"),
3450
                                        JOptionPane.YES_NO_OPTION);
3451
                        if (option == JOptionPane.NO_OPTION) {
3452
                            throw e;
3453
                        }
3454
                    }
3455
                }
3456
            }
3457
            return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3458
                    .size()]);
3459
        }
3460

    
3461
        public UnsavedDataPanel getUnsavedDataPanel() {
3462
            if (panel == null) {
3463
                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3464
            }
3465
            return panel;
3466
        }
3467

    
3468
        /**
3469
         * Checks if the extensions have some unsaved data, and shows a dialog
3470
         * to allow saving it. This dialog also allows to don't exit Andami.
3471
         *
3472
         * @return true if the user confirmed he wishes to exit, false otherwise
3473
         * @throws Exception
3474
         */
3475
        public int manageUnsavedData() throws Exception {
3476
            IUnsavedData[] unsavedData = getUnsavedData();
3477

    
3478
            // there was no unsaved data
3479
            if (unsavedData.length == 0) {
3480
                int option = JOptionPane
3481
                        .showConfirmDialog(frame, Messages
3482
                                .getString("MDIFrame.quiere_salir"), Messages
3483
                                .getString("MDIFrame.salir"),
3484
                                JOptionPane.YES_NO_OPTION);
3485
                return option;
3486
            }
3487

    
3488
            UnsavedDataPanel panel = getUnsavedDataPanel();
3489
            panel.setUnsavedDataArray(unsavedData);
3490

    
3491
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3492

    
3493
                public void cancel(UnsavedDataPanel panel) {
3494
                    proceed(false);
3495
                    PluginServices.getMDIManager().closeWindow(panel);
3496

    
3497
                }
3498

    
3499
                public void discard(UnsavedDataPanel panel) {
3500
                    proceed(true);
3501
                    PluginServices.getMDIManager().closeWindow(panel);
3502

    
3503
                }
3504

    
3505
                public void accept(UnsavedDataPanel panel) {
3506
                    IUnsavedData[] unsavedDataArray = panel
3507
                            .getSelectedsUnsavedData();
3508
                    boolean saved;
3509
                    for (int i = 0; i < unsavedDataArray.length; i++) {
3510
                        try {
3511
                            saved = unsavedDataArray[i].saveData();
3512
                        } catch (Exception ex) {
3513
                            PluginServices.getLogger().error(
3514
                                    "Error saving"
3515
                                    + unsavedDataArray[i]
3516
                                    .getResourceName(), ex);
3517
                            saved = false;
3518
                        }
3519
                        if (!saved) {
3520
                            JOptionPane
3521
                                    .showMessageDialog(
3522
                                            panel,
3523
                                            PluginServices
3524
                                            .getText(this,
3525
                                                    "The_following_resource_could_not_be_saved_")
3526
                                            + "\n"
3527
                                            + unsavedDataArray[i]
3528
                                            .getResourceName()
3529
                                            + " -- "
3530
                                            + unsavedDataArray[i]
3531
                                            .getDescription(),
3532
                                            PluginServices.getText(this,
3533
                                                    "unsaved_resources"),
3534
                                            JOptionPane.ERROR_MESSAGE);
3535

    
3536
                            try {
3537
                                unsavedDataArray = getUnsavedData();
3538
                            } catch (Exception e) {
3539
                                // This exception has been registered before
3540
                            }
3541
                            panel.setUnsavedDataArray(unsavedDataArray);
3542
                            return;
3543
                        }
3544
                    }
3545
                    proceed(true);
3546
                    PluginServices.getMDIManager().closeWindow(panel);
3547
                }
3548
            });
3549

    
3550
            PluginServices.getMDIManager().addWindow(panel);
3551
            if (proceed) {
3552
                return JOptionPane.YES_OPTION;
3553
            } else {
3554
                return JOptionPane.NO_OPTION;
3555
            }
3556
        }
3557

    
3558
        private void proceed(boolean proceed) {
3559
            this.proceed = proceed;
3560
        }
3561

    
3562
    }
3563

    
3564
    public static TerminationProcess getTerminationProcess() {
3565
        return (new Launcher()).new TerminationProcess();
3566
    }
3567

    
3568
    private PackageInfo getPackageInfo(String pluginsFolder) {
3569
        try {
3570
            PluginsManager pm = PluginsLocator.getManager();
3571
            return pm.getPackageInfo();
3572
        } catch (Exception e) {
3573
            logger.info("Can't locate PackageInfo from plugin org.gvsig.app", e);
3574
            return null;
3575
        }
3576
    }
3577

    
3578
    /**
3579
     * Launch the gvSIG package installer.
3580
     *
3581
     * @throws Exception if there is any error
3582
     */
3583
    private void doInstall(String[] args) throws Exception {
3584
        String installURL = null;
3585
        String installURLFile = null;
3586
        String gvSIGVersion = null;
3587
        String[] myArgs = new String[3];
3588
        PackageInfo packageInfo = null;
3589

    
3590
        Options options = new Options();
3591
        options.addOption("i", "install", false, "install");
3592
        options.addOption("u", "installURL", true, "installURL");
3593
        options.addOption("f", "installURLFile", true, "installURLFile");
3594
        options.addOption("v", "installVersion", true, "installVersion");
3595
        options.addOption("A", "applicationName", true, "application name, default is gvSIG");
3596
        options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3597
        options.addOption("l", "language", true, "language");
3598

    
3599
        // This options are managed by the gvSIG.sh but need to be declared here to avoid
3600
        // errors.
3601
        options.addOption(null, "debug", false, "Activate the JVM remote debug");
3602
        options.addOption(null, "pause", false, "Pause when activate JVM debug");
3603

    
3604
        /*
3605
         * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3606
         *
3607
         * --install
3608
         * --applicationName=gvSIG
3609
         * --language=es
3610
         * --pluginsFolder=gvSIG/extensiones
3611
         *
3612
         * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3613
         * --installVersion=2.0.0
3614
         * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3615
         * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3616
         *
3617
         */
3618
        CommandLineParser parser = new PosixParser();
3619
        CommandLine line = null;
3620
        try {
3621
            line = parser.parse(options, args);
3622
            boolean hasAllMandatoryOptions = true;
3623
            if (!line.hasOption("install")) {
3624
                hasAllMandatoryOptions = false;
3625
            }
3626

    
3627
            if (line.hasOption("installVersion")) {
3628
                gvSIGVersion = line.getOptionValue("installVersion");
3629
            }
3630
            if (line.hasOption("applicationName")) {
3631
                myArgs[0] = line.getOptionValue("applicationName");
3632
            } else {
3633
                myArgs[0] = "gvSIG";
3634
            }
3635
            if (line.hasOption("pluginsFolder")) {
3636
                myArgs[1] = line.getOptionValue("pluginsFolder");
3637
            } else {
3638
                myArgs[1] = "gvSIG/extensiones";
3639
            }
3640
            if (line.hasOption("language")) {
3641
                myArgs[2] = "language=" + line.getOptionValue("language");
3642
            } else {
3643
                // prevent null
3644
                myArgs[2] = Locale.getDefault().toString();
3645
            }
3646

    
3647
            if (line.hasOption("installURL")) {
3648
                installURL = line.getOptionValue("installURL");
3649
            } else {
3650
                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3651
            }
3652

    
3653
            if (line.hasOption("installURLFile")) {
3654
                installURLFile = line.getOptionValue("installURLFile");
3655
            } else {
3656
                installURLFile = "gvsig-installer-urls.config";
3657
            }
3658

    
3659
            if (!hasAllMandatoryOptions) {
3660
                System.err.println(Messages.get("usage") + ": Launcher "
3661
                        + "--install "
3662
                        + "[--applicationName=appName] "
3663
                        + "[--pluginsFolder=plugins-directory] "
3664
                        + "[--installURLFile=File] "
3665
                        + "[--installURL=URL] "
3666
                        + "[--language=locale]"
3667
                );
3668
                return;
3669
            }
3670
        } catch (ParseException exp) {
3671
            System.err.println("Unexpected exception:" + exp.getMessage());
3672
            System.exit(-1);
3673
        }
3674

    
3675
        initializeApp(myArgs, "installer");
3676

    
3677
        new DefaultLibrariesInitializer().fullInitialize(true);
3678

    
3679
        initializeInstallerManager();
3680

    
3681
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
3682

    
3683
        try {
3684
            logger.info("Loading plugins configurations");
3685
            this.loadPluginConfigs();
3686
        } catch (Throwable ex) {
3687
            logger.warn("Can't load plugins configurations", ex);
3688
        }
3689

    
3690
        try {
3691
            logger.info("Loading plugins");
3692
            this.loadPluginServices();
3693
        } catch (Throwable ex) {
3694
            logger.warn("Can't load plugins", ex);
3695
        }
3696

    
3697
        AndamiConfig config = getAndamiConfig();
3698

    
3699
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3700

    
3701
        initializeLibraries();
3702

    
3703
        packageInfo = getPackageInfo(myArgs[1]);
3704

    
3705
        // set the gvSIG version to the install manager, to compose the download URL
3706
        if (packageInfo != null) {
3707
            installerManager.setVersion(packageInfo.getVersion());
3708
        } else {
3709
            installerManager.setVersion(gvSIGVersion);
3710
        }
3711
        if (!installURL.contains(";")
3712
                && !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION)
3713
                && !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION)) {
3714
            if (packageInfo != null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA)
3715
                    || packageInfo.getState().startsWith(InstallerManager.STATE.RC)
3716
                    || packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL))) {
3717
                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";
3718
            }
3719
        }
3720
        // Configure default index download URL
3721
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3722

    
3723
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3724

    
3725
        // Launch installer
3726
        PluginsManager manager = PluginsLocator.getManager();
3727

    
3728
        InstallWizardPanel installPackageWizard = SwingInstallerLocator
3729
                .getSwingInstallerManager().createInstallPackageWizard(
3730
                        manager.getApplicationFolder(),
3731
                        manager.getInstallFolder());
3732
        installPackageWizard.setWizardActionListener(new InstallerWizardActionListener() {
3733
            @Override
3734
            public void finish(InstallerWizardPanel installerWizard) {
3735
                logger.info("Finish installation.");
3736
                System.exit(0);
3737
            }
3738

    
3739
            @Override
3740
            public void cancel(InstallerWizardPanel installerWizard) {
3741
                logger.info("Cancel installation.");
3742
                System.exit(0);
3743
            }
3744
        });
3745

    
3746
        // the wizard will show the Typical or Advanced mode option.
3747
        installPackageWizard.setSkipTypicalOrAdvancedWizardPage(false);
3748
        // default packages will be selected.
3749
        installPackageWizard.setSelectDefaultPackages(true);
3750

    
3751
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3752
        frame.addWindowListener(new WindowAdapter() {
3753
            @Override
3754
            public void windowClosing(WindowEvent we) {
3755
                logger.info("Closing installation.");
3756
                System.exit(0);
3757
            }
3758

    
3759
            @Override
3760
            public void windowClosed(WindowEvent we) {
3761
                logger.info("Close installation.");
3762
                System.exit(0);
3763
            }
3764
        });
3765
        frame.getContentPane().add(installPackageWizard.asJComponent(), BorderLayout.CENTER);
3766
        URL iconURL = getClass().getResource("/images/main/install-icon.png");
3767
        if( iconURL!=null ) {
3768
            ImageIcon icon = new ImageIcon(iconURL);
3769
            frame.setIconImage(icon.getImage());
3770
        }
3771
        frame.pack();
3772
        frame.setLocationRelativeTo(null);
3773

    
3774
        frame.setVisible(true);
3775
    }
3776

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

    
3781
    private static final int INFO_OS_NAME = 0;
3782
    private static final int INFO_OS_ARCH = 1;
3783
    private static final int INFO_OS_VERSION = 2;
3784
    private static final int INFO_OS_ADITIONAL = 3;
3785
    private static final int INFO_JRE_VENDOR = 4;
3786
    private static final int INFO_JRE_VERSION = 5;
3787
    private static final int INFO_JRE_HOME = 6;
3788
    private static final int INFO_PROXY_HOST = 7;
3789
    private static final int INFO_PROXY_PORT = 8;
3790
    private static final int INFO_PROXY_USER = 9;
3791
    private static final int INFO_PROXY_PASSWORD = 10;
3792
    private static final int INFO_APP_LOCALE = 11;
3793
    private static final int INFO_APP_FOLDER = 12;
3794
    private static final int INFO_APP_HOME = 13;
3795
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3796
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3797
    private static final int INFO_APP_THEME = 16;
3798
    private static final int INFO_APP_SKIN = 17;
3799
    private static final int INFO_PACKAGES = 18;
3800
    private static final int INFO_TEMP_FOLDER = 19;
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
                + "    temp forlder            : {" + INFO_TEMP_FOLDER + "}\n"
3827
                + "Installed packages\n"
3828
                + "{" + INFO_PACKAGES + "}";
3829

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

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

    
3835
        Properties props = System.getProperties();
3836

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

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

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

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

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

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

    
3886
        try {
3887
            if (pkgs == null) {
3888
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3889
                pkgs = installmgr.getInstalledPackages();
3890
            }
3891
            StringWriter writer = new StringWriter();
3892
            for (PackageInfo pkg : pkgs) {
3893
                writer.write("    ");
3894
                writer.write(pkg.toStringCompact());
3895
                writer.write("\n");
3896
            }
3897
            values[INFO_PACKAGES] = writer.toString();
3898

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

    
3903
        String s = MessageFormat.format(template, (Object[])values);
3904
        return s;
3905
    }
3906

    
3907
    private void logger_info(String msg) {
3908
        String info[] = msg.split("\n");
3909
        for (String info1 : info) {
3910
            logger.info(info1);
3911
        }
3912
    }
3913

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

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

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

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

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

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

    
3997
    private class DisablePluginsConflictingDialog extends JDialog {
3998

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

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

    
4007
        private class Item {
4008

    
4009
            private String code;
4010
            private PackageInfo pkg;
4011

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

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

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

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

    
4036
            this.packages = packages;
4037

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

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

    
4053
            doTranslations();
4054

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

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

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

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

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

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

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

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

    
4121
    private void initializeIdentityManagement(File pluginsFolder) {
4122
        File identityManagementConfigFile = null;
4123
        PluginServices plugin = null;
4124
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
4125
        while (it.hasNext()) {
4126
            Entry<String, PluginConfig> entry = it.next();
4127
            File pluginFolder = entry.getValue().getPluginFolder();
4128
            File f = new File(pluginFolder, "identity-management.ini");
4129
            if (f.exists()) {
4130
                if (identityManagementConfigFile != null) {
4131
                    logger.warn("Too many identity-managemnt plugins. Disable all.");
4132
                } else {
4133
                    identityManagementConfigFile = f;
4134
                    plugin = PluginServices.getPluginServices(entry.getKey());
4135
                }
4136
            }
4137
        }
4138
        if(plugin != null){
4139
                new DefaultLibrariesInitializer(plugin.getClassLoader()).fullInitialize(true);
4140
        }
4141

    
4142
        if (identityManagementConfigFile == null || plugin == null) {
4143
            return;
4144
        }
4145
        if (!identityManagementConfigFile.canRead()) {
4146
            return;
4147
        }
4148
        PropertiesConfiguration identityManagementConfig = null;
4149
        try {
4150
            identityManagementConfig = new PropertiesConfiguration(identityManagementConfigFile);
4151
        } catch (Exception ex) {
4152
            logger.warn("Can't open identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.", ex);
4153
            return;
4154
        }
4155
        String identityManagerClassName = identityManagementConfig.getString("IdentityManager", null);
4156
        String identityManagementInitializerClassName = identityManagementConfig.getString("IdentityManagementInitializer", null);
4157
        try {
4158
            if (identityManagerClassName != null) {
4159
                Class identityManagerClass = plugin.getClassLoader().loadClass(identityManagerClassName);
4160
                ToolsLocator.registerIdentityManager(identityManagerClass);
4161
            } else {
4162
                logger.info("Entry IdentityManager not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4163
            }
4164

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

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

    
4180
}