Statistics
| Revision:

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

History | View | Annotate | Download (163 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
 */
202
public class Launcher {
203

    
204
    private static Arguments arguments;
205

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

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

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

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

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

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

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

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

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

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

    
299
            return item;
300
        }
301

    
302
    }
303

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

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

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

    
323
    }
324

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

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

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

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

    
353
    protected static ListBaseException launcherrors = null;
354

    
355
    protected static Theme theme = null;
356

    
357
    private List<String> deprecatedPluginNames = null;
358

    
359
    private static final class ProxyAuth extends Authenticator {
360

    
361
        private PasswordAuthentication auth;
362

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

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

    
372
    private static Launcher launcherInstance;
373

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

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

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

    
397
    protected void downloadExtensions(String extDir) {
398
        // do nothing
399
    }
400

    
401
    public static class LaunchException extends ListBaseException {
402

    
403
        private static final long serialVersionUID = 4541192746962684705L;
404

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

    
411
    }
412

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

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

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

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

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

    
447
    public static Arguments getArguments() {
448
        return arguments;
449
    }
450
    
451
    public void doMain(String[] args) throws Exception {
452

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

    
460
        initializeApp(args, null);
461

    
462
        // Solucionamos el problema de permisos que se produc?do con Java
463
        // Web Start con este codigo.
464
        Policy.setPolicy(new Policy() {
465

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

    
472
            public void refresh() {
473
            }
474
        });
475

    
476
        new DefaultLibrariesInitializer().fullInitialize(true);
477

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
694
        splashWindow.close();
695

    
696
        frame.setCursor(Cursor.DEFAULT_CURSOR);
697

    
698
        if (launcherrors != null) {
699
            NotificationManager.addError(launcherrors);
700
        }
701
        if( !arguments.contains("showgui", "false") ) {
702
            org.apache.log4j.Logger.getRootLogger().addAppender(
703
                    new NotificationAppender());
704
        }
705

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

    
711
    }
712

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

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

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

    
742
    }
743

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

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

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

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

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

    
791
    /**
792
     * @param args
793
     * @throws IOException
794
     * @throws ConfigurationException
795
     */
796
    private void initializeApp(String[] args, String applicationClasifier) throws IOException, ConfigurationException {
797
        if (args.length < 1) {
798
            appName = "gvSIG"; // Nombre de aplicacion por defecto es "gvSIG"
799
        } else {
800
            appName = args[0];
801
        }
802
        // Hacemos visibles los argumentos como una propiedad est?tica
803
        // de plugin services para quien lo quiera usar (por ejemplo, para
804
        // cargar un proyecto por l?nea de comandos)
805
        PluginServices.setArguments(args);
806

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

    
814
        ToolsLocator.registerDefaultToolsLibraries();
815

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

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

    
824
        configureLocales();
825

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

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

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

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

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

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

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

    
910
    public static String getApplicationName() {
911
        return appName;
912
    }
913

    
914
    private class NotificationAppender extends AppenderSkeleton {
915

    
916
        @Override
917
        protected void append(LoggingEvent event) {
918
            if (event.getLevel() == org.apache.log4j.Level.ERROR
919
                    || event.getLevel() == org.apache.log4j.Level.FATAL) {
920

    
921
                Throwable th = null;
922
                ThrowableInformation thi = event.getThrowableInformation();
923
                if (thi != null) {
924
                    th = thi.getThrowable();
925
                }
926
                NotificationManager.dispatchError(event.getRenderedMessage(), th);
927
                return;
928
            }
929
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
930
            // NotificationManager.dispatchWarning(event.getRenderedMessage(),
931
            // null);
932
            // return;
933
            // }
934
        }
935

    
936
        @Override
937
        public void close() {
938
            // TODO Auto-generated method stub
939

    
940
        }
941

    
942
        @Override
943
        public boolean requiresLayout() {
944
            // TODO Auto-generated method stub
945
            return false;
946
        }
947

    
948
    }
949

    
950
    /**
951
     * Return the directory applicaction is installed.
952
     */
953
    public static String getApplicationDirectory() {
954
        return getApplicationFolder().getAbsolutePath();
955
    }
956

    
957
    public static File getApplicationFolder() {
958
        // TODO: check if there is a better way to handle this
959
        return new File(System.getProperty("user.dir"));
960
    }
961

    
962
    private void registerIcons() {
963
        IconTheme theme = PluginServices.getIconTheme();
964
        ClassLoader loader = Launcher.class.getClassLoader();
965

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

    
984
    private Properties loadProperties(File f) {
985
        FileInputStream fin = null;
986
        Properties p = null;
987
        try {
988
            fin = new FileInputStream(f);
989
            p = new Properties();
990
            p.load(fin);
991
        } catch (IOException ex) {
992
            // Do nothing
993
        }
994
        return p;
995
    }
996

    
997
    /**
998
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
999
     * la aplicacion.
1000
     *
1001
     * @return Theme
1002
     */
1003
    private Theme getTheme(String pluginsDirectory) {
1004
        File infoFile = new File(Launcher.getApplicationFolder(), "package.info");
1005
        File themeFile = null;
1006
        List<Theme> themes = new ArrayList<Theme>();
1007

    
1008
        // Try to get theme from args
1009
        String name = PluginServices.getArgumentByName("andamiTheme");
1010
        if (name != null) {
1011
            themeFile = new File(name);
1012
            logger.info("search andami-theme in {}", themeFile.getAbsolutePath());
1013
            if (themeFile.exists()) {
1014
                Theme theme = new Theme(loadProperties(infoFile));
1015
                theme.readTheme(themeFile);
1016
                logger.info("andami-theme found in {}", themeFile.getAbsolutePath());
1017
                return theme;
1018
            }
1019
        }
1020

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

    
1042
        // Try to get theme from dir gvSIG in user home
1043
        themeFile = new File(getAppHomeDir(), "theme" + File.separator
1044
                + "andami-theme.xml");
1045
        logger.info("search andami-theme in user's home {}", themeFile
1046
                .getAbsolutePath());
1047
        if (themeFile.exists()) {
1048
            Theme theme = new Theme(loadProperties(infoFile));
1049
            theme.readTheme(themeFile);
1050
            themes.add(theme);
1051
        }
1052

    
1053
        // Try to get theme from the instalation dir of gvSIG.
1054
        themeFile = new File(getApplicationDirectory(), "theme"
1055
                + File.separator + "andami-theme.xml");
1056
        logger.info("search andami-theme in installation folder {}", themeFile
1057
                .getAbsolutePath());
1058
        if (themeFile.exists()) {
1059
            Theme theme = new Theme(loadProperties(infoFile));
1060
            theme.readTheme(themeFile);
1061
            themes.add(theme);
1062
        }
1063

    
1064
        Collections.sort(themes, new Comparator<Theme>() {
1065
            public int compare(Theme t1, Theme t2) {
1066
                return t2.getPriority() - t1.getPriority();
1067
            }
1068
        });
1069
        if (logger.isInfoEnabled()) {
1070
            logger.info("Found andami-themes in:");
1071
            for (Theme theme : themes) {
1072
                logger.info(" - " + theme.getPriority() + ", " + theme.getSource().getAbsolutePath());
1073
            }
1074
        }
1075
        Theme theme = themes.get(0);
1076
        logger.info("Using theme '" + theme.getSource() + "'.");
1077
        return theme;
1078
    }
1079

    
1080
    /**
1081
     * Establece los datos que tengamos guardados respecto de la configuracion
1082
     * del proxy.
1083
     */
1084
    private void configureProxy() {
1085
        String host = prefs.get("firewall.http.host", "");
1086
        String port = prefs.get("firewall.http.port", "");
1087

    
1088
        System.getProperties().put("http.proxyHost", host);
1089
        System.getProperties().put("http.proxyPort", port);
1090

    
1091
        // Ponemos el usuario y clave del proxy, si existe
1092
        String proxyUser = prefs.get("firewall.http.user", null);
1093
        String proxyPassword = prefs.get("firewall.http.password", null);
1094
        if (proxyUser != null) {
1095
            System.getProperties().put("http.proxyUserName", proxyUser);
1096
            System.getProperties().put("http.proxyPassword", proxyPassword);
1097

    
1098
            Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
1099
        } else {
1100
            Authenticator.setDefault(new ProxyAuth("", ""));
1101
        }
1102
    }
1103

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

    
1144
    private XMLEntity saveMDIStatus() {
1145
        XMLEntity xml = new XMLEntity();
1146
        // save frame size
1147
        int[] wh = new int[2];
1148
        wh[0] = frame.getWidth();
1149
        wh[1] = frame.getHeight();
1150
        xml.putProperty(MainFrame.MAIN_FRAME_SIZE, wh);
1151
        // save frame location
1152
        int[] xy = new int[2];
1153
        xy[0] = frame.getX();
1154
        xy[1] = frame.getY();
1155
        xml.putProperty(MainFrame.MAIN_FRAME_POS, xy);
1156
        // save frame status
1157
        xml.putProperty(MainFrame.MAIN_FRAME_EXT_STATE,
1158
                frame.getExtendedState());
1159
        return xml;
1160
    }
1161

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

    
1176
    private void loadPluginsPersistence() throws ConfigurationException {
1177
        XMLEntity entity = persistenceFromXML();
1178

    
1179
        for (int i = 0; i < entity.getChildrenCount(); i++) {
1180
            XMLEntity plugin = entity.getChild(i);
1181
            String pName = plugin
1182
                    .getStringProperty("com.iver.andami.pluginName");
1183

    
1184
            if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
1185
                pName = "org.gvsig.app";
1186
            }
1187
            if (pluginsServices.get(pName) != null) {
1188
                ((PluginServices) pluginsServices.get(pName))
1189
                        .setPersistentXML(plugin);
1190
            } else {
1191
                if (pName.startsWith("Andami.Launcher")) {
1192
                    restoreMDIStatus(plugin);
1193
                }
1194
            }
1195
        }
1196
    }
1197

    
1198
    /**
1199
     * Salva la persistencia de los plugins.
1200
     *
1201
     * @author LWS
1202
     */
1203
    private void savePluginPersistence() {
1204
        Iterator<String> i = pluginsConfig.keySet().iterator();
1205

    
1206
        XMLEntity entity = new XMLEntity();
1207

    
1208
        while (i.hasNext()) {
1209
            String pName = i.next();
1210
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
1211
            XMLEntity ent = ps.getPersistentXML();
1212

    
1213
            if (ent != null) {
1214
                ent.putProperty("com.iver.andami.pluginName", pName);
1215
                entity.addChild(ent);
1216
            }
1217
        }
1218
        XMLEntity ent = saveMDIStatus();
1219
        if (ent != null) {
1220
            ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
1221
            entity.addChild(ent);
1222
        }
1223
        try {
1224
            persistenceToXML(entity);
1225
        } catch (ConfigurationException e1) {
1226
            this
1227
                    .addError(
1228
                            Messages
1229
                            .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1230
                            e1);
1231
        }
1232
    }
1233

    
1234
    private void installPluginsLabels() {
1235
        Iterator<String> i = pluginsConfig.keySet().iterator();
1236

    
1237
        while (i.hasNext()) {
1238
            String name = i.next();
1239
            PluginConfig pc = pluginsConfig.get(name);
1240
            PluginServices ps = (PluginServices) pluginsServices.get(name);
1241

    
1242
            LabelSet[] ls = pc.getLabelSet();
1243

    
1244
            for (int j = 0; j < ls.length; j++) {
1245
                PluginClassLoader loader = ps.getClassLoader();
1246

    
1247
                try {
1248
                    Class clase = loader.loadClass(ls[j].getClassName());
1249
                    frame.setStatusBarLabels(clase, ls[j].getLabel());
1250
                } catch (Throwable e) {
1251
                    this.addError(
1252
                            Messages.getString("Launcher.labelset_class"), e);
1253
                }
1254
            }
1255
        }
1256
    }
1257

    
1258
    private String configureSkin(XMLEntity xml, String defaultSkin) {
1259
        if (defaultSkin == null) {
1260
            for (int i = 0; i < xml.getChildrenCount(); i++) {
1261
                if (xml.getChild(i).contains("Skin-Selected")) {
1262
                    String className = xml.getChild(i).getStringProperty(
1263
                            "Skin-Selected");
1264
                    return className;
1265
                }
1266
            }
1267
        }
1268
        // return "com.iver.core.mdiManager.NewSkin";
1269
        return defaultSkin;
1270
    }
1271

    
1272
    private void fixSkin(SkinExtension skinExtension,
1273
            PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1274
        // now insert the skin selected.
1275
        MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1276
                // MDIManagerFactory.setSkinExtension(se,
1277
        // ps.getClassLoader());
1278

    
1279
        Class<? extends IExtension> skinClass;
1280

    
1281
        try {
1282
            skinClass = (Class<? extends IExtension>) pluginClassLoader
1283
                    .loadClass(skinExtension.getClassName());
1284

    
1285
            IExtension skinInstance = skinClass.newInstance();
1286
            ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1287
                    skinInstance, ExtensionDecorator.INACTIVE);
1288
            classesExtensions.put(skinClass, newExtensionDecorator);
1289
        } catch (ClassNotFoundException e) {
1290
            logger.error(Messages
1291
                    .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1292
                    e);
1293
            throw new MDIManagerLoadException(e);
1294
        } catch (InstantiationException e) {
1295
            logger
1296
                    .error(
1297
                            Messages
1298
                            .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1299
                            e);
1300
            throw new MDIManagerLoadException(e);
1301
        } catch (IllegalAccessException e) {
1302
            logger
1303
                    .error(
1304
                            Messages
1305
                            .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1306
                            e);
1307
            throw new MDIManagerLoadException(e);
1308
        }
1309

    
1310
    }
1311

    
1312
    /**
1313
     * DOCUMENT ME!
1314
     *
1315
     * @throws MDIManagerLoadException
1316
     */
1317
    private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1318
        XMLEntity entity = null;
1319
        try {
1320
            entity = persistenceFromXML();
1321
        } catch (ConfigurationException e1) {
1322
            // TODO Auto-generated catch block
1323
            e1.printStackTrace();
1324
        }
1325
        Iterator<String> i = pluginsConfig.keySet().iterator();
1326

    
1327
        SkinExtension skinExtension = null;
1328
        PluginClassLoader pluginClassLoader = null;
1329
        List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1330
        while (i.hasNext()) {
1331
            String name = i.next();
1332
            PluginConfig pc = pluginsConfig.get(name);
1333
            PluginServices ps = pluginsServices.get(name);
1334

    
1335
            if (pc.getExtensions().getSkinExtension() != null) {
1336
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1337
                // logger.warn(Messages.getString(
1338
                // "Launcher.Dos_skin_extension"));
1339
                // }
1340

    
1341
                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1342
                for (int numExten = 0; numExten < se.length; numExten++) {
1343
                    skinExtensions.add(se[numExten]);
1344
                }
1345
                for (int j = 0; j < se.length; j++) {
1346
                    String configuredSkin = this.configureSkin(entity,
1347
                            defaultSkin);
1348
                    if ((configuredSkin != null)
1349
                            && configuredSkin.equals(se[j].getClassName())) {
1350
                        skinExtension = se[j];
1351
                        pluginClassLoader = ps.getClassLoader();
1352
                    }
1353
                }
1354
            }
1355
        }
1356

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

    
1373
    }
1374

    
1375
    private static void frameIcon(Theme theme) {
1376
        Iterator<String> i = pluginsConfig.keySet().iterator();
1377

    
1378
        while (i.hasNext()) {
1379
            String pName = i.next();
1380
            PluginConfig pc = pluginsConfig.get(pName);
1381
            if (pc.getIcon() != null) {
1382
                if (theme.getIcon() != null) {
1383
                    frame.setIconImage(theme.getIcon().getImage());
1384
                } else {
1385

    
1386
                    ImageIcon icon = PluginServices.getIconTheme().get(
1387
                            pc.getIcon().getSrc());
1388
                    frame.setIconImage(icon.getImage());
1389

    
1390
                }
1391
                if (theme.getName() != null) {
1392
                    frame.setTitlePrefix(theme.getName());
1393
                } else {
1394
                    frame.setTitlePrefix(pc.getIcon().getText());
1395
                }
1396
                if (theme.getBackgroundImage() != null) {
1397

    
1398
                    PluginServices.getMDIManager().setBackgroundImage(
1399
                            theme.getBackgroundImage(), theme.getTypeDesktop());
1400
                }
1401
            }
1402
        }
1403
    }
1404

    
1405
    private void initializeExtensions() {
1406

    
1407
        List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1408
                pluginsOrdered.size());
1409
        classLoaders.add(getClass().getClassLoader());
1410
        Iterator<String> iter = pluginsOrdered.iterator();
1411

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

    
1436
            Extension[] exts = pc.getExtensions().getExtension();
1437

    
1438
            TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1439
                    new ExtensionComparator());
1440

    
1441
            for (int j = 0; j < exts.length; j++) {
1442
                if (!exts[j].getActive()) {
1443
                    continue;
1444
                }
1445

    
1446
                if (orderedExtensions.contains(exts[j])) {
1447
                    logger.warn("Two extensions with the same priority ("
1448
                            + exts[j].getClassName() + ")");
1449
                }
1450

    
1451
                orderedExtensions.add(exts[j]);
1452
            }
1453

    
1454
            Iterator<Extension> e = orderedExtensions.iterator();
1455

    
1456
            logger.info("Initializing extensions of plugin " + pName + ": ");
1457
            while (e.hasNext()) {
1458
                Extension extension = e.next();
1459
                org.gvsig.andami.plugins.IExtension extensionInstance;
1460

    
1461
                try {
1462
                    logger.info("Initializing " + extension.getClassName()
1463
                            + "...");
1464
                    message(extension.getClassName() + "...");
1465
                    Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1466
                            .getClassLoader().loadClass(
1467
                                    extension.getClassName());
1468
                    extensionInstance = extensionClass.newInstance();
1469
                    if (extensionInstance instanceof org.gvsig.andami.plugins.Extension) {
1470
                        ((org.gvsig.andami.plugins.Extension) extensionInstance).setPlugin(ps);
1471
                    } else {
1472
                        logger.warn("The extension " + extensionClass.getName() + " don't extends of Extension.");
1473
                    }
1474

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

    
1493
                    extensionInstance.initialize();
1494
                    extensions.add(extensionInstance);
1495

    
1496
                } catch (NoClassDefFoundError e1) {
1497
                    this.addError("Can't find class extension ("
1498
                            + extension.getClassName() + ")", e1);
1499
                } catch (Throwable e1) {
1500
                    this.addError("Can't initialize extension '"
1501
                            + extension.getClassName() + "'.", e1);
1502
                }
1503
            }
1504
        }
1505
    }
1506

    
1507
    private void postInitializeExtensions() {
1508
        logger.info("PostInitializing extensions: ");
1509

    
1510
        for (int i = 0; i < extensions.size(); i++) {
1511
            org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1512
                    .get(i);
1513
            String name = extensionInstance.getClass().getName();
1514
            logger.info("PostInitializing " + name + "...");
1515
            message(name + "...");
1516
            try {
1517
                extensionInstance.postInitialize();
1518
            } catch (Throwable ex) {
1519
                this.addError("postInitialize of extension '"
1520
                        + extensionInstance.getClass().getName() + "' failed",
1521
                        ex);
1522
            }
1523
        }
1524
    }
1525

    
1526
    private void registerActionOfExtensions(ActionInfoManager actionManager,
1527
            Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1528
        ActionInfo actionInfo;
1529
        while (extensiones.hasMoreElements()) {
1530
            SkinExtensionType extension = extensiones.nextElement();
1531
            Class<? extends IExtension> classExtension;
1532
            try {
1533
                classExtension = (Class<? extends IExtension>) loader
1534
                        .loadClass(extension.getClassName());
1535

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

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

    
1579
                }
1580
                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1581
                while (toolBars.hasMoreElements()) {
1582
                    ToolBar toolBar = toolBars.nextElement();
1583

    
1584
                    Enumeration<ActionTool> actionTools = toolBar
1585
                            .enumerateActionTool();
1586
                    while (actionTools.hasMoreElements()) {
1587
                        ActionTool actionTool = actionTools.nextElement();
1588
                        actionInfo = actionManager.createAction(
1589
                                classExtension, actionTool.getName(),
1590
                                actionTool.getText(),
1591
                                actionTool.getActionCommand(),
1592
                                actionTool.getIcon(),
1593
                                null,
1594
                                actionTool.getPosition(),
1595
                                actionTool.getTooltip());
1596
                        actionInfo = actionManager.registerAction(actionInfo);
1597
                        if (actionInfo != null) {
1598
                            actionTool.setActionCommand(actionInfo.getCommand());
1599
                            actionTool.setTooltip(actionInfo.getTooltip());
1600
                            actionTool.setIcon(actionInfo.getIconName());
1601
                            actionTool.setPosition(actionInfo.getPosition());
1602
                            actionTool.setName(actionInfo.getName());
1603
                        }
1604
                    }
1605

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

    
1637
    @SuppressWarnings("unchecked")
1638
    private void registerActions() {
1639
        logger.info("registerActions");
1640

    
1641
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1642
        Iterator<String> it = pluginsConfig.keySet().iterator();
1643

    
1644
        while (it.hasNext()) {
1645
            String pluginName = it.next();
1646
            PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1647
            PluginServices pluginService = pluginsServices.get(pluginName);
1648
            PluginClassLoader loader = pluginService.getClassLoader();
1649

    
1650
            logger.info("registerActions of plugin '" + pluginName + "'.");
1651

    
1652
            Extensions extensionConfig = pluginConfig.getExtensions();
1653

    
1654
            Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1655
            registerActionOfExtensions(actionManager, extensiones, loader);
1656

    
1657
            Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1658
            registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1659

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

    
1687
        }
1688
    }
1689

    
1690
    private TreeSet<SortableMenu> getOrderedMenus() {
1691

    
1692
        TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1693
                new MenuComparator());
1694

    
1695
        Iterator<String> i = pluginsConfig.keySet().iterator();
1696

    
1697
        while (i.hasNext()) {
1698
            String pName = i.next();
1699
            try {
1700
                PluginServices ps = pluginsServices.get(pName);
1701
                PluginConfig pc = pluginsConfig.get(pName);
1702

    
1703
                Extension[] exts = pc.getExtensions().getExtension();
1704

    
1705
                for (int j = 0; j < exts.length; j++) {
1706
                    if (!exts[j].getActive()) {
1707
                        continue;
1708
                    }
1709

    
1710
                    Menu[] menus = exts[j].getMenu();
1711

    
1712
                    for (int k = 0; k < menus.length; k++) {
1713
                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1714
                                exts[j], menus[k]);
1715

    
1716
                        if (orderedMenus.contains(sm)) {
1717
                            this
1718
                                    .addError(Messages
1719
                                            .getString("Launcher.Two_menus_with_the_same_position")
1720
                                            + " - "
1721
                                            + menus[k].getText()
1722
                                            + " - " + exts[j].getClassName());
1723
                        }
1724

    
1725
                        orderedMenus.add(sm);
1726
                    }
1727
                }
1728

    
1729
                // Se instalan las extensiones de MDI
1730
                SkinExtension[] skinExts = pc.getExtensions()
1731
                        .getSkinExtension();
1732
                for (int j = 0; j < skinExts.length; j++) {
1733

    
1734
                    if (skinExts[j] != null) {
1735
                        Menu[] menu = skinExts[j].getMenu();
1736

    
1737
                        for (int k = 0; k < menu.length; k++) {
1738
                            SortableMenu sm = new SortableMenu(ps
1739
                                    .getClassLoader(), skinExts[j], menu[k]);
1740

    
1741
                            if (orderedMenus.contains(sm)) {
1742
                                this
1743
                                        .addError(Messages
1744
                                                .getString("Launcher.Two_menus_with_the_same_position")
1745
                                                + skinExts[j].getClassName());
1746
                            }
1747

    
1748
                            orderedMenus.add(sm);
1749
                        }
1750
                    }
1751
                }
1752

    
1753
            } catch (Throwable e) {
1754
                addError("Error initializing menus of plugin '" + pName + "'",
1755
                        e);
1756
            }
1757

    
1758
        }
1759

    
1760
        return orderedMenus;
1761
    }
1762

    
1763
    private void installPluginsMenus() {
1764
        logger.info("installPluginsMenus");
1765

    
1766
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1767

    
1768
        // Se itera por los menus ordenados
1769
        Iterator<SortableMenu> e = orderedMenus.iterator();
1770

    
1771
        // Se ordenan los menues
1772
        while (e.hasNext()) {
1773
            try {
1774
                SortableMenu sm = e.next();
1775
                logger.debug(sm.menu.getPosition() + ":" + sm.menu.getText() + ":" + sm.loader.getPluginName() + ":" + sm.extension.getClassName());
1776
                frame.addMenu(sm.loader, sm.extension, sm.menu);
1777
            } catch (Throwable ex) {
1778
                this.addError(
1779
                        Messages.getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1780
                        ex
1781
                );
1782
            }
1783
        }
1784
    }
1785

    
1786
    public class PluginMenuItem {
1787

    
1788
        private Menu menu;
1789
        private PluginClassLoader loader;
1790
        private SkinExtensionType extension;
1791

    
1792
        PluginMenuItem(PluginClassLoader loader,
1793
                SkinExtensionType extension, Menu menu) {
1794
            this.menu = menu;
1795
            this.loader = loader;
1796
            this.extension = extension;
1797
        }
1798

    
1799
        public PluginServices getPlugin() {
1800
            String pluginName = loader.getPluginName();
1801
            return PluginServices.getPluginServices(pluginName);
1802
        }
1803

    
1804
        public String getExtensionName() {
1805
            return this.extension.getClassName();
1806
        }
1807

    
1808
        public IExtension getExtension() {
1809
            Class<?> extensionClass;
1810
            try {
1811
                extensionClass = loader.loadClass(this.extension.getClassName());
1812
            } catch (ClassNotFoundException e) {
1813
                return null;
1814
            }
1815
            return PluginServices.getExtension(extensionClass);
1816
        }
1817

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

    
1822
        public long getPosition() {
1823
            return this.menu.getPosition();
1824
        }
1825

    
1826
        public String getName() {
1827
            return this.menu.getName();
1828
        }
1829

    
1830
        public boolean isParent() {
1831
            return menu.getIs_separator();
1832
        }
1833

    
1834
        public String getPluginName() {
1835
            return this.loader.getPluginName();
1836
        }
1837

    
1838
        public ActionInfo getAction() {
1839
            ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1840
            return manager.getAction(this.menu.getName());
1841
        }
1842
    }
1843

    
1844
    public List<PluginMenuItem> getPluginMenuItems() {
1845
        List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1846

    
1847
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1848
        Iterator<SortableMenu> e = orderedMenus.iterator();
1849
        while (e.hasNext()) {
1850
            SortableMenu sm = e.next();
1851
            PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1852
            menuItems.add(item);
1853
        }
1854
        return menuItems;
1855
    }
1856

    
1857
    private List<ToolBar> getOrderedToolBars() {
1858
        Map<String, ToolBar> toolbars = new HashMap<>();
1859

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

    
1894
            @Override
1895
            public int compare(ToolBar o1, ToolBar o2) {
1896
                return Integer.compare(o1.getPosition(), o2.getPosition());
1897
            }
1898
        });
1899
        return toolBarsList;
1900
    }
1901

    
1902
    /**
1903
     * Installs the menus, toolbars, actiontools, selectable toolbars and
1904
     * combos. The order in which they are shown is determined here.
1905
     */
1906
    private void installPluginsControls() {
1907
        logger.info("installPluginsControls (toolbars)");
1908
        installPluginsControlsToToolsbar();
1909
        installPluginsControlsToStatusbar();
1910
    }
1911

    
1912
    private void installPluginsControlsToToolsbar() {
1913

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

    
1954
            for( SortableTool tool : tools ) {
1955
                try {
1956
                    if (tool.actiontool != null) {
1957
                        frame.addTool(tool.loader, tool.extension,
1958
                            tool.toolbar, tool.actiontool
1959
                        );
1960
                    } else {
1961
                        frame.addTool(tool.loader, tool.extension,
1962
                            tool.toolbar, tool.selectabletool
1963
                        );
1964
                    }
1965
                } catch (Exception ex) {
1966
                }
1967
            }
1968
        }
1969
    }
1970

    
1971
    private void installPluginsControlsToStatusbar() {
1972
        Iterator<String> pluginNames = pluginsConfig.keySet().iterator();
1973

    
1974
        Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1975
        Set<Extension> orderedExtensions = new TreeSet<Extension>(new ExtensionComparator());
1976

    
1977
        while (pluginNames.hasNext()) {
1978
            String pluginName = pluginNames.next();
1979
            try {
1980
                PluginConfig pc = pluginsConfig.get(pluginName);
1981
                PluginServices ps = pluginsServices.get(pluginName);
1982

    
1983
                Extension[] exts = pc.getExtensions().getExtension();
1984

    
1985
                for (int j = 0; j < exts.length; j++) {
1986
                    String cname = "unknow";
1987
                    try {
1988
                        cname = exts[j].getClassName();
1989
                        if (exts[j].getActive() && !cname.equals(LibraryExtension.class.getName())) {
1990
                            if (orderedExtensions.contains(exts[j])) {
1991
                                this.addError(
1992
                                    Messages.getString("Launcher.Two_extensions_with_the_same_priority")
1993
                                    + cname
1994
                                );
1995
                            }
1996

    
1997
                            orderedExtensions.add(exts[j]);
1998
                            extensionPluginServices.put(exts[j], ps);
1999
                        }
2000
                    } catch (Throwable e) {
2001
                        addError("Error initializing controls of plugin '"
2002
                                + pluginName + "' extension '" + cname + "'", e);
2003
                    }
2004
                }
2005
            } catch (Throwable e) {
2006
                addError("Error initializing controls of plugin '" + pluginName
2007
                        + "'", e);
2008
            }
2009
        }
2010

    
2011
        Iterator<Extension> e = orderedExtensions.iterator();
2012

    
2013
        // load the combo-scales and combo-buttons for the status bar
2014
        while (e.hasNext()) {
2015
            Extension ext = e.next();
2016
            String extName = "unknow";
2017
            try {
2018
                extName = ext.getClassName();
2019

    
2020
                // get controls for statusBar
2021
                PluginServices ps = extensionPluginServices.get(ext);
2022
                PluginClassLoader loader = ps.getClassLoader();
2023

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

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

    
2117
    }
2118

    
2119
    /**
2120
     * Adds new plugins to the the andami-config file.
2121
     */
2122
    private void updateAndamiConfig() {
2123
        Set<String> olds = new HashSet<String>();
2124

    
2125
        Plugin[] plugins = andamiConfig.getPlugin();
2126

    
2127
        for (int i = 0; i < plugins.length; i++) {
2128
            olds.add(plugins[i].getName());
2129
        }
2130

    
2131
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2132

    
2133
        while (i.hasNext()) {
2134
            PluginServices ps = i.next();
2135

    
2136
            if (!olds.contains(ps.getPluginName())) {
2137
                Plugin p = new Plugin();
2138
                p.setName(ps.getPluginName());
2139
                p.setUpdate(false);
2140

    
2141
                andamiConfig.addPlugin(p);
2142
            }
2143
        }
2144
    }
2145

    
2146
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2147
        URL[] urls = null;
2148

    
2149
        String libfolderPath = pluginConfig.getLibraries().getLibraryDir();
2150
        File libFolderFile = new File(pluginConfig.getPluginFolder(), libfolderPath);
2151

    
2152
        File[] files = libFolderFile.listFiles(new FileFilter() {
2153

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

    
2174
    private static class OrderedPlugins extends ArrayList<String> {
2175

    
2176
        private List<String> problems = new ArrayList<String>();
2177
        private int retries = 0;
2178
        private PluginsConfig pluginsConfig = null;
2179
        private List<String> deprcatedPluginNames = null;
2180

    
2181
        OrderedPlugins(PluginsConfig pluginsConfig, List<String>deprcatedPluginNames) {
2182
            super();
2183
            this.pluginsConfig = pluginsConfig;
2184
            this.deprcatedPluginNames = deprcatedPluginNames;
2185
            List<String> pluginNames = new ArrayList<String>();
2186
            for (String pluginName : pluginsConfig.keySet()) {
2187
                pluginNames.add(pluginName);
2188
            }
2189
            Collections.sort(pluginNames);
2190
            for (String pluginName : pluginNames) {
2191
                this.add(pluginName);
2192
            }
2193
        }
2194

    
2195
        public List<String> getProblems() {
2196
            return this.problems;
2197
        }
2198

    
2199
        private void addProblem(String msg) {
2200
           this.problems.add(msg);
2201
        }
2202

    
2203
        public boolean add(String pluginName) {
2204
            return this.add(pluginName,new ArrayList<String>());
2205
        }
2206

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

    
2264
    private void loadPluginServices() {
2265
        OrderedPlugins orderedPlugins = getOrdererPluginsNames();
2266

    
2267
        if( !orderedPlugins.getProblems().isEmpty() ) {
2268
            for (String problem : orderedPlugins.getProblems()) {
2269
                logger.warn(problem);
2270
            }
2271
        }
2272

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

    
2276
            URL[] urls = getPluginClasspathURLs(config);
2277

    
2278
            List<PluginClassLoader> loaders = new ArrayList<PluginClassLoader>();
2279
            for (Depends dependency : config.getDepends()) {
2280
                String dependencyName = dependency.getPluginName();
2281
                PluginServices dependencyPluginService = pluginsServices.get(dependencyName);
2282
                if( dependencyPluginService == null ) {
2283
                    if( dependency.getOptional() ) {
2284
                        logger.info("Procesing plugin '"+pluginName+", optional dependency not found ("+dependencyName+").");
2285
                    } else {
2286
                        logger.warn("Procesing plugin '"+pluginName+", dependency not found ("+dependencyName+").");
2287
                    }
2288
                    continue;
2289
                }
2290
                loaders.add(dependencyPluginService.getClassLoader());
2291
            }
2292
            try {
2293
                PluginClassLoader loader = new PluginClassLoader(
2294
                        urls,
2295
                        config.getPluginFolder().getAbsolutePath(),
2296
                        Launcher.class.getClassLoader(),
2297
                        loaders
2298
                );
2299
                PluginServices ps = new PluginServices(
2300
                        loader,
2301
                        PluginsConfig.getAlternativeNames(config)
2302
                );
2303
                logger.info("Plugin '" + pluginName + "' created");
2304
                pluginsServices.put(ps.getPluginName(), ps);
2305
                pluginsOrdered.add(pluginName);
2306
            } catch (IOException ex) {
2307
                logger.warn("Can't create PluginServices for '" + pluginName + "'.", ex);
2308
            }
2309
        }
2310

    
2311
        // Se eliminan los plugins que no fueron instalados
2312
        List<String> pluginsToRemove = new ArrayList<String>();
2313
        for (String pluginName : pluginsConfig.keySet()) {
2314
            PluginServices pluginService = pluginsServices.get(pluginName);
2315
            if( pluginService == null ) {
2316
                pluginsToRemove.add(pluginName);
2317
            }
2318
        }
2319
        for (String pluginName : pluginsToRemove) {
2320
            logger.warn("Removed plugin "+pluginName+".");
2321
            pluginsConfig.remove(pluginName);
2322
       }
2323
    }
2324

    
2325
    /*
2326
    private void dumpPluginsDependencyInformation() {
2327
        logger.info("Plugin dependency information");
2328
        Iterator<String> i = pluginsConfig.keySet().iterator();
2329
        while (i.hasNext()) {
2330
            String pluginName = i.next();
2331
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2332
            logger.info("  Plugin " + pluginName);
2333
            Depends[] dependencies = config.getDepends();
2334
            for (int j = 0; j < dependencies.length; j++) {
2335
                Depends dependency = dependencies[j];
2336
                String dependencyName = dependency.getPluginName();
2337
                logger.info("    Dependency " + dependencyName);
2338
            }
2339
        }
2340
    }
2341
    */
2342
    private void pluginsMessages() {
2343
        Iterator<String> iterator = pluginsOrdered.iterator();
2344
        PluginConfig config;
2345
        PluginServices ps;
2346

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2619
    }
2620

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

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

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

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

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

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

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

    
2683
    public synchronized static void closeApplication(boolean quietly) {
2684
        TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2685
        if( quietly ) {
2686
            terminationProcess.closeAndami();
2687
        } else {
2688
            terminationProcess.run();
2689
        }
2690
    }
2691
    
2692
    static HashMap getClassesExtensions() {
2693
        return classesExtensions;
2694
    }
2695

    
2696
    public static IExtension getExtensionByName(String extensionName) {
2697
        if( StringUtils.isEmpty(extensionName) ) {
2698
            return null;
2699
        }
2700
        for (Entry<Class<? extends IExtension>, ExtensionDecorator> entry : classesExtensions.entrySet()) {
2701
            Class<? extends IExtension> extensionClass = entry.getKey();
2702
            IExtension extension = entry.getValue();
2703
            if( extensionName.equals(extensionClass.getName()) ) {
2704
                while( extension instanceof ExtensionDecorator ) {
2705
                    extension = ((ExtensionDecorator)extension).getExtension();
2706
                }
2707
                return extension;
2708
            }
2709
        }
2710
        return null;
2711
    }
2712

    
2713
    private static Extensions[] getExtensions() {
2714
        List<Extensions> array = new ArrayList<Extensions>();
2715
        Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2716

    
2717
        while (iter.hasNext()) {
2718
            array.add(iter.next().getExtensions());
2719
        }
2720

    
2721
        return array.toArray(new Extensions[array.size()]);
2722
    }
2723

    
2724
    public static Iterator getExtensionIterator() {
2725
        return extensions.iterator();
2726
    }
2727

    
2728
    public static HashMap getPluginConfig() {
2729
        return pluginsConfig;
2730
    }
2731

    
2732
    public static Extension getExtension(String s) {
2733
        Extensions[] exts = getExtensions();
2734

    
2735
        for (int i = 0; i < exts.length; i++) {
2736
            for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2737
                if (exts[i].getExtension(j).getClassName().equals(s)) {
2738
                    return exts[i].getExtension(j);
2739
                }
2740
            }
2741
        }
2742

    
2743
        return null;
2744
    }
2745

    
2746
    public static AndamiConfig getAndamiConfig() {
2747
        return andamiConfig;
2748
    }
2749

    
2750
    private static class ExtensionComparator implements Comparator {
2751

    
2752
        public int compare(Object o1, Object o2) {
2753
            Extension e1 = (Extension) o1;
2754
            Extension e2 = (Extension) o2;
2755

    
2756
            if (!e1.hasPriority() && !e2.hasPriority()) {
2757
                return -1;
2758
            }
2759

    
2760
            if (e1.hasPriority() && !e2.hasPriority()) {
2761
                return Integer.MIN_VALUE;
2762
            }
2763

    
2764
            if (e2.hasPriority() && !e1.hasPriority()) {
2765
                return Integer.MAX_VALUE;
2766
            }
2767

    
2768
            if (e1.getPriority() != e2.getPriority()) {
2769
                return e2.getPriority() - e1.getPriority();
2770
            } else {
2771
                return (e2.toString().compareTo(e1.toString()));
2772
            }
2773
        }
2774
    }
2775

    
2776
    private static class MenuComparator implements Comparator<SortableMenu> {
2777

    
2778
        private static ExtensionComparator extComp = new ExtensionComparator();
2779

    
2780
        public int compare(SortableMenu e1, SortableMenu e2) {
2781

    
2782
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2783
                if (e1.extension instanceof SkinExtensionType) {
2784
                    return 1;
2785
                } else if (e2.extension instanceof SkinExtensionType) {
2786
                    return -1;
2787
                } else {
2788
                    return extComp.compare(e1.extension, e2.extension);
2789
                }
2790
            }
2791

    
2792
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2793
                return Integer.MIN_VALUE;
2794
            }
2795

    
2796
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2797
                return Integer.MAX_VALUE;
2798
            }
2799

    
2800
            if (e1.menu.getPosition() == e2.menu.getPosition()) {
2801
                                // we don't return 0 unless both objects are the same, otherwise
2802
                // the objects get overwritten in the treemap
2803
                return (e1.toString().compareTo(e2.toString()));
2804
            }
2805
            if (e1.menu.getPosition() > e2.menu.getPosition()) {
2806
                return Integer.MAX_VALUE;
2807
            }
2808
            return Integer.MIN_VALUE;
2809

    
2810
        }
2811
    }
2812

    
2813
    private static class SortableMenu {
2814

    
2815
        public PluginClassLoader loader;
2816
        public Menu menu;
2817
        public SkinExtensionType extension;
2818

    
2819
        public SortableMenu(PluginClassLoader loader,
2820
                SkinExtensionType skinExt, Menu menu2) {
2821
            extension = skinExt;
2822
            menu = menu2;
2823
            this.loader = loader;
2824
        }
2825

    
2826
    }
2827

    
2828
    private static class SortableTool {
2829

    
2830
        public PluginClassLoader loader;
2831
        public ToolBar toolbar;
2832
        public ActionTool actiontool;
2833
        public SelectableTool selectabletool;
2834
        public SkinExtensionType extension;
2835

    
2836
        public SortableTool(PluginClassLoader loader,
2837
                SkinExtensionType skinExt, ToolBar toolbar2,
2838
                ActionTool actiontool2) {
2839
            extension = skinExt;
2840
            toolbar = toolbar2;
2841
            actiontool = actiontool2;
2842
            this.loader = loader;
2843
        }
2844

    
2845
        public SortableTool(PluginClassLoader loader,
2846
                SkinExtensionType skinExt, ToolBar toolbar2,
2847
                SelectableTool selectabletool2) {
2848
            extension = skinExt;
2849
            toolbar = toolbar2;
2850
            selectabletool = selectabletool2;
2851
            this.loader = loader;
2852
        }
2853

    
2854
        public long getPosition() {
2855
            if( this.actiontool!=null ) {
2856
                return this.actiontool.getPosition();
2857
            }
2858
            if( this.selectabletool!=null ) {
2859
                return this.selectabletool.getPosition();
2860
            }
2861
            return 0;
2862
        }
2863
    }
2864

    
2865
    private static class ToolBarComparator implements Comparator<SortableTool> {
2866

    
2867
        private static ExtensionComparator extComp = new ExtensionComparator();
2868

    
2869
        public int compare(SortableTool e1, SortableTool e2) {
2870

    
2871
                        // if the toolbars have the same name, they are considered to be
2872
            // the same toolbar, so we don't need to do further comparing
2873
            if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2874
                return 0;
2875
            }
2876

    
2877
            if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2878
                if (e1.extension instanceof SkinExtensionType) {
2879
                    return 1;
2880
                } else if (e2.extension instanceof SkinExtensionType) {
2881
                    return -1;
2882
                } else {
2883
                    return extComp.compare(e1.extension, e2.extension);
2884
                }
2885
            }
2886

    
2887
            if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2888
                return Integer.MIN_VALUE;
2889
            }
2890

    
2891
            if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2892
                return Integer.MAX_VALUE;
2893
            }
2894
            if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2895
                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2896
            }
2897

    
2898
            if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2899
                    && e1.toolbar.getSelectableTool().equals(
2900
                            e2.toolbar.getSelectableTool())) {
2901
                return 0;
2902
            }
2903
            return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2904
        }
2905
    }
2906

    
2907
    /**
2908
     * <p>
2909
     * This class is used to compare tools (selectabletool and actiontool),
2910
     * using the "position" attribute.
2911
     * </p>
2912
     * <p>
2913
     * The ordering criteria are:
2914
     * </p>
2915
     * <ul>
2916
     * <li>If the tools are placed in different toolbars, they use the toolbars'
2917
     * order. (using the ToolBarComparator).</li>
2918
     * <li></li>
2919
     * <li>If any of the tools has not 'position' attribute, the tool which
2920
     * <strong>has</strong> the attribute will be placed first.</li>
2921
     * <li>If both tools have the same position (or they don't have a 'position'
2922
     * attribute), the priority of the extensions where the tool is
2923
     * defined.</li>
2924
     * </ul>
2925
     *
2926
     */
2927
    private static class ToolComparator implements Comparator<SortableTool> {
2928

    
2929
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2930

    
2931
        public int compare(SortableTool e1, SortableTool e2) {
2932
            // compare the toolbars which contain the tools
2933
            long result = toolBarComp.compare(e1, e2);
2934
            if (result != 0) { // if the toolbars are different, use their order
2935
                return result > 0 ? 1 : -1;
2936
            }
2937
            // otherwise, compare the tools
2938
            long e1Position = -1, e2Position = -1;
2939

    
2940
            if (e1.actiontool != null) {
2941
                if (e1.actiontool.hasPosition()) {
2942
                    e1Position = e1.actiontool.getPosition();
2943
                }
2944
            } else if (e1.selectabletool != null) {
2945
                if (e1.selectabletool.hasPosition()) {
2946
                    e1Position = e1.selectabletool.getPosition();
2947
                }
2948
            }
2949

    
2950
            if (e2.actiontool != null) {
2951
                if (e2.actiontool.hasPosition()) {
2952
                    e2Position = e2.actiontool.getPosition();
2953
                }
2954
            } else if (e2.selectabletool != null) {
2955
                if (e2.selectabletool.hasPosition()) {
2956
                    e2Position = e2.selectabletool.getPosition();
2957
                }
2958
            }
2959

    
2960
            if ((e1Position == -1) && (e2Position != -1)) {
2961
                return 1;
2962
            }
2963
            if ((e1Position != -1) && (e2Position == -1)) {
2964
                return -1;
2965
            }
2966
            if ((e1Position != -1) && (e2Position != -1)) {
2967
                result = e1Position - e2Position;
2968
                                // we don't return 0 unless both objects are the same, otherwise
2969
                // the objects get overwritten in the treemap
2970
                if (result != 0) {
2971
                    return result > 0 ? 1 : -1;
2972
                }
2973
            }
2974
            return e1.toString().compareTo(e2.toString());
2975
        }
2976
    }
2977

    
2978
    public static String getDefaultLookAndFeel() {
2979
        String osName = (String) System.getProperty("os.name");
2980

    
2981
        if ((osName.length() > 4)
2982
                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2983
            return nonWinDefaultLookAndFeel;
2984
        }
2985
        if (osName.toLowerCase().startsWith("mac os x")) {
2986
            return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2987
        }
2988

    
2989
        return UIManager.getSystemLookAndFeelClassName();
2990
    }
2991

    
2992
    /**
2993
     * Gets the ISO 839 two-characters-long language code matching the provided
2994
     * language code (which may be an ISO 839-2/T three-characters-long code or
2995
     * an ISO 839-1 two-characters-long code).
2996
     *
2997
     * If the provided parameter is already two characters long, it returns the
2998
     * parameter without any modification.
2999
     *
3000
     * @param langCode A language code representing either an ISO 839-2/T
3001
     * language code or an ISO 839-1 code.
3002
     * @return A two-characters-long code specifying an ISO 839 language code.
3003
     */
3004
    private static String normalizeLanguageCode(String langCode) {
3005
        final String fileName = "iso_639.tab";
3006
        if (langCode.length() == 2) {
3007
            return langCode;
3008
        } else if (langCode.length() == 3) {
3009
            if (langCode.equals("va") || langCode.equals("val")) { // special
3010
                // case
3011
                // for
3012
                // Valencian
3013
                return "ca";
3014
            }
3015
            URL isoCodes = Launcher.class.getClassLoader()
3016
                    .getResource(fileName);
3017
            if (isoCodes != null) {
3018
                try {
3019
                    BufferedReader reader = new BufferedReader(
3020
                            new InputStreamReader(isoCodes.openStream(),
3021
                                    "ISO-8859-1"));
3022
                    String line;
3023

    
3024
                    while ((line = reader.readLine()) != null) {
3025
                        String[] language = line.split("\t");
3026
                        if (language[0].equals(langCode)) {
3027
                                                        // the three
3028
                            // characters code
3029
                            return language[2]; // third column i the two
3030
                            // characters code
3031
                        }
3032
                    }
3033
                } catch (IOException ex) {
3034
                    logger.error(Messages
3035
                            .getString("Error_reading_isocodes_file"), ex);
3036
                    return "es";
3037
                }
3038
            } else {
3039
                logger.error(Messages.getString("Error_reading_isocodes_file"));
3040
                return "es";
3041
            }
3042
        }
3043
        return "es";
3044
    }
3045

    
3046
    /**
3047
     * Configures the locales (languages and local resources) to be used by the
3048
     * application.
3049
     *
3050
     * First it tries to get the locale from the command line parameters, then
3051
     * the andami-config file is checked.
3052
     *
3053
     * The locale name is normalized to get a two characters language code as
3054
     * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
3055
     * also accepted from the command line or the configuration file).
3056
     *
3057
     * Finally, the gvsig-i18n library and the default locales for Java and
3058
     * Swing are configured.
3059
     *
3060
     */
3061
    private static void configureLocales() {
3062
        // Configurar el locale
3063
        String localeStr = null;
3064

    
3065
        if( getArguments().contains("language") ) {
3066
            localeStr = getArguments().get("language");
3067
        } else {
3068
            localeStr = andamiConfig.getLocaleLanguage();
3069
        }
3070
        localeStr = normalizeLanguageCode(localeStr);
3071
        locale = getLocale(
3072
                localeStr,
3073
                andamiConfig.getLocaleCountry(),
3074
                andamiConfig.getLocaleVariant()
3075
        );
3076
        org.gvsig.i18n.Messages.setCurrentLocale(locale);
3077
        JComponent.setDefaultLocale(locale);
3078
        /*
3079
         org.gvsig.i18n.Messages.addLocale(locale);
3080
         // add english and spanish as fallback languages
3081
         if ( localeStr.equals("es") || localeStr.equals("ca")
3082
         || localeStr.equals("gl") || localeStr.equals("eu")
3083
         || localeStr.equals("va") ) {
3084
         // prefer Spanish for languages spoken in Spain
3085
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3086
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3087
         } else {
3088
         // prefer English for the rest
3089
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3090
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3091
         }
3092
         */
3093
        // Create classloader for the i18n resources in the
3094
        // andami and user i18n folder. Those values will have
3095
        // precedence over any other values added afterwards
3096
        File appI18nFolder = new File(getApplicationFolder(), "i18n");
3097
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
3098
        if (!userI18nFolder.exists()) {
3099
            try {
3100
                FileUtils.forceMkdir(userI18nFolder);
3101
            } catch (IOException e) {
3102
                logger.info("Can't create i18n folder in gvSIG home (" + userI18nFolder + ").", e);
3103
            }
3104
        }
3105
//        logger.info("Loading i18n resources from the application and user "
3106
//                + "folders: {}, {}", appI18nFolder, userI18nFolder);
3107

    
3108
        URL[] i18nURLs = getURLsFromI18nFolders(userI18nFolder, appI18nFolder);
3109
        ClassLoader i18nClassLoader = URLClassLoader.newInstance(i18nURLs, null);
3110
        logger.info("loading resources from classloader " + i18nClassLoader.toString() + ".");
3111
        org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
3112
                "Andami Launcher");
3113

    
3114
        // Finally load the andami own i18n resources
3115
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
3116
                "Andami Launcher");
3117
    }
3118

    
3119
    private static URL[] getURLsFromI18nFolders(File userFolder, File appFolder) {
3120
        List<URL> urls = new ArrayList<URL>();
3121
        File[] files = new File[]{userFolder, appFolder};
3122
        for (int n1 = 0; n1 < files.length; n1++) {
3123
            File folder = files[n1];
3124
//                try {
3125
//                    urls.add(folder.toURI().toURL());
3126
//                } catch (MalformedURLException ex) {
3127
//                    logger.warn("Can't convert file to url (file="+userFolder.getAbsolutePath()+").", ex);
3128
//                    return null;
3129
//                }
3130
            File[] subFiles = folder.listFiles();
3131
            for (int n2 = 0; n2 < subFiles.length; n2++) {
3132
                File subFolder = subFiles[n2];
3133
                if ("andami".equalsIgnoreCase(subFolder.getName())) {
3134
                    // Skip andami and add the last.
3135
                    continue;
3136
                }
3137
                if (subFolder.isDirectory()) {
3138
                    try {
3139
                        urls.add(subFolder.toURI().toURL());
3140
                    } catch (MalformedURLException ex) {
3141
                        logger.warn("Can't convert file to url (file=" + subFolder.getAbsolutePath() + ").", ex);
3142
                        return null;
3143
                    }
3144
                }
3145
            }
3146
        }
3147
        File folder = new File(appFolder, "andami");
3148
        try {
3149
            urls.add(folder.toURI().toURL());
3150
        } catch (MalformedURLException ex) {
3151
            logger.warn("Can't convert file to url (file=" + folder.getAbsolutePath() + ").", ex);
3152
            return null;
3153
        }
3154
        return urls.toArray(new URL[urls.size()]);
3155
    }
3156

    
3157
    /**
3158
     * Gets Home Directory location of the application into users home folder.
3159
     *
3160
     * May be set from outside the aplication by means of
3161
     * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
3162
     *
3163
     * @return
3164
     */
3165
    public static String getAppHomeDir() {
3166
        return appHomeDir;
3167
    }
3168

    
3169
    public static File getApplicationHomeFolder() {
3170
        return new File(getAppHomeDir());
3171
    }
3172

    
3173
    /**
3174
     * Sets Home Directory location of the application. May be set from outside
3175
     * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3176
     * the name of the application
3177
     *
3178
     * @param appHomeDir
3179
     */
3180
    public static void setAppHomeDir(String appHomeDir) {
3181
        Launcher.appHomeDir = appHomeDir;
3182
    }
3183

    
3184
    /**
3185
     * Initialize the extesion that have to take the control of the state of
3186
     * action controls of the UI of all extensions. <br>
3187
     * <br>
3188
     * For use this option you have to add an argument to the command line like
3189
     * this: <br>
3190
     * <br>
3191
     * -exclusiveUI={pathToExtensionClass} <br>
3192
     *
3193
     */
3194
    private static void initializeExclusiveUIExtension() {
3195
        String name = PluginServices.getArgumentByName("exclusiveUI");
3196
        if (name == null) {
3197
            return;
3198
        }
3199

    
3200
        Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3201
                .iterator();
3202
        int charIndex;
3203
        Class<? extends IExtension> key;
3204
        while (iter.hasNext()) {
3205
            key = iter.next();
3206
            charIndex = key.getName().indexOf(name);
3207
            // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3208
            if (charIndex == 0) {
3209
                IExtension ext = classesExtensions.get(key);
3210
                if (ext instanceof ExtensionDecorator) {
3211
                    ext = ((ExtensionDecorator) ext).getExtension();
3212
                }
3213
                if (ext instanceof ExclusiveUIExtension) {
3214
                    PluginServices
3215
                            .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3216
                }
3217
                break;
3218
            }
3219
        }
3220

    
3221
        logger
3222
                .error(Messages
3223
                        .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3224
                        + " '" + name + "'");
3225
    }
3226

    
3227
    public static void initIconThemes() {
3228
        PluginsManager pluginsManager = PluginsLocator.getManager();
3229
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3230

    
3231
        File f = new File(pluginsManager.getApplicationHomeFolder(), "icon-theme");
3232
        if (!f.exists()) {
3233
            try {
3234
                f.mkdir();
3235
            } catch (Exception ex) {
3236
                // Do nothing
3237
            }
3238
        }
3239
        iconManager.getRepository().add(f, "_User");
3240

    
3241
        f = new File(pluginsManager.getApplicationFolder(), "icon-theme");
3242
        if (!f.exists()) {
3243
            try {
3244
                f.mkdir();
3245
            } catch (Exception ex) {
3246
                // Do nothing
3247
            }
3248
        }
3249
        iconManager.getRepository().add(f, "_Global");
3250

    
3251
        Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3252
        String defaultThemeID = prefs.get("default-theme", null);
3253
        if (defaultThemeID != null) {
3254
            IconTheme iconTheme = iconManager.get(defaultThemeID);
3255
            if (iconTheme != null) {
3256
                iconManager.setCurrent(iconTheme);
3257
            }
3258
        }
3259
        double scaleFactor;
3260
        try {
3261
            scaleFactor = prefs.getDouble("scaleFactor",1.0);
3262
        } catch(Throwable th) {
3263
            scaleFactor = 1.0;
3264
        }
3265
        iconManager.setScaleFactor(scaleFactor);
3266
    }
3267

    
3268
    public static void manageUnsavedData(String prompt) throws Exception {
3269
        final UnsavedDataPanel panel = new UnsavedDataPanel(prompt);
3270
        final List<IUnsavedData> unsavedData = PluginsLocator.getManager().getUnsavedData();
3271
        panel.setUnsavedData(unsavedData);
3272

    
3273
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3274

    
3275
            public void cancel(UnsavedDataPanel panel) {
3276
                panel.setVisible(false);
3277
            }
3278

    
3279
            public void discard(UnsavedDataPanel panel) {
3280
                panel.setVisible(false);
3281
            }
3282

    
3283
            public void accept(UnsavedDataPanel panel) {
3284
                panel.setVisible(false);
3285

    
3286
                try {
3287
                    PluginsLocator.getManager().saveUnsavedData(panel.getSelectedsUnsavedDataList());
3288
                } catch (UnsavedDataException e) {
3289
                    StringBuilder msg = new StringBuilder();
3290
                    msg.append(PluginServices.getText(this, "The_following_resources_could_not_be_saved"));
3291
                    msg.append("\n");
3292
                    for (Iterator iterator = e.getUnsavedData().iterator(); iterator.hasNext();) {
3293
                        IUnsavedData unsavedData = (IUnsavedData) iterator.next();
3294
                        msg.append(unsavedData.getResourceName());
3295
                        msg.append(" -- ");
3296
                        msg.append(unsavedData.getDescription());
3297
                        msg.append("\n");
3298
                    }
3299
                    JOptionPane.showMessageDialog(panel, msg, PluginServices.getText(this, "Resources_was_not_saved"), JOptionPane.ERROR_MESSAGE);
3300
                }
3301
            }
3302
        });
3303

    
3304
        //TODO: mostrar panel WindowManager
3305
        ToolsSwingLocator.getWindowManager().showWindow(
3306
                panel,
3307
                PluginServices.getText(panel, "Resource_was_not_saved"),
3308
                MODE.DIALOG);
3309

    
3310
    }
3311

    
3312
    /**
3313
     * Manages Andami termination process
3314
     *
3315
     */
3316
    public class TerminationProcess {
3317

    
3318
        private boolean proceed = false;
3319
        private UnsavedDataPanel panel = null;
3320

    
3321
        public void run() {
3322
            try {
3323
                int exit = manageUnsavedData();
3324
                if ((exit == JOptionPane.NO_OPTION)
3325
                        || (exit == JOptionPane.CLOSED_OPTION)) {
3326
                    // the user doesn't want to exit
3327
                    return;
3328
                }
3329
                closeAndami();
3330
            } catch (Exception e) {
3331
                logger.warn("It is not possible to close the application", e);
3332
                                // It is not possible to close the application.
3333
                // this exception has been registered before
3334
            }
3335
        }
3336

    
3337
        /**
3338
         * Finishes the application without asking user if want or not to save
3339
         * unsaved data.
3340
         */
3341
        public void closeAndami() {
3342
            PluginsManager pluginsManager = PluginsLocator.getManager();
3343
            pluginsManager.executeShutdownTasks();
3344

    
3345
            try {
3346
                saveAndamiConfig();
3347
            } catch (Exception ex) {
3348
                logger.error(
3349
                        "There was an error exiting application, can't save andami-config.xml",
3350
                        ex
3351
                );
3352
            }
3353

    
3354
            try {
3355
                // Persistencia de los plugins
3356
                savePluginPersistence();
3357
                savePluginsProperties();
3358
            } catch (Exception ex) {
3359
                logger.error(
3360
                        "There was an error exiting application, can't save plugins properties",
3361
                        ex
3362
                );
3363
            }
3364

    
3365
            // Finalize all the extensions
3366
            finalizeExtensions();
3367

    
3368
            try {
3369
                // Clean any temp data created
3370
                Utilities.cleanUpTempFiles();
3371
            } catch (Exception ex) {
3372
                logger.error(
3373
                        "There was an error exiting application, can't remove temporary files",
3374
                        ex
3375
                );
3376
            }
3377

    
3378
            logger.info("Quiting application.");
3379

    
3380
            // Para la depuraci?n de memory leaks
3381
            System.gc();
3382

    
3383
            System.exit(0);
3384
        }
3385

    
3386
        public void saveAndamiConfig() {
3387
            // Configuraci?n de Andami
3388
            try {
3389
                andamiConfigToXML(andamiConfigPath);
3390
            } catch (MarshalException e) {
3391
                logger
3392
                        .error(
3393
                                Messages
3394
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3395
                                e);
3396
            } catch (ValidationException e) {
3397
                logger
3398
                        .error(
3399
                                Messages
3400
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3401
                                e);
3402
            } catch (IOException e) {
3403
                logger
3404
                        .error(
3405
                                Messages
3406
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3407
                                e);
3408
            }
3409
        }
3410

    
3411
        private void savePluginsProperties() {
3412
            PluginsManager manager = PluginsLocator.getManager();
3413
            List<PluginServices> plugins = manager.getPlugins();
3414
            for (PluginServices plugin : plugins) {
3415
                if (plugin != null) {
3416
                    plugin.savePluginProperties();
3417
                }
3418
            }
3419
        }
3420

    
3421
        /**
3422
         * Exectutes the terminate method for all the extensions, in the reverse
3423
         * order they were initialized
3424
         *
3425
         */
3426
        private void finalizeExtensions() {
3427
            for (int i = extensions.size() - 1; i >= 0; i--) {
3428
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3429
                        .get(i);
3430
                String extensionName = "(unknow)";
3431
                try {
3432
                    extensionName = extensionInstance.getClass().getName();
3433
                    extensionInstance.terminate();
3434
                } catch (Exception ex) {
3435
                    logger.error(MessageFormat.format(
3436
                            "There was an error extension ending {0}",
3437
                            extensionName), ex);
3438
                }
3439
            }
3440
        }
3441

    
3442
        private IUnsavedData[] getUnsavedData() throws Exception {
3443
            List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3444
            IExtension exclusiveExtension = PluginServices
3445
                    .getExclusiveUIExtension();
3446

    
3447
            for (int i = extensions.size() - 1; i >= 0; i--) {
3448
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3449
                        .get(i);
3450
                IExtensionStatus status = null;
3451
                if (exclusiveExtension != null) {
3452
                    status = exclusiveExtension.getStatus(extensionInstance);
3453
                } else {
3454
                    status = extensionInstance.getStatus();
3455
                }
3456
                if (status != null) {
3457
                    try {
3458
                        if (status.hasUnsavedData()) {
3459
                            IUnsavedData[] array = status.getUnsavedData();
3460
                            for (int element = 0; element < array.length; element++) {
3461
                                unsavedDataList.add(array[element]);
3462
                            }
3463
                        }
3464
                    } catch (Exception e) {
3465
                        logger.info("Error calling the hasUnsavedData method",
3466
                                new Exception());
3467
                        int option = JOptionPane
3468
                                .showConfirmDialog(
3469
                                        frame,
3470
                                        Messages
3471
                                        .getString("error_getting_unsaved_data"),
3472
                                        Messages.getString("MDIFrame.salir"),
3473
                                        JOptionPane.YES_NO_OPTION);
3474
                        if (option == JOptionPane.NO_OPTION) {
3475
                            throw e;
3476
                        }
3477
                    }
3478
                }
3479
            }
3480
            return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3481
                    .size()]);
3482
        }
3483

    
3484
        public UnsavedDataPanel getUnsavedDataPanel() {
3485
            if (panel == null) {
3486
                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3487
            }
3488
            return panel;
3489
        }
3490

    
3491
        /**
3492
         * Checks if the extensions have some unsaved data, and shows a dialog
3493
         * to allow saving it. This dialog also allows to don't exit Andami.
3494
         *
3495
         * @return true if the user confirmed he wishes to exit, false otherwise
3496
         * @throws Exception
3497
         */
3498
        public int manageUnsavedData() throws Exception {
3499
            IUnsavedData[] unsavedData = getUnsavedData();
3500

    
3501
            // there was no unsaved data
3502
            if (unsavedData.length == 0) {
3503
                int option = JOptionPane
3504
                        .showConfirmDialog(frame, Messages
3505
                                .getString("MDIFrame.quiere_salir"), Messages
3506
                                .getString("MDIFrame.salir"),
3507
                                JOptionPane.YES_NO_OPTION);
3508
                return option;
3509
            }
3510

    
3511
            UnsavedDataPanel panel = getUnsavedDataPanel();
3512
            panel.setUnsavedDataArray(unsavedData);
3513

    
3514
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3515

    
3516
                public void cancel(UnsavedDataPanel panel) {
3517
                    proceed(false);
3518
                    PluginServices.getMDIManager().closeWindow(panel);
3519

    
3520
                }
3521

    
3522
                public void discard(UnsavedDataPanel panel) {
3523
                    proceed(true);
3524
                    PluginServices.getMDIManager().closeWindow(panel);
3525

    
3526
                }
3527

    
3528
                public void accept(UnsavedDataPanel panel) {
3529
                    IUnsavedData[] unsavedDataArray = panel
3530
                            .getSelectedsUnsavedData();
3531
                    boolean saved;
3532
                    for (int i = 0; i < unsavedDataArray.length; i++) {
3533
                        try {
3534
                            saved = unsavedDataArray[i].saveData();
3535
                        } catch (Exception ex) {
3536
                            PluginServices.getLogger().error(
3537
                                    "Error saving"
3538
                                    + unsavedDataArray[i]
3539
                                    .getResourceName(), ex);
3540
                            saved = false;
3541
                        }
3542
                        if (!saved) {
3543
                            JOptionPane
3544
                                    .showMessageDialog(
3545
                                            panel,
3546
                                            PluginServices
3547
                                            .getText(this,
3548
                                                    "The_following_resource_could_not_be_saved_")
3549
                                            + "\n"
3550
                                            + unsavedDataArray[i]
3551
                                            .getResourceName()
3552
                                            + " -- "
3553
                                            + unsavedDataArray[i]
3554
                                            .getDescription(),
3555
                                            PluginServices.getText(this,
3556
                                                    "unsaved_resources"),
3557
                                            JOptionPane.ERROR_MESSAGE);
3558

    
3559
                            try {
3560
                                unsavedDataArray = getUnsavedData();
3561
                            } catch (Exception e) {
3562
                                // This exception has been registered before
3563
                            }
3564
                            panel.setUnsavedDataArray(unsavedDataArray);
3565
                            return;
3566
                        }
3567
                    }
3568
                    proceed(true);
3569
                    PluginServices.getMDIManager().closeWindow(panel);
3570
                }
3571
            });
3572

    
3573
            PluginServices.getMDIManager().addWindow(panel);
3574
            if (proceed) {
3575
                return JOptionPane.YES_OPTION;
3576
            } else {
3577
                return JOptionPane.NO_OPTION;
3578
            }
3579
        }
3580

    
3581
        private void proceed(boolean proceed) {
3582
            this.proceed = proceed;
3583
        }
3584

    
3585
    }
3586

    
3587
    public static TerminationProcess getTerminationProcess() {
3588
        return (new Launcher()).new TerminationProcess();
3589
    }
3590

    
3591
    private PackageInfo getPackageInfo(String pluginsFolder) {
3592
        try {
3593
            PluginsManager pm = PluginsLocator.getManager();
3594
            return pm.getPackageInfo();
3595
        } catch (Exception e) {
3596
            logger.info("Can't locate PackageInfo from plugin org.gvsig.app", e);
3597
            return null;
3598
        }
3599
    }
3600

    
3601
    /**
3602
     * Launch the gvSIG package installer.
3603
     *
3604
     * @throws Exception if there is any error
3605
     */
3606
    private void doInstall(String[] args) throws Exception {
3607
        String installURL = null;
3608
        String installURLFile = null;
3609
        String gvSIGVersion = null;
3610
        String[] myArgs = new String[3];
3611
        PackageInfo packageInfo = null;
3612

    
3613
        Options options = new Options();
3614
        options.addOption("i", "install", false, "install");
3615
        options.addOption("u", "installURL", true, "installURL");
3616
        options.addOption("f", "installURLFile", true, "installURLFile");
3617
        options.addOption("v", "installVersion", true, "installVersion");
3618
        options.addOption("A", "applicationName", true, "application name, default is gvSIG");
3619
        options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3620
        options.addOption("l", "language", true, "language");
3621

    
3622
        // This options are managed by the gvSIG.sh but need to be declared here to avoid
3623
        // errors.
3624
        options.addOption(null, "debug", false, "Activate the JVM remote debug");
3625
        options.addOption(null, "pause", false, "Pause when activate JVM debug");
3626

    
3627
        /*
3628
         * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3629
         *
3630
         * --install
3631
         * --applicationName=gvSIG
3632
         * --language=es
3633
         * --pluginsFolder=gvSIG/extensiones
3634
         *
3635
         * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3636
         * --installVersion=2.0.0
3637
         * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3638
         * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3639
         *
3640
         */
3641
        CommandLineParser parser = new PosixParser();
3642
        CommandLine line = null;
3643
        try {
3644
            line = parser.parse(options, args);
3645
            boolean hasAllMandatoryOptions = true;
3646
            if (!line.hasOption("install")) {
3647
                hasAllMandatoryOptions = false;
3648
            }
3649

    
3650
            if (line.hasOption("installVersion")) {
3651
                gvSIGVersion = line.getOptionValue("installVersion");
3652
            }
3653
            if (line.hasOption("applicationName")) {
3654
                myArgs[0] = line.getOptionValue("applicationName");
3655
            } else {
3656
                myArgs[0] = "gvSIG";
3657
            }
3658
            if (line.hasOption("pluginsFolder")) {
3659
                myArgs[1] = line.getOptionValue("pluginsFolder");
3660
            } else {
3661
                myArgs[1] = "gvSIG/extensiones";
3662
            }
3663
            if (line.hasOption("language")) {
3664
                myArgs[2] = "language=" + line.getOptionValue("language");
3665
            } else {
3666
                // prevent null
3667
                myArgs[2] = Locale.getDefault().toString();
3668
            }
3669

    
3670
            if (line.hasOption("installURL")) {
3671
                installURL = line.getOptionValue("installURL");
3672
            } else {
3673
                installURL = "http://downloads.gvsig.org/download/gvsig-desktop-testing/";
3674
            }
3675

    
3676
            if (line.hasOption("installURLFile")) {
3677
                installURLFile = line.getOptionValue("installURLFile");
3678
            } else {
3679
                installURLFile = "gvsig-installer-urls.config";
3680
            }
3681

    
3682
            if (!hasAllMandatoryOptions) {
3683
                System.err.println(Messages.get("usage") + ": Launcher "
3684
                        + "--install "
3685
                        + "[--applicationName=appName] "
3686
                        + "[--pluginsFolder=plugins-directory] "
3687
                        + "[--installURLFile=File] "
3688
                        + "[--installURL=URL] "
3689
                        + "[--language=locale]"
3690
                );
3691
                return;
3692
            }
3693
        } catch (ParseException exp) {
3694
            System.err.println("Unexpected exception:" + exp.getMessage());
3695
            System.exit(-1);
3696
        }
3697

    
3698
        initializeApp(myArgs, "installer");
3699

    
3700
        new DefaultLibrariesInitializer().fullInitialize(true);
3701

    
3702
        initializeInstallerManager();
3703

    
3704
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
3705

    
3706
        try {
3707
            logger.info("Loading plugins configurations");
3708
            this.loadPluginConfigs();
3709
        } catch (Throwable ex) {
3710
            logger.warn("Can't load plugins configurations", ex);
3711
        }
3712

    
3713
        try {
3714
            logger.info("Loading plugins");
3715
            this.loadPluginServices();
3716
        } catch (Throwable ex) {
3717
            logger.warn("Can't load plugins", ex);
3718
        }
3719

    
3720
        AndamiConfig config = getAndamiConfig();
3721

    
3722
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3723

    
3724
        initializeLibraries();
3725

    
3726
        packageInfo = getPackageInfo(myArgs[1]);
3727

    
3728
        // set the gvSIG version to the install manager, to compose the download URL
3729
        if (packageInfo != null) {
3730
            installerManager.setVersion(packageInfo.getVersion());
3731
        } else {
3732
            installerManager.setVersion(gvSIGVersion);
3733
        }
3734
        if (!installURL.contains(";")
3735
                && !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION)
3736
                && !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION)) {
3737
            if (packageInfo != null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA)
3738
                    || packageInfo.getState().startsWith(InstallerManager.STATE.RC)
3739
                    || packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL))) {
3740
                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki ## Current build";
3741
            }
3742
        }
3743
        // Configure default index download URL
3744
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3745

    
3746
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3747

    
3748
        // Launch installer
3749
        PluginsManager manager = PluginsLocator.getManager();
3750

    
3751
        InstallWizardPanel installPackageWizard = SwingInstallerLocator
3752
                .getSwingInstallerManager().createInstallPackageWizard(
3753
                        manager.getApplicationFolder(),
3754
                        manager.getInstallFolder());
3755
        installPackageWizard.setWizardActionListener(new InstallerWizardActionListener() {
3756
            @Override
3757
            public void finish(InstallerWizardPanel installerWizard) {
3758
                logger.info("Finish installation.");
3759
                System.exit(0);
3760
            }
3761

    
3762
            @Override
3763
            public void cancel(InstallerWizardPanel installerWizard) {
3764
                logger.info("Cancel installation.");
3765
                System.exit(0);
3766
            }
3767
        });
3768

    
3769
        // the wizard will show the Typical or Advanced mode option.
3770
        installPackageWizard.setSkipTypicalOrAdvancedWizardPage(false);
3771
        // default packages will be selected.
3772
        installPackageWizard.setSelectDefaultPackages(true);
3773

    
3774
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3775
        frame.addWindowListener(new WindowAdapter() {
3776
            @Override
3777
            public void windowClosing(WindowEvent we) {
3778
                logger.info("Closing installation.");
3779
                System.exit(0);
3780
            }
3781

    
3782
            @Override
3783
            public void windowClosed(WindowEvent we) {
3784
                logger.info("Close installation.");
3785
                System.exit(0);
3786
            }
3787
        });
3788
        frame.getContentPane().add(installPackageWizard.asJComponent(), BorderLayout.CENTER);
3789
        URL iconURL = getClass().getResource("/images/main/install-icon.png");
3790
        if( iconURL!=null ) {
3791
            ImageIcon icon = new ImageIcon(iconURL);
3792
            frame.setIconImage(icon.getImage());
3793
        }
3794
        frame.pack();
3795
        frame.setLocationRelativeTo(null);
3796

    
3797
        frame.setVisible(true);
3798
    }
3799

    
3800
    public static String getInformation() {
3801
        return getInformation(null);
3802
    }
3803

    
3804
    private static final int INFO_OS_NAME = 0;
3805
    private static final int INFO_OS_ARCH = 1;
3806
    private static final int INFO_OS_VERSION = 2;
3807
    private static final int INFO_OS_ADITIONAL = 3;
3808
    private static final int INFO_JRE_VENDOR = 4;
3809
    private static final int INFO_JRE_VERSION = 5;
3810
    private static final int INFO_JRE_HOME = 6;
3811
    private static final int INFO_PROXY_HOST = 7;
3812
    private static final int INFO_PROXY_PORT = 8;
3813
    private static final int INFO_PROXY_USER = 9;
3814
    private static final int INFO_PROXY_PASSWORD = 10;
3815
    private static final int INFO_APP_LOCALE = 11;
3816
    private static final int INFO_APP_FOLDER = 12;
3817
    private static final int INFO_APP_HOME = 13;
3818
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3819
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3820
    private static final int INFO_APP_THEME = 16;
3821
    private static final int INFO_APP_SKIN = 17;
3822
    private static final int INFO_PACKAGES = 18;
3823
    private static final int INFO_TEMP_FOLDER = 19;
3824

    
3825
    public static String getInformation(PackageInfo[] pkgs) {
3826

    
3827
        String template = "OS\n"
3828
                + "    name    : {" + INFO_OS_NAME + "}\n"
3829
                + "    arch    : {" + INFO_OS_ARCH + "}\n"
3830
                + "    version : {" + INFO_OS_VERSION + "} \n"
3831
                + "{" + INFO_OS_ADITIONAL + "}"
3832
                + "JRE\n"
3833
                + "    vendor  : {" + INFO_JRE_VENDOR + "}\n"
3834
                + "    version : {" + INFO_JRE_VERSION + "}\n"
3835
                + "    home    : {" + INFO_JRE_HOME + "}\n"
3836
                + "HTTP Proxy\n"
3837
                + "    http.proxyHost     : {" + INFO_PROXY_HOST + "}\n"
3838
                + "    http.proxyPort     : {" + INFO_PROXY_PORT + "}\n"
3839
                + "    http.proxyUserName : {" + INFO_PROXY_USER + "}\n"
3840
                + "    http.proxyPassword : {" + INFO_PROXY_PASSWORD + "}\n"
3841
                + "Application\n"
3842
                + "    locale language         : {" + INFO_APP_LOCALE + "}\n"
3843
                + "    application forlder     : {" + INFO_APP_FOLDER + "}\n"
3844
                + "    application home forlder: {" + INFO_APP_HOME + "}\n"
3845
                + "    install forlder         : {" + INFO_APP_INSTALL_FOLDER + "}\n"
3846
                + "    plugins forlder         : {" + INFO_APP_PLUGINS_FOLDER + "}\n"
3847
                + "    theme                   : {" + INFO_APP_THEME + "}\n"
3848
                + "    Skin                    : {" + INFO_APP_SKIN + "}\n"
3849
                + "    temp forlder            : {" + INFO_TEMP_FOLDER + "}\n"
3850
                + "Installed packages\n"
3851
                + "{" + INFO_PACKAGES + "}";
3852

    
3853
        String values[] = new String[INFO_TEMP_FOLDER + 1];
3854

    
3855
        PluginsManager pluginmgr = PluginsLocator.getManager();
3856
        LocaleManager localemgr = PluginsLocator.getLocaleManager();
3857

    
3858
        Properties props = System.getProperties();
3859

    
3860
        // OS information
3861
        values[INFO_OS_NAME] = props.getProperty("os.name");
3862
        values[INFO_OS_ARCH] = props.getProperty("os.arch");
3863
        values[INFO_OS_VERSION] = props.getProperty("os.version");
3864

    
3865
        if (values[INFO_OS_NAME].startsWith("Linux")) {
3866
            try {
3867
                StringWriter writer = new StringWriter();
3868

    
3869
                String[] command = {"lsb_release", "-a"};
3870
                Process p = Runtime.getRuntime().exec(command);
3871
                InputStream is = p.getInputStream();
3872
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
3873
                String line;
3874
                while ((line = reader.readLine()) != null) {
3875
                    writer.write("    " + line + "\n");
3876
                }
3877
                values[INFO_OS_ADITIONAL] = writer.toString();
3878
            } catch (Exception ex) {
3879
                logger.warn("Can't get detailled os information (lsb_release -a).", ex);
3880
            }
3881
        }
3882

    
3883
        values[INFO_JRE_VENDOR] = props.getProperty("java.vendor");
3884
        values[INFO_JRE_VERSION] = props.getProperty("java.version");
3885
        values[INFO_JRE_HOME] = props.getProperty("java.home");
3886
        values[INFO_PROXY_HOST] = props.getProperty("http.proxyHost");
3887
        values[INFO_PROXY_PORT] = props.getProperty("http.proxyPort");
3888
        values[INFO_PROXY_USER] = props.getProperty("http.proxyUserName");
3889

    
3890
        if (props.get("http.proxyPassword") == null) {
3891
            values[INFO_PROXY_PASSWORD] = "(null)";
3892
        } else {
3893
            values[INFO_PROXY_PASSWORD] = "***********";
3894
        }
3895

    
3896
        try {
3897
            values[INFO_APP_SKIN] = MDIManagerFactory.getSkinExtension().getClassName();
3898
        } catch (Throwable e) {
3899
            values[INFO_APP_SKIN] = "(unknow)";
3900
        }
3901
        values[INFO_TEMP_FOLDER] = ToolsLocator.getFoldersManager().getTemporaryFolder().getAbsolutePath();
3902
        values[INFO_APP_LOCALE] = localemgr.getCurrentLocale().toString();
3903
        values[INFO_APP_FOLDER] = pluginmgr.getApplicationFolder().getAbsolutePath();
3904
        values[INFO_APP_HOME] = pluginmgr.getApplicationHomeFolder().getAbsolutePath();
3905
        values[INFO_APP_INSTALL_FOLDER] = pluginmgr.getInstallFolder().getAbsolutePath();
3906
        values[INFO_APP_PLUGINS_FOLDER] = StringUtils.join(pluginmgr.getPluginsFolders());
3907
        values[INFO_APP_THEME] = Launcher.theme.getSource().getAbsolutePath();
3908

    
3909
        try {
3910
            if (pkgs == null) {
3911
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3912
                pkgs = installmgr.getInstalledPackages();
3913
            }
3914
            StringWriter writer = new StringWriter();
3915
            for (PackageInfo pkg : pkgs) {
3916
                writer.write("    ");
3917
                writer.write(pkg.toStringCompact());
3918
                writer.write("\n");
3919
            }
3920
            values[INFO_PACKAGES] = writer.toString();
3921

    
3922
        } catch (Throwable e) {
3923
            logger.warn("Can't get installed package information.", e);
3924
        }
3925

    
3926
        String s = MessageFormat.format(template, (Object[])values);
3927
        return s;
3928
    }
3929

    
3930
    private void logger_info(String msg) {
3931
        String info[] = msg.split("\n");
3932
        for (String info1 : info) {
3933
            logger.info(info1);
3934
        }
3935
    }
3936

    
3937
    private void saveEnvironInformation(PackageInfo[] pkgs) {
3938
        PluginsManager manager = PluginsLocator.getManager();
3939
        File fout = new File(manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3940
        try {
3941
            FileUtils.write(fout, getInformation(pkgs));
3942
        } catch (IOException e) {
3943
            logger.info("Can't create '" + fout.getAbsolutePath() + "'");
3944
        }
3945
    }
3946

    
3947
    private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3948
        final Set<String> incompatiblePlugins = new HashSet<String>();
3949

    
3950
        // Add installed packages to a Map to optimize searchs
3951
        final Map<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
3952
        for (int i = 0; i < installedPackages.length; i++) {
3953
            packages.put(installedPackages[i].getCode(), installedPackages[i]);
3954
        }
3955
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
3956
        while (it.hasNext()) {
3957
            List<String> pluginNames = new ArrayList<String>();
3958
            Entry<String, PluginConfig> entry = it.next();
3959
            PluginConfig pluginConfig = entry.getValue();
3960
            pluginNames.add(entry.getKey());
3961

    
3962
                        // Locate the package for this plugin.
3963
            // Be care whith alias
3964
            String[] aliases = pluginsConfig.getAliases(pluginConfig);
3965
            if (aliases != null) {
3966
                for (int i = 0; i < aliases.length; i++) {
3967
                    pluginNames.add(aliases[i]);
3968
                }
3969
            }
3970
            PackageInfo pkg = null;
3971
            for (int n = 0; n < pluginNames.size(); n++) {
3972
                pkg = packages.get(pluginNames.get(n));
3973
                if (pkg != null) {
3974
                    break;
3975
                }
3976
            }
3977

    
3978
            // If package is found verify dependencies
3979
            if (pkg != null) {
3980
                Dependencies dependencies = pkg.getDependencies();
3981
                for (int i = 0; i < dependencies.size(); i++) {
3982
                    Dependency dependency = (Dependency) dependencies.get(i);
3983
                    if (Dependency.CONFLICT.equalsIgnoreCase(dependency.getType())) {
3984
                        String code = dependency.getCode();
3985
                        if (pluginsConfig.get(code) != null) {
3986
                            incompatiblePlugins.add(pkg.getCode());
3987
                            incompatiblePlugins.add(code);
3988
                        }
3989
                    }
3990
                }
3991
            }
3992
        }
3993
        if (incompatiblePlugins.isEmpty()) {
3994
            return;
3995
        }
3996
        splashWindow.toBack();
3997
        DisablePluginsConflictingDialog dlg = new DisablePluginsConflictingDialog(packages, incompatiblePlugins);
3998
        dlg.setVisible(true);
3999
        splashWindow.toFront();
4000
        switch (dlg.getAction()) {
4001
            case DisablePluginsConflictingDialog.CLOSE:
4002
                System.exit(0);
4003
                break;
4004
            case DisablePluginsConflictingDialog.CONTINUE:
4005
                break;
4006
        }
4007
        List<String> pluginsToDissable = dlg.getPluginNamesToDisable();
4008
        if (pluginsToDissable == null) {
4009
            return;
4010
        }
4011

    
4012
        Iterator<String> it2 = pluginsToDissable.iterator();
4013
        while (it2.hasNext()) {
4014
            String pluginName = it2.next();
4015
            logger.info("Dissabling plugin '" + pluginName + "' by user action.");
4016
            pluginsConfig.remove(pluginName);
4017
        }
4018
    }
4019

    
4020
    private class DisablePluginsConflictingDialog extends JDialog {
4021

    
4022
        public static final int CONTINUE = 0;
4023
        public static final int CLOSE = 1;
4024

    
4025
        private DisablePluginsConflictingLayoutPanel contents;
4026
        private int action = 0;
4027
        private List<Item> incompatiblePlugins = null;
4028
        private Map<String, PackageInfo> packages;
4029

    
4030
        private class Item {
4031

    
4032
            private String code;
4033
            private PackageInfo pkg;
4034

    
4035
            public Item(String code, PackageInfo pkg) {
4036
                this.code = code;
4037
                this.pkg = pkg;
4038
            }
4039

    
4040
            public String toString() {
4041
                if (this.pkg == null) {
4042
                    return code;
4043
                }
4044
                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
4045
            }
4046

    
4047
            public String getCode() {
4048
                if (pkg == null) {
4049
                    return code;
4050
                }
4051
                return pkg.getCode();
4052
            }
4053
        }
4054

    
4055
        DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
4056
            super((Frame) null, "", true);
4057
            this.setTitle(translate("_Conflicting_plugins"));
4058

    
4059
            this.packages = packages;
4060

    
4061
            this.incompatiblePlugins = new ArrayList<Item>();
4062
            Item item = null;
4063
            Iterator<String> it = incompatiblePlugins.iterator();
4064
            while (it.hasNext()) {
4065
                String code = it.next();
4066
                item = new Item(code, packages.get(code));
4067
                this.incompatiblePlugins.add(item);
4068
                logger.info("Found plugin '" + item.getCode() + "' incopatibles with each other.");
4069
            }
4070
            initComponents();
4071
        }
4072

    
4073
        private void initComponents() {
4074
            this.contents = new DisablePluginsConflictingLayoutPanel();
4075

    
4076
            doTranslations();
4077

    
4078
            this.contents.buttonClose.addActionListener(new ActionListener() {
4079
                public void actionPerformed(ActionEvent arg0) {
4080
                    doClose();
4081
                }
4082
            });
4083
            this.contents.buttonContinue.addActionListener(new ActionListener() {
4084
                public void actionPerformed(ActionEvent arg0) {
4085
                    doContinue();
4086
                }
4087
            });
4088
            this.contents.pluginList.setModel(new DefaultListModel(this.incompatiblePlugins));
4089
            ListSelectionModel sm = this.contents.pluginList.getSelectionModel();
4090
            sm.setSelectionMode(sm.MULTIPLE_INTERVAL_SELECTION);
4091
            this.setContentPane(this.contents);
4092
            this.pack();
4093

    
4094
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
4095
            setLocation((screenSize.width / 2) - (this.getWidth() / 2),
4096
                    (screenSize.height / 2) - (this.getHeight() / 2));
4097
        }
4098

    
4099
        private void doTranslations() {
4100
            DisablePluginsConflictingLayoutPanel c = this.contents;
4101
            c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
4102
            c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
4103
            c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
4104
            c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
4105
            c.buttonClose.setText(translate("_Close"));
4106
            c.buttonContinue.setText(translate("_Continue"));
4107
        }
4108

    
4109
        private String translate(String msg) {
4110
            return PluginServices.getText(this, msg);
4111
        }
4112

    
4113
        private void doClose() {
4114
            this.action = CLOSE;
4115
            this.setVisible(false);
4116
        }
4117

    
4118
        private void doContinue() {
4119
            this.action = CONTINUE;
4120
            this.setVisible(false);
4121
        }
4122

    
4123
        public int getAction() {
4124
            return this.action;
4125
        }
4126

    
4127
        public List<String> getPluginNamesToDisable() {
4128
            if (this.action == CLOSE) {
4129
                return null;
4130
            }
4131
            Object[] selecteds = null;
4132
            selecteds = (Object[]) this.contents.pluginList.getSelectedValues();
4133
            if (selecteds == null || selecteds.length < 1) {
4134
                return null;
4135
            }
4136
            List<String> values = new ArrayList<String>();
4137
            for (int i = 0; i < selecteds.length; i++) {
4138
                values.add(((Item) selecteds[i]).getCode());
4139
            }
4140
            return values;
4141
        }
4142
    }
4143

    
4144
    private void initializeIdentityManagement(File pluginsFolder) {
4145
        File identityManagementConfigFile = null;
4146
        PluginServices plugin = null;
4147
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
4148
        while (it.hasNext()) {
4149
            Entry<String, PluginConfig> entry = it.next();
4150
            File pluginFolder = entry.getValue().getPluginFolder();
4151
            File f = new File(pluginFolder, "identity-management.ini");
4152
            if (f.exists()) {
4153
                if (identityManagementConfigFile != null) {
4154
                    logger.warn("Too many identity-managemnt plugins. Disable all.");
4155
                } else {
4156
                    identityManagementConfigFile = f;
4157
                    plugin = PluginServices.getPluginServices(entry.getKey());
4158
                }
4159
            }
4160
        }
4161
        if(plugin != null){
4162
                new DefaultLibrariesInitializer(plugin.getClassLoader()).fullInitialize(true);
4163
        }
4164

    
4165
        if (identityManagementConfigFile == null || plugin == null) {
4166
            return;
4167
        }
4168
        if (!identityManagementConfigFile.canRead()) {
4169
            return;
4170
        }
4171
        PropertiesConfiguration identityManagementConfig = null;
4172
        try {
4173
            identityManagementConfig = new PropertiesConfiguration(identityManagementConfigFile);
4174
        } catch (Exception ex) {
4175
            logger.warn("Can't open identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.", ex);
4176
            return;
4177
        }
4178
        String identityManagerClassName = identityManagementConfig.getString("IdentityManager", null);
4179
        String identityManagementInitializerClassName = identityManagementConfig.getString("IdentityManagementInitializer", null);
4180
        try {
4181
            if (identityManagerClassName != null) {
4182
                Class identityManagerClass = plugin.getClassLoader().loadClass(identityManagerClassName);
4183
                ToolsLocator.registerIdentityManager(identityManagerClass);
4184
            } else {
4185
                logger.info("Entry IdentityManager not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4186
            }
4187

    
4188
            if (identityManagementInitializerClassName != null) {
4189
                Class identityManagerInitializerClass = plugin.getClassLoader().loadClass(identityManagementInitializerClassName);
4190
                Runnable identityManagerInitializer = (Runnable) identityManagerInitializerClass.newInstance();
4191
                identityManagerInitializer.run();
4192
            } else {
4193
                logger.info("Entry IdentityManagementInitializer not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4194
            }
4195

    
4196
        } catch (Exception ex) {
4197
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4198
            return;
4199
        }
4200
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4201
    }
4202
}