Statistics
| Revision:

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

History | View | Annotate | Download (164 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.andami;
24

    
25
import java.awt.BorderLayout;
26
import java.awt.Cursor;
27
import java.awt.Dimension;
28
import java.awt.EventQueue;
29
import java.awt.Frame;
30
import java.awt.KeyboardFocusManager;
31
import java.awt.Point;
32
import java.awt.Toolkit;
33
import java.awt.event.ActionEvent;
34
import java.awt.event.ActionListener;
35
import java.awt.event.WindowEvent;
36
import java.awt.event.WindowListener;
37
import java.io.BufferedOutputStream;
38
import java.io.BufferedReader;
39
import java.io.File;
40
import java.io.FileFilter;
41
import java.io.FileInputStream;
42
import java.io.FileNotFoundException;
43
import java.io.FileOutputStream;
44
import java.io.FileReader;
45
import java.io.IOException;
46
import java.io.InputStream;
47
import java.io.InputStreamReader;
48
import java.io.OutputStreamWriter;
49
import java.io.Reader;
50
import java.io.StringWriter;
51
import java.net.Authenticator;
52
import java.net.MalformedURLException;
53
import java.net.PasswordAuthentication;
54
import java.net.URL;
55
import java.net.URLClassLoader;
56
import java.nio.channels.FileChannel;
57
import java.security.AllPermission;
58
import java.security.CodeSource;
59
import java.security.PermissionCollection;
60
import java.security.Permissions;
61
import java.security.Policy;
62
import java.text.MessageFormat;
63
import java.util.ArrayList;
64
import java.util.Arrays;
65
import java.util.Collections;
66
import java.util.Comparator;
67
import java.util.Enumeration;
68
import java.util.HashMap;
69
import java.util.HashSet;
70
import java.util.Iterator;
71
import java.util.List;
72
import java.util.Locale;
73
import java.util.Map;
74
import java.util.Map.Entry;
75
import java.util.Properties;
76
import java.util.Set;
77
import java.util.TreeSet;
78
import java.util.logging.Level;
79
import java.util.prefs.Preferences;
80

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

    
92

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
300
            return item;
301
        }
302

    
303
    }
304

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

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

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

    
324
    }
325

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

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

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

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

    
354
    protected static ListBaseException launcherrors = null;
355

    
356
    protected static Theme theme = null;
357

    
358
    private List<String> deprecatedPluginNames = null;
359

    
360
    private static final class ProxyAuth extends Authenticator {
361

    
362
        private PasswordAuthentication auth;
363

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

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

    
373
    private static Launcher launcherInstance;
374

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

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

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

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

    
407
    public static class LaunchException extends ListBaseException {
408

    
409
        private static final long serialVersionUID = 4541192746962684705L;
410

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

    
417
    }
418

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

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

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

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

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

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

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

    
462
        initializeApp(args, null);
463

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
696
        splashWindow.close();
697

    
698
        frame.setCursor(Cursor.DEFAULT_CURSOR);
699

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

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

    
711
    }
712

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

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

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

    
742
    }
743

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

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

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

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

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

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

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

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

    
822
        configureLocales(args);
823

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

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

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

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

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

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

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

    
906
    private class NotificationAppender extends AppenderSkeleton {
907

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

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

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

    
932
        }
933

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

    
940
    }
941

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1198
        XMLEntity entity = new XMLEntity();
1199

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

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

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

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

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

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

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

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

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

    
1271
        Class<? extends IExtension> skinClass;
1272

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

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

    
1302
    }
1303

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

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

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

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

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

    
1365
    }
1366

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

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

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

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

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

    
1397
    private void initializeExtensions() {
1398

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1644
            Extensions extensionConfig = pluginConfig.getExtensions();
1645

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

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

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

    
1679
        }
1680
    }
1681

    
1682
    private TreeSet<SortableMenu> getOrderedMenus() {
1683

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1750
        }
1751

    
1752
        return orderedMenus;
1753
    }
1754

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

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

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

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

    
1778
    public class PluginMenuItem {
1779

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1880
            @Override
1881
            public int compare(ToolBar o1, ToolBar o2) {
1882
                return Integer.compare(o1.getPosition(), o2.getPosition());
1883
            }
1884
        });
1885
        return toolBarsList;        
1886
    }
1887
    
1888
    /**
1889
     * Installs the menus, toolbars, actiontools, selectable toolbars and
1890
     * combos. The order in which they are shown is determined here.
1891
     */
1892
    private void installPluginsControls() {
1893
        logger.info("installPluginsControls (toolbars)");
1894

    
1895
        Iterator<String> pluginNames = pluginsConfig.keySet().iterator();
1896

    
1897
        Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1898
        Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1899
        Set<Extension> orderedExtensions = new TreeSet<Extension>(
1900
                new ExtensionComparator());
1901

    
1902
                // First of all, sort the extensions.
1903
        // We need to iterate on the plugins, and iterate on each plugin's
1904
        // extensions
1905
        // (each plugin may contain one or more extensions)
1906
        while (pluginNames.hasNext()) { // iterate on the plugins
1907
            String pluginName = pluginNames.next();
1908
            try {
1909
                PluginConfig pc = pluginsConfig.get(pluginName);
1910
                PluginServices ps = pluginsServices.get(pluginName);
1911

    
1912
                Extension[] exts = pc.getExtensions().getExtension();
1913

    
1914
                for (int j = 0; j < exts.length; j++) { // iterate on the
1915
                    // extensions
1916
                    String cname = "unknow";
1917
                    try {
1918
                        cname = exts[j].getClassName();
1919
                        if (exts[j].getActive()
1920
                                && !cname.equals(LibraryExtension.class
1921
                                        .getName())) {
1922
                            if (orderedExtensions.contains(exts[j])) {
1923
                                this
1924
                                        .addError(Messages
1925
                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1926
                                                + cname);
1927
                            }
1928

    
1929
                            orderedExtensions.add(exts[j]);
1930
                            extensionPluginServices.put(exts[j], ps);
1931
                            extensionPluginConfig.put(exts[j], pc);
1932
                        }
1933
                    } catch (Throwable e) {
1934
                        addError("Error initializing controls of plugin '"
1935
                                + pluginName + "' extension '" + cname + "'", e);
1936
                    }
1937
                }
1938
            } catch (Throwable e) {
1939
                addError("Error initializing controls of plugin '" + pluginName
1940
                        + "'", e);
1941
            }
1942
        }
1943

    
1944
        
1945
        // A?ade primero las toolbars ordenadas para garantizar el orden de estas
1946
        for( ToolBar toolbar : getOrderedToolBars() ) {
1947
            frame.addToolBar(toolbar.getName(), toolbar.getDescription(), toolbar.getPosition());
1948
        }
1949

    
1950
        TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1951
                new ToolComparator());
1952
        Iterator<Extension> e = orderedExtensions.iterator();
1953

    
1954
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1955
        // selectabletools)
1956
        // and load the combo-scales and combo-buttons for the status bar
1957
        while (e.hasNext()) {
1958
            Extension ext = e.next();
1959
            String extName = "unknow";
1960
            try {
1961
                extName = ext.getClassName();
1962
                ToolBar[] toolbars = ext.getToolBar();
1963

    
1964
                // get tools from toolbars
1965
                for (int k = 0; k < toolbars.length; k++) {
1966
                    ActionTool[] tools = toolbars[k].getActionTool();
1967

    
1968
                    for (int t = 0; t < tools.length; t++) {
1969
                        SortableTool sm = new SortableTool(
1970
                                (extensionPluginServices.get(ext))
1971
                                .getClassLoader(), ext, toolbars[k],
1972
                                tools[t]);
1973
                        orderedTools.add(sm);
1974
                    }
1975

    
1976
                    SelectableTool[] sTools = toolbars[k].getSelectableTool();
1977

    
1978
                    for (int t = 0; t < sTools.length; t++) {
1979
                        SortableTool sm = new SortableTool(
1980
                                (extensionPluginServices.get(ext))
1981
                                .getClassLoader(), ext, toolbars[k],
1982
                                sTools[t]);
1983
                        orderedTools.add(sm);
1984
                    }
1985
                }
1986

    
1987
                // get controls for statusBar
1988
                PluginServices ps = extensionPluginServices.get(ext);
1989
                PluginClassLoader loader = ps.getClassLoader();
1990

    
1991
                // ArrayList componentList = new ArrayList();
1992
                ComboScale[] comboScaleArray = ext.getComboScale();
1993
                for (int k = 0; k < comboScaleArray.length; k++) {
1994
                    org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1995
                    String label = comboScaleArray[k].getLabel();
1996
                    if (label != null) {
1997
                        combo.setLabel(label);
1998
                    }
1999
                    String name = comboScaleArray[k].getName();
2000
                    if (name != null) {
2001
                        combo.setName(name);
2002
                    }
2003
                    String[] elementsString = ((String) comboScaleArray[k]
2004
                            .getElements()).split(";");
2005
                    long[] elements = new long[elementsString.length];
2006
                    for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
2007
                        try {
2008
                            elements[currentElem] = Long
2009
                                    .parseLong(elementsString[currentElem]);
2010
                        } catch (NumberFormatException nfex1) {
2011
                            this
2012
                                    .addError(ext.getClassName()
2013
                                            + " -- "
2014
                                            + Messages
2015
                                            .getString("error_parsing_comboscale_elements"));
2016
                            elements[currentElem] = 0;
2017
                        }
2018
                    }
2019
                    combo.setItems(elements);
2020
                    try {
2021
                        long value = Long.parseLong((String) comboScaleArray[k]
2022
                                .getValue());
2023
                        combo.setScale(value);
2024
                    } catch (NumberFormatException nfex2) {
2025
                        this
2026
                                .addError(ext.getClassName()
2027
                                        + " -- "
2028
                                        + Messages
2029
                                        .getString("error_parsing_comboscale_value"));
2030
                    }
2031
                    try {
2032
                        frame.addStatusBarControl(loader.loadClass(ext
2033
                                .getClassName()), combo);
2034
                    } catch (ClassNotFoundException e1) {
2035
                        this
2036
                                .addError(
2037
                                        Messages
2038
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2039
                                        e1);
2040
                    }
2041
                }
2042

    
2043
                ComboButton[] comboButtonArray = ext.getComboButton();
2044
                for (int k = 0; k < comboButtonArray.length; k++) {
2045
                    ComboButtonElement[] elementList = comboButtonArray[k]
2046
                            .getComboButtonElement();
2047
                    org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
2048
                    String name = comboButtonArray[k].getName();
2049
                    if (name != null) {
2050
                        combo.setName(name);
2051
                    }
2052
                    for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
2053
                        ComboButtonElement element = elementList[currentElement];
2054
                        ImageIcon icon;
2055
                        URL iconLocation = loader
2056
                                .getResource(element.getIcon());
2057
                        if (iconLocation == null) {
2058
                            this.addError(Messages.getString("Icon_not_found_")
2059
                                    + element.getIcon());
2060
                        } else {
2061
                            icon = new ImageIcon(iconLocation);
2062
                            JButton button = new JButton(icon);
2063
                            combo.addButton(button);
2064
                            button.setActionCommand(element.getActionCommand());
2065
                        }
2066
                    }
2067
                    try {
2068
                        frame.addStatusBarControl(loader.loadClass(ext
2069
                                .getClassName()), combo);
2070
                    } catch (ClassNotFoundException e1) {
2071
                        this
2072
                                .addError(
2073
                                        Messages
2074
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2075
                                        e1);
2076
                    }
2077
                }
2078
            } catch (Throwable e2) {
2079
                addError(
2080
                        "Error initializing tools and status bars of extension '"
2081
                        + extName + "'", e2);
2082
            }
2083
        }
2084

    
2085
                // Add the tools from MDI extensions to the ordered tool-list, so that
2086
        // we get a sorted list containing all the tools
2087
        pluginNames = pluginsConfig.keySet().iterator();
2088
        while (pluginNames.hasNext()) {
2089
            String pName = (String) pluginNames.next();
2090
            try {
2091
                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
2092
                PluginServices ps = (PluginServices) pluginsServices.get(pName);
2093

    
2094
                SkinExtension[] skinExts = pc.getExtensions()
2095
                        .getSkinExtension();
2096
                for (int j = 0; j < skinExts.length; j++) {
2097

    
2098
                    if (skinExts[j] != null) {
2099
                        ToolBar[] toolbars = skinExts[j].getToolBar();
2100

    
2101
                        for (int k = 0; k < toolbars.length; k++) {
2102
                            ActionTool[] tools = toolbars[k].getActionTool();
2103

    
2104
                            for (int t = 0; t < tools.length; t++) {
2105
                                SortableTool stb = new SortableTool(ps
2106
                                        .getClassLoader(), skinExts[j],
2107
                                        toolbars[k], tools[t]);
2108
                                orderedTools.add(stb);
2109
                            }
2110

    
2111
                            SelectableTool[] sTools = toolbars[k]
2112
                                    .getSelectableTool();
2113

    
2114
                            for (int t = 0; t < sTools.length; t++) {
2115
                                SortableTool stb = new SortableTool(ps
2116
                                        .getClassLoader(), skinExts[j],
2117
                                        toolbars[k], sTools[t]);
2118
                                orderedTools.add(stb);
2119
                            }
2120
                        }
2121
                    }
2122
                }
2123
                // Install popup menus
2124
                PopupMenus pus = pc.getPopupMenus();
2125
                if (pus != null) {
2126
                    PopupMenu[] menus = pus.getPopupMenu();
2127
                    for (int j = 0; j < menus.length; j++) {
2128
                        String menuName = "(unknow)";
2129
                        try {
2130
                            menuName = menus[j].getName();
2131
                            frame.addPopupMenu(ps.getClassLoader(), menus[j]);
2132
                        } catch (Throwable ex) {
2133
                            addError("Error adding popup menu' " + menuName + "' in plugin '" + pName + "'.");
2134
                        }
2135
                    }
2136
                }
2137
            } catch (Throwable e3) {
2138
                addError("Error initializing skins of the plugin '" + pName
2139
                        + "'", e3);
2140
            }
2141
        }
2142

    
2143
                // loop on the ordered extension list, to add them to the interface in
2144
        // an ordered way
2145
        Iterator<SortableTool> t = orderedTools.iterator();
2146
        while (t.hasNext()) {
2147
            SortableTool stb = t.next();
2148
            try {
2149
                if (stb.actiontool != null) {
2150
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2151
                            stb.actiontool);
2152
                } else {
2153
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2154
                            stb.selectabletool);
2155
                }
2156
            } catch (ClassNotFoundException ex) {
2157
                this
2158
                        .addError(
2159
                                Messages
2160
                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
2161
                                ex);
2162
            } catch (Throwable e2) {
2163
                addError("Error adding tools to the interface of extension '"
2164
                        + stb.extension.getClassName() + "'", e2);
2165
            }
2166
        }
2167
    }
2168

    
2169
    /**
2170
     * Adds new plugins to the the andami-config file.
2171
     */
2172
    private void updateAndamiConfig() {
2173
        Set<String> olds = new HashSet<String>();
2174

    
2175
        Plugin[] plugins = andamiConfig.getPlugin();
2176

    
2177
        for (int i = 0; i < plugins.length; i++) {
2178
            olds.add(plugins[i].getName());
2179
        }
2180

    
2181
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2182

    
2183
        while (i.hasNext()) {
2184
            PluginServices ps = i.next();
2185

    
2186
            if (!olds.contains(ps.getPluginName())) {
2187
                Plugin p = new Plugin();
2188
                p.setName(ps.getPluginName());
2189
                p.setUpdate(false);
2190

    
2191
                andamiConfig.addPlugin(p);
2192
            }
2193
        }
2194
    }
2195

    
2196
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2197
        URL[] urls = null;
2198

    
2199
        String libfolderPath = pluginConfig.getLibraries().getLibraryDir();
2200
        File libFolderFile = new File(pluginConfig.getPluginFolder(), libfolderPath);
2201

    
2202
        File[] files = libFolderFile.listFiles(new FileFilter() {
2203

    
2204
            public boolean accept(File pathname) {
2205
                return (pathname.getName().toUpperCase().endsWith(".JAR")
2206
                        || pathname.getName().toUpperCase().endsWith(".ZIP"));
2207
            }
2208
        });
2209
        if (files == null) {
2210
            urls = new URL[0];
2211
        } else {
2212
            urls = new URL[files.length];
2213
            for (int j = 0; j < files.length; j++) {
2214
                try {
2215
                    urls[j] = new URL("file:" + files[j]);
2216
                } catch (MalformedURLException e) {
2217
                    logger.warn("Can't add file '" + files[j] + "' to the classpath of plugin '" + pluginConfig.getPluginName() + "'.");
2218
                }
2219
            }
2220
        }
2221
        return urls;
2222
    }
2223

    
2224
    private static class OrderedPlugins extends ArrayList<String> {
2225
        
2226
        private List<String> problems = new ArrayList<String>();
2227
        private int retries = 0;
2228
        private PluginsConfig pluginsConfig = null;
2229
        private List<String> deprcatedPluginNames = null;
2230
        
2231
        OrderedPlugins(PluginsConfig pluginsConfig, List<String>deprcatedPluginNames) {
2232
            super();
2233
            this.pluginsConfig = pluginsConfig;
2234
            this.deprcatedPluginNames = deprcatedPluginNames;
2235
            List<String> pluginNames = new ArrayList<String>();
2236
            for (String pluginName : pluginsConfig.keySet()) {
2237
                pluginNames.add(pluginName);
2238
            }
2239
            Collections.sort(pluginNames);
2240
            for (String pluginName : pluginNames) {
2241
                this.add(pluginName);
2242
            }
2243
        }
2244
        
2245
        public List<String> getProblems() {
2246
            return this.problems;
2247
        }
2248
 
2249
        private void addProblem(String msg) {
2250
           this.problems.add(msg);
2251
        }
2252
    
2253
        public boolean add(String pluginName) {
2254
            return this.add(pluginName,new ArrayList<String>());
2255
        }
2256
        
2257
        private boolean add(String pluginName, List<String>processing) {
2258
            pluginName = this.pluginsConfig.getMainKey(pluginName);
2259
            if( this.contains(pluginName) ) {
2260
                return true;
2261
            }
2262
            if( processing.contains(pluginName) ) {
2263
                this.addProblem("Dependencias ciclicas procesando '"+pluginName+"'.");
2264
                return true;
2265
            }
2266
            PluginConfig pluginConfig = this.pluginsConfig.get(pluginName);
2267
            Depends[] dependencies = pluginConfig.getDepends();
2268
            if( dependencies.length==0 ) {
2269
               super.add(pluginName);
2270
               return true;
2271
            }
2272
            if( this.retries > 100 ) {
2273
               this.addProblem("Posible dependencias ciclicas procesando '"+pluginName+"'." );
2274
               return false;
2275
            }
2276
            processing.add(pluginName);
2277
            boolean dependenciesAvailables = true;
2278
            for (Depends dependency : dependencies) {
2279
                String dependencyName = dependency.getPluginName();
2280
                if (deprcatedPluginNames.contains(dependencyName)) {
2281
                    this.addProblem("Plugin '" + pluginName + "' use a deprecated plugin name '" + dependencyName + "' as dependency. Must use '" + pluginsConfig.getMainKey(dependencyName) + "'.");
2282
                }                
2283
                PluginConfig dependencyConfig = this.pluginsConfig.get(dependencyName);
2284
                if( dependencyConfig == null) {
2285
                  if( dependency.getOptional() ) {
2286
                    this.addProblem("Plugin '" + pluginName + "', declare an optional dependency '" + dependencyName + "' that not found.");
2287
                    continue;
2288
                  }
2289
                  dependenciesAvailables = false;
2290
                  this.addProblem("Plugin '"+pluginName+"' declara a dependency '"+dependencyName+"' that not found.");
2291
                  continue;
2292
                }
2293
                this.retries++;
2294
                if( ! (this.add(dependencyName, processing)) ) {
2295
                  dependenciesAvailables = false;
2296
                }
2297
                this.retries--;
2298
            }
2299
            if( dependenciesAvailables ) {
2300
                super.add(pluginName);
2301
            } else {
2302
              this.addProblem("Plugin '"+pluginName+"' no disponible, alguna dependencia no resuelta.");
2303
              return false;
2304
            }
2305
            return true;
2306
        }      
2307
    }
2308
            
2309
    private void loadPluginServices() {
2310
        OrderedPlugins orderedPlugins = new OrderedPlugins(pluginsConfig, getDeprecatedPluginNames());
2311
        
2312
        if( !orderedPlugins.getProblems().isEmpty() ) {
2313
            for (String problem : orderedPlugins.getProblems()) {
2314
                logger.warn(problem);
2315
            }
2316
        }
2317

    
2318
        for (String pluginName : orderedPlugins) {
2319
            PluginConfig config = pluginsConfig.get(pluginName);
2320

    
2321
            URL[] urls = getPluginClasspathURLs(config);
2322
            
2323
            List<PluginClassLoader> loaders = new ArrayList<PluginClassLoader>();
2324
            for (Depends dependency : config.getDepends()) {
2325
                String dependencyName = dependency.getPluginName();
2326
                PluginServices dependencyPluginService = pluginsServices.get(dependencyName);
2327
                if( dependencyPluginService == null ) {
2328
                    if( dependency.getOptional() ) {
2329
                        logger.info("Procesing plugin '"+pluginName+", optional dependency not found ("+dependencyName+").");
2330
                    } else {
2331
                        logger.warn("Procesing plugin '"+pluginName+", dependency not found ("+dependencyName+").");
2332
                    }
2333
                    continue;
2334
                }
2335
                loaders.add(dependencyPluginService.getClassLoader());
2336
            }
2337
            try {
2338
                PluginClassLoader loader = new PluginClassLoader(
2339
                        urls,
2340
                        config.getPluginFolder().getAbsolutePath(),
2341
                        Launcher.class.getClassLoader(),
2342
                        loaders
2343
                );
2344
                PluginServices ps = new PluginServices(
2345
                        loader,
2346
                        PluginsConfig.getAlternativeNames(config)
2347
                );
2348
                logger.info("Plugin '" + pluginName + "' created");
2349
                pluginsServices.put(ps.getPluginName(), ps);
2350
                pluginsOrdered.add(pluginName);
2351
            } catch (IOException ex) {
2352
                logger.warn("Can't create PluginServices for '" + pluginName + "'.", ex);
2353
            }
2354
        }
2355
        
2356
        // Se eliminan los plugins que no fueron instalados
2357
        List<String> pluginsToRemove = new ArrayList<String>();
2358
        for (String pluginName : pluginsConfig.keySet()) {
2359
            PluginServices pluginService = pluginsServices.get(pluginName);
2360
            if( pluginService == null ) {
2361
                pluginsToRemove.add(pluginName);
2362
            } 
2363
        }
2364
        for (String pluginName : pluginsToRemove) {
2365
            logger.warn("Removed plugin "+pluginName+".");
2366
            pluginsConfig.remove(pluginName);
2367
       }
2368
    }
2369
 
2370
    /*
2371
    private void dumpPluginsDependencyInformation() {
2372
        logger.info("Plugin dependency information");
2373
        Iterator<String> i = pluginsConfig.keySet().iterator();
2374
        while (i.hasNext()) {
2375
            String pluginName = i.next();
2376
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2377
            logger.info("  Plugin " + pluginName);
2378
            Depends[] dependencies = config.getDepends();
2379
            for (int j = 0; j < dependencies.length; j++) {
2380
                Depends dependency = dependencies[j];
2381
                String dependencyName = dependency.getPluginName();
2382
                logger.info("    Dependency " + dependencyName);
2383
            }
2384
        }
2385
    }
2386
    */
2387
    private void pluginsMessages() {
2388
        Iterator<String> iterator = pluginsOrdered.iterator();
2389
        PluginConfig config;
2390
        PluginServices ps;
2391

    
2392
        while (iterator.hasNext()) {
2393
            String pluginName = iterator.next();
2394
            config = pluginsConfig.get(pluginName);
2395
            ps = pluginsServices.get(pluginName);
2396

    
2397
            if ((config.getResourceBundle() != null)
2398
                    && !config.getResourceBundle().getName().equals("")) {
2399
                // add the locale files associated with the plugin
2400
                org.gvsig.i18n.Messages.addResourceFamily(config
2401
                        .getResourceBundle().getName(), ps.getClassLoader(),
2402
                        pluginName);
2403
                org.gvsig.i18n.Messages.addResourceFamily("i18n." + config
2404
                        .getResourceBundle().getName(), ps.getClassLoader(),
2405
                        pluginName);
2406
            }
2407
        }
2408
    }
2409

    
2410
    static public PluginServices getPluginServices(String name) {
2411
        return (PluginServices) pluginsServices.get(name);
2412
    }
2413

    
2414
    static String getPluginsDir() {
2415
        return andamiConfig.getPluginsDirectory();
2416
    }
2417

    
2418
    static File getPluginFolder(String pluginName) {
2419
        return pluginsConfig.get(pluginName).getPluginFolder();
2420
    }
2421

    
2422
    static void setPluginsDir(String s) {
2423
        andamiConfig.setPluginsDirectory(s);
2424
    }
2425

    
2426
    static MDIFrame getMDIFrame() {
2427
        return frame;
2428
    }
2429

    
2430
    private PluginsConfig loadPluginConfigs() {
2431
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
2432
        List<File> repositoriesFolders = installerManager.getLocalAddonRepositories("plugin");
2433
        for (File repositoryFolder : repositoriesFolders) {
2434
            logger.info("Loading plugins configuration from repository folder " + repositoryFolder.getAbsolutePath() + ".");
2435

    
2436
            if (!repositoryFolder.exists()) {
2437
                logger.warn("Plugins repository folder not found '" + repositoryFolder.getAbsolutePath() + "'.");
2438
                continue;
2439
            }
2440

    
2441
            File[] pluginsFolders = repositoryFolder.listFiles();
2442
            if (pluginsFolders.length == 0) {
2443
                logger.info("Plugins repository folder is empty '" + repositoryFolder.getAbsolutePath() + "'.");
2444
                continue;
2445
            }
2446

    
2447
            for (int i = 0; i < pluginsFolders.length; i++) {
2448
                File pluginFolder = pluginsFolders[i];
2449
                if (!pluginFolder.isDirectory()) {
2450
                    continue;
2451
                }
2452
                String pluginName = pluginFolder.getName();
2453
                File pluginConfigFile = new File(pluginFolder, "config.xml");
2454
                if (!pluginConfigFile.exists()) {
2455
                    logger.info("Plugin '" + pluginName + "' not has a config.xml file (" + pluginConfigFile.getAbsolutePath() + ".");
2456
                    continue;
2457
                }
2458
                try {
2459
                    FileInputStream is = new FileInputStream(pluginConfigFile);
2460
                    Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2461
                    if (xml == null) {
2462
                        // the encoding was not correctly detected, use system default
2463
                        xml = new FileReader(pluginConfigFile);
2464
                    } else {
2465
                        // use a buffered reader to improve performance
2466
                        xml = new BufferedReader(xml);
2467
                    }
2468
                    PluginConfig pluginConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2469
                    pluginConfig.setPluginName(pluginName);
2470
                    pluginConfig.setPluginFolder(pluginFolder);
2471
                    pluginsConfig.put(pluginName, pluginConfig);
2472

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

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

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

    
2482
                }
2483
            }
2484
        }
2485
        return pluginsConfig;
2486
    }
2487

    
2488
    private static Locale getLocale(String language, String country,
2489
            String variant) {
2490
        if (variant != null) {
2491
            return new Locale(language, country, variant);
2492
        } else if (country != null) {
2493
            return new Locale(language, country);
2494
        } else if (language != null) {
2495
            return new Locale(language);
2496
        } else {
2497
            return new Locale("es");
2498
        }
2499
    }
2500

    
2501
    private static void andamiConfigToXML(String file) throws IOException,
2502
            MarshalException, ValidationException {
2503
                // write on a temporary file in order to not destroy current file if
2504
        // there is some problem while marshaling
2505
        File tmpFile = new File(file + "-"
2506
                + DateTime.getCurrentDate().getTime());
2507
        File xml = new File(file);
2508
        File parent = xml.getParentFile();
2509
        parent.mkdirs();
2510

    
2511
        BufferedOutputStream os = new BufferedOutputStream(
2512
                new FileOutputStream(tmpFile));
2513
        OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2514
        andamiConfig.marshal(writer);
2515
        writer.close();
2516

    
2517
                // if marshaling process finished correctly, move the file to the
2518
        // correct one
2519
        xml.delete();
2520
        if (!tmpFile.renameTo(xml)) {
2521
            // if rename was not succesful, try copying it
2522
            FileChannel sourceChannel = new FileInputStream(tmpFile)
2523
                    .getChannel();
2524
            FileChannel destinationChannel = new FileOutputStream(xml)
2525
                    .getChannel();
2526
            sourceChannel.transferTo(0, sourceChannel.size(),
2527
                    destinationChannel);
2528
            sourceChannel.close();
2529
            destinationChannel.close();
2530
        }
2531
    }
2532

    
2533
    private static void andamiConfigFromXML(String file)
2534
            throws ConfigurationException {
2535
        File xml = new File(file);
2536

    
2537
        InputStreamReader reader = null;
2538
        try {
2539
            // Se lee la configuraci?n
2540
            reader = XMLEncodingUtils.getReader(xml);
2541
            andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2542
        } catch (FileNotFoundException e) {
2543
            // Si no existe se ponen los valores por defecto
2544
            andamiConfig = getDefaultAndamiConfig();
2545
        } catch (MarshalException e) {
2546
            // try to close the stream, maybe it remains open
2547
            if (reader != null) {
2548
                try {
2549
                    reader.close();
2550
                } catch (IOException e1) {
2551
                }
2552
            }
2553
                        // if there was a problem reading the file, backup it and create a
2554
            // new one with default values
2555
            String backupFile = file + "-"
2556
                    + DateTime.getCurrentDate().getTime();
2557
            NotificationManager
2558
                    .addError(
2559
                            Messages
2560
                            .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2561
                            + backupFile, new ConfigurationException(e));
2562
            xml.renameTo(new File(backupFile));
2563
            andamiConfig = getDefaultAndamiConfig();
2564
        } catch (ValidationException e) {
2565
            throw new ConfigurationException(e);
2566
        }
2567
    }
2568

    
2569
    private static AndamiConfig getDefaultAndamiConfig() {
2570
        AndamiConfig andamiConfig = new AndamiConfig();
2571

    
2572
        Andami andami = new Andami();
2573
        andami.setUpdate(true);
2574
        andamiConfig.setAndami(andami);
2575
        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2576
        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2577
        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2578

    
2579
        if (System.getProperty("javawebstart.version") != null) // Es java web
2580
        // start)
2581
        {
2582
            andamiConfig
2583
                    .setPluginsDirectory(new File(appHomeDir, "extensiones")
2584
                            .getAbsolutePath());
2585
        } else {
2586
            andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2587
                    .getAbsolutePath());
2588
        }
2589

    
2590
        andamiConfig.setPlugin(new Plugin[0]);
2591
        return andamiConfig;
2592
    }
2593

    
2594
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
2595
        File xml = getPluginsPersistenceFile(true);
2596

    
2597
        if (xml.exists()) {
2598
            InputStreamReader reader = null;
2599

    
2600
            try {
2601
                reader = XMLEncodingUtils.getReader(xml);
2602
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2603
                return new XMLEntity(tag);
2604
            } catch (FileNotFoundException e) {
2605
                throw new ConfigurationException(e);
2606
            } catch (MarshalException e) {
2607

    
2608
                                // try to reopen with default encoding (for backward
2609
                // compatibility)
2610
                try {
2611
                    reader = new FileReader(xml);
2612
                    XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2613
                    return new XMLEntity(tag);
2614

    
2615
                } catch (MarshalException ex) {
2616
                    // try to close the stream, maybe it remains open
2617
                    if (reader != null) {
2618
                        try {
2619
                            reader.close();
2620
                        } catch (IOException e1) {
2621
                        }
2622
                    }
2623
                    // backup the old file
2624
                    String backupFile = getPluginsPersistenceFile(true)
2625
                            .getPath()
2626
                            + "-" + DateTime.getCurrentDate().getTime();
2627
                    NotificationManager
2628
                            .addError(
2629
                                    Messages
2630
                                    .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2631
                                    + backupFile,
2632
                                    new ConfigurationException(e));
2633
                    xml.renameTo(new File(backupFile));
2634
                    // create a new, empty configuration
2635
                    return new XMLEntity();
2636
                } catch (FileNotFoundException ex) {
2637
                    return new XMLEntity();
2638
                } catch (ValidationException ex) {
2639
                    throw new ConfigurationException(e);
2640
                }
2641
            } catch (ValidationException e) {
2642
                throw new ConfigurationException(e);
2643
            }
2644
        } else {
2645
            return new XMLEntity();
2646
        }
2647
    }
2648

    
2649
    private static File getPluginsPersistenceFile(boolean read) {
2650
        if (read) {
2651
            File pluginsPersistenceFile = new File(getAppHomeDir(),
2652
                    "plugins-persistence-2_0.xml");
2653
            if (pluginsPersistenceFile.exists()) {
2654
                return pluginsPersistenceFile;
2655
            }
2656
            pluginsPersistenceFile = new File(getAppHomeDir(),
2657
                    "plugins-persistence.xml");
2658
            if (pluginsPersistenceFile.exists()) {
2659
                return pluginsPersistenceFile;
2660
            }
2661
        }
2662
        return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2663

    
2664
    }
2665

    
2666
    private static void persistenceToXML(XMLEntity entity)
2667
            throws ConfigurationException {
2668
                // write on a temporary file in order to not destroy current file if
2669
        // there is some problem while marshaling
2670
        File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2671
                + "-" + DateTime.getCurrentDate().getTime());
2672

    
2673
        File xml = getPluginsPersistenceFile(false);
2674
        OutputStreamWriter writer = null;
2675

    
2676
        try {
2677
            writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2678
                    CASTORENCODING);
2679
            entity.getXmlTag().marshal(writer);
2680
            writer.close();
2681

    
2682
                        // if marshaling process finished correctly, move the file to the
2683
            // correct one
2684
            xml.delete();
2685
            if (!tmpFile.renameTo(xml)) {
2686
                // if rename was not succesful, try copying it
2687
                FileChannel sourceChannel = new FileInputStream(tmpFile)
2688
                        .getChannel();
2689
                FileChannel destinationChannel = new FileOutputStream(xml)
2690
                        .getChannel();
2691
                sourceChannel.transferTo(0, sourceChannel.size(),
2692
                        destinationChannel);
2693
                sourceChannel.close();
2694
                destinationChannel.close();
2695

    
2696
            }
2697
        } catch (FileNotFoundException e) {
2698
            throw new ConfigurationException(e);
2699
        } catch (MarshalException e) {
2700
            // try to close the stream, maybe it remains open
2701
            if (writer != null) {
2702
                try {
2703
                    writer.close();
2704
                } catch (IOException e1) {
2705
                }
2706
            }
2707
        } catch (ValidationException e) {
2708
            throw new ConfigurationException(e);
2709
        } catch (IOException e) {
2710
            throw new ConfigurationException(e);
2711
        }
2712
    }
2713

    
2714
    static MDIFrame getFrame() {
2715
        return frame;
2716
    }
2717

    
2718
    /**
2719
     * Gracefully closes the application. It shows dialogs to save data, finish
2720
     * processes, etc, then it terminates the extensions, removes temporal files
2721
     * and finally exits.
2722
     */
2723
    public synchronized static void closeApplication() {
2724
        TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2725
        terminationProcess.run();
2726
    }
2727

    
2728
    static HashMap getClassesExtensions() {
2729
        return classesExtensions;
2730
    }
2731

    
2732
    private static Extensions[] getExtensions() {
2733
        List<Extensions> array = new ArrayList<Extensions>();
2734
        Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2735

    
2736
        while (iter.hasNext()) {
2737
            array.add(iter.next().getExtensions());
2738
        }
2739

    
2740
        return array.toArray(new Extensions[array.size()]);
2741
    }
2742

    
2743
    public static Iterator getExtensionIterator() {
2744
        return extensions.iterator();
2745
    }
2746

    
2747
    public static HashMap getPluginConfig() {
2748
        return pluginsConfig;
2749
    }
2750

    
2751
    public static Extension getExtension(String s) {
2752
        Extensions[] exts = getExtensions();
2753

    
2754
        for (int i = 0; i < exts.length; i++) {
2755
            for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2756
                if (exts[i].getExtension(j).getClassName().equals(s)) {
2757
                    return exts[i].getExtension(j);
2758
                }
2759
            }
2760
        }
2761

    
2762
        return null;
2763
    }
2764

    
2765
    public static AndamiConfig getAndamiConfig() {
2766
        return andamiConfig;
2767
    }
2768

    
2769
    private static class ExtensionComparator implements Comparator {
2770

    
2771
        public int compare(Object o1, Object o2) {
2772
            Extension e1 = (Extension) o1;
2773
            Extension e2 = (Extension) o2;
2774

    
2775
            if (!e1.hasPriority() && !e2.hasPriority()) {
2776
                return -1;
2777
            }
2778

    
2779
            if (e1.hasPriority() && !e2.hasPriority()) {
2780
                return Integer.MIN_VALUE;
2781
            }
2782

    
2783
            if (e2.hasPriority() && !e1.hasPriority()) {
2784
                return Integer.MAX_VALUE;
2785
            }
2786

    
2787
            if (e1.getPriority() != e2.getPriority()) {
2788
                return e2.getPriority() - e1.getPriority();
2789
            } else {
2790
                return (e2.toString().compareTo(e1.toString()));
2791
            }
2792
        }
2793
    }
2794

    
2795
    private static class MenuComparator implements Comparator<SortableMenu> {
2796

    
2797
        private static ExtensionComparator extComp = new ExtensionComparator();
2798

    
2799
        public int compare(SortableMenu e1, SortableMenu e2) {
2800

    
2801
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2802
                if (e1.extension instanceof SkinExtensionType) {
2803
                    return 1;
2804
                } else if (e2.extension instanceof SkinExtensionType) {
2805
                    return -1;
2806
                } else {
2807
                    return extComp.compare(e1.extension, e2.extension);
2808
                }
2809
            }
2810

    
2811
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2812
                return Integer.MIN_VALUE;
2813
            }
2814

    
2815
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2816
                return Integer.MAX_VALUE;
2817
            }
2818

    
2819
            if (e1.menu.getPosition() == e2.menu.getPosition()) {
2820
                                // we don't return 0 unless both objects are the same, otherwise
2821
                // the objects get overwritten in the treemap
2822
                return (e1.toString().compareTo(e2.toString()));
2823
            }
2824
            if (e1.menu.getPosition() > e2.menu.getPosition()) {
2825
                return Integer.MAX_VALUE;
2826
            }
2827
            return Integer.MIN_VALUE;
2828

    
2829
        }
2830
    }
2831

    
2832
    private static class SortableMenu {
2833

    
2834
        public PluginClassLoader loader;
2835
        public Menu menu;
2836
        public SkinExtensionType extension;
2837

    
2838
        public SortableMenu(PluginClassLoader loader,
2839
                SkinExtensionType skinExt, Menu menu2) {
2840
            extension = skinExt;
2841
            menu = menu2;
2842
            this.loader = loader;
2843
        }
2844

    
2845
    }
2846

    
2847
    private static class SortableTool {
2848

    
2849
        public PluginClassLoader loader;
2850
        public ToolBar toolbar;
2851
        public ActionTool actiontool;
2852
        public SelectableTool selectabletool;
2853
        public SkinExtensionType extension;
2854

    
2855
        public SortableTool(PluginClassLoader loader,
2856
                SkinExtensionType skinExt, ToolBar toolbar2,
2857
                ActionTool actiontool2) {
2858
            extension = skinExt;
2859
            toolbar = toolbar2;
2860
            actiontool = actiontool2;
2861
            this.loader = loader;
2862
        }
2863

    
2864
        public SortableTool(PluginClassLoader loader,
2865
                SkinExtensionType skinExt, ToolBar toolbar2,
2866
                SelectableTool selectabletool2) {
2867
            extension = skinExt;
2868
            toolbar = toolbar2;
2869
            selectabletool = selectabletool2;
2870
            this.loader = loader;
2871
        }
2872
    }
2873

    
2874
    private static class ToolBarComparator implements Comparator<SortableTool> {
2875

    
2876
        private static ExtensionComparator extComp = new ExtensionComparator();
2877

    
2878
        public int compare(SortableTool e1, SortableTool e2) {
2879

    
2880
                        // if the toolbars have the same name, they are considered to be
2881
            // the same toolbar, so we don't need to do further comparing
2882
            if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2883
                return 0;
2884
            }
2885

    
2886
            if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2887
                if (e1.extension instanceof SkinExtensionType) {
2888
                    return 1;
2889
                } else if (e2.extension instanceof SkinExtensionType) {
2890
                    return -1;
2891
                } else {
2892
                    return extComp.compare(e1.extension, e2.extension);
2893
                }
2894
            }
2895

    
2896
            if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2897
                return Integer.MIN_VALUE;
2898
            }
2899

    
2900
            if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2901
                return Integer.MAX_VALUE;
2902
            }
2903
            if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2904
                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2905
            }
2906

    
2907
            if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2908
                    && e1.toolbar.getSelectableTool().equals(
2909
                            e2.toolbar.getSelectableTool())) {
2910
                return 0;
2911
            }
2912
            return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2913
        }
2914
    }
2915

    
2916
    /**
2917
     * <p>
2918
     * This class is used to compare tools (selectabletool and actiontool),
2919
     * using the "position" attribute.
2920
     * </p>
2921
     * <p>
2922
     * The ordering criteria are:
2923
     * </p>
2924
     * <ul>
2925
     * <li>If the tools are placed in different toolbars, they use the toolbars'
2926
     * order. (using the ToolBarComparator).</li>
2927
     * <li></li>
2928
     * <li>If any of the tools has not 'position' attribute, the tool which
2929
     * <strong>has</strong> the attribute will be placed first.</li>
2930
     * <li>If both tools have the same position (or they don't have a 'position'
2931
     * attribute), the priority of the extensions where the tool is
2932
     * defined.</li>
2933
     * </ul>
2934
     *
2935
     * @author cesar
2936
     * @version $Revision: 40305 $
2937
     */
2938
    private static class ToolComparator implements Comparator<SortableTool> {
2939

    
2940
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2941

    
2942
        public int compare(SortableTool e1, SortableTool e2) {
2943
            // compare the toolbars which contain the tools
2944
            long result = toolBarComp.compare(e1, e2);
2945
            if (result != 0) { // if the toolbars are different, use their order
2946
                return result > 0 ? 1 : -1;
2947
            }
2948
            // otherwise, compare the tools
2949
            long e1Position = -1, e2Position = -1;
2950

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

    
2961
            if (e2.actiontool != null) {
2962
                if (e2.actiontool.hasPosition()) {
2963
                    e2Position = e2.actiontool.getPosition();
2964
                }
2965
            } else if (e2.selectabletool != null) {
2966
                if (e2.selectabletool.hasPosition()) {
2967
                    e2Position = e2.selectabletool.getPosition();
2968
                }
2969
            }
2970

    
2971
            if ((e1Position == -1) && (e2Position != -1)) {
2972
                return 1;
2973
            }
2974
            if ((e1Position != -1) && (e2Position == -1)) {
2975
                return -1;
2976
            }
2977
            if ((e1Position != -1) && (e2Position != -1)) {
2978
                result = e1Position - e2Position;
2979
                                // we don't return 0 unless both objects are the same, otherwise
2980
                // the objects get overwritten in the treemap
2981
                if (result != 0) {
2982
                    return result > 0 ? 1 : -1;
2983
                }
2984
            }
2985
            return e1.toString().compareTo(e2.toString());
2986
        }
2987
    }
2988

    
2989
    public static String getDefaultLookAndFeel() {
2990
        String osName = (String) System.getProperty("os.name");
2991

    
2992
        if ((osName.length() > 4)
2993
                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2994
            return nonWinDefaultLookAndFeel;
2995
        }
2996
        if (osName.toLowerCase().startsWith("mac os x")) {
2997
            return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2998
        }
2999

    
3000
        return UIManager.getSystemLookAndFeelClassName();
3001
    }
3002

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

    
3035
                    while ((line = reader.readLine()) != null) {
3036
                        String[] language = line.split("\t");
3037
                        if (language[0].equals(langCode)) {
3038
                                                        // the three
3039
                            // characters code
3040
                            return language[2]; // third column i the two
3041
                            // characters code
3042
                        }
3043
                    }
3044
                } catch (IOException ex) {
3045
                    logger.error(Messages
3046
                            .getString("Error_reading_isocodes_file"), ex);
3047
                    return "es";
3048
                }
3049
            } else {
3050
                logger.error(Messages.getString("Error_reading_isocodes_file"));
3051
                return "es";
3052
            }
3053
        }
3054
        return "es";
3055
    }
3056

    
3057
    /**
3058
     * Configures the locales (languages and local resources) to be used by the
3059
     * application.
3060
     *
3061
     * First it tries to get the locale from the command line parameters, then
3062
     * the andami-config file is checked.
3063
     *
3064
     * The locale name is normalized to get a two characters language code as
3065
     * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
3066
     * also accepted from the command line or the configuration file).
3067
     *
3068
     * Finally, the gvsig-i18n library and the default locales for Java and
3069
     * Swing are configured.
3070
     *
3071
     */
3072
    private static void configureLocales(String[] args) {
3073
        // Configurar el locale
3074
        String localeStr = null;
3075

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

    
3118
        URL[] i18nURLs = getURLsFromI18nFolders(userI18nFolder, appI18nFolder);
3119
        ClassLoader i18nClassLoader = URLClassLoader.newInstance(i18nURLs, null);
3120
        logger.info("loading resources from classloader " + i18nClassLoader.toString() + ".");
3121
        org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
3122
                "Andami Launcher");
3123

    
3124
        // Finally load the andami own i18n resources
3125
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
3126
                "Andami Launcher");
3127
    }
3128

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

    
3167
    /**
3168
     * Gets Home Directory location of the application into users home folder.
3169
     *
3170
     * May be set from outside the aplication by means of
3171
     * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
3172
     *
3173
     * @return
3174
     */
3175
    public static String getAppHomeDir() {
3176
        return appHomeDir;
3177
    }
3178

    
3179
    public static File getApplicationHomeFolder() {
3180
        return new File(getAppHomeDir());
3181
    }
3182

    
3183
    /**
3184
     * Sets Home Directory location of the application. May be set from outside
3185
     * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3186
     * the name of the application
3187
     *
3188
     * @param appHomeDir
3189
     */
3190
    public static void setAppHomeDir(String appHomeDir) {
3191
        Launcher.appHomeDir = appHomeDir;
3192
    }
3193

    
3194
    /**
3195
     * Initialize the extesion that have to take the control of the state of
3196
     * action controls of the UI of all extensions. <br>
3197
     * <br>
3198
     * For use this option you have to add an argument to the command line like
3199
     * this: <br>
3200
     * <br>
3201
     * -exclusiveUI={pathToExtensionClass} <br>
3202
     *
3203
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3204
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3205
     */
3206
    private static void initializeExclusiveUIExtension() {
3207
        String name = PluginServices.getArgumentByName("exclusiveUI");
3208
        if (name == null) {
3209
            return;
3210
        }
3211

    
3212
        Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3213
                .iterator();
3214
        int charIndex;
3215
        Class<? extends IExtension> key;
3216
        while (iter.hasNext()) {
3217
            key = iter.next();
3218
            charIndex = key.getName().indexOf(name);
3219
            // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3220
            if (charIndex == 0) {
3221
                IExtension ext = classesExtensions.get(key);
3222
                if (ext instanceof ExtensionDecorator) {
3223
                    ext = ((ExtensionDecorator) ext).getExtension();
3224
                }
3225
                if (ext instanceof ExclusiveUIExtension) {
3226
                    PluginServices
3227
                            .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3228
                }
3229
                break;
3230
            }
3231
        }
3232

    
3233
        logger
3234
                .error(Messages
3235
                        .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3236
                        + " '" + name + "'");
3237
    }
3238

    
3239
    public static void initIconThemes() {
3240
        PluginsManager pluginsManager = PluginsLocator.getManager();
3241
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3242

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

    
3253
        f = new File(pluginsManager.getApplicationFolder(), "icon-theme");
3254
        if (!f.exists()) {
3255
            try {
3256
                f.mkdir();
3257
            } catch (Exception ex) {
3258
                // Do nothing
3259
            }
3260
        }
3261
        iconManager.getRepository().add(f, "_Global");
3262

    
3263
        Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3264
        String defaultThemeID = prefs.get("default-theme", null);
3265
        if (defaultThemeID != null) {
3266
            IconTheme iconTheme = iconManager.get(defaultThemeID);
3267
            if (iconTheme != null) {
3268
                iconManager.setCurrent(iconTheme);
3269
            }
3270
        }
3271
    }
3272

    
3273
    public static void manageUnsavedData(String prompt) throws Exception {
3274
        final UnsavedDataPanel panel = new UnsavedDataPanel(prompt);
3275
        final List<IUnsavedData> unsavedData = PluginsLocator.getManager().getUnsavedData();
3276
        panel.setUnsavedData(unsavedData);
3277

    
3278
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3279

    
3280
            public void cancel(UnsavedDataPanel panel) {
3281
                panel.setVisible(false);
3282
            }
3283

    
3284
            public void discard(UnsavedDataPanel panel) {
3285
                panel.setVisible(false);
3286
            }
3287

    
3288
            public void accept(UnsavedDataPanel panel) {
3289
                panel.setVisible(false);
3290

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

    
3309
        //TODO: mostrar panel WindowManager
3310
        ToolsSwingLocator.getWindowManager().showWindow(
3311
                panel,
3312
                PluginServices.getText(panel, "Resource_was_not_saved"),
3313
                MODE.DIALOG);
3314

    
3315
    }
3316

    
3317
    /**
3318
     * Manages Andami termination process
3319
     *
3320
     * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3321
     */
3322
    public class TerminationProcess {
3323

    
3324
        private boolean proceed = false;
3325
        private UnsavedDataPanel panel = null;
3326

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

    
3343
        /**
3344
         * Finishes the application without asking user if want or not to save
3345
         * unsaved data.
3346
         */
3347
        public void closeAndami() {
3348
            PluginsManager pluginsManager = PluginsLocator.getManager();
3349
            pluginsManager.executeShutdownTasks();
3350

    
3351
            try {
3352
                saveAndamiConfig();
3353
            } catch (Exception ex) {
3354
                logger.error(
3355
                        "There was an error exiting application, can't save andami-config.xml",
3356
                        ex
3357
                );
3358
            }
3359

    
3360
            try {
3361
                // Persistencia de los plugins
3362
                savePluginPersistence();
3363
                savePluginsProperties();
3364
            } catch (Exception ex) {
3365
                logger.error(
3366
                        "There was an error exiting application, can't save plugins properties",
3367
                        ex
3368
                );
3369
            }
3370

    
3371
            // Finalize all the extensions
3372
            finalizeExtensions();
3373

    
3374
            try {
3375
                // Clean any temp data created
3376
                Utilities.cleanUpTempFiles();
3377
            } catch (Exception ex) {
3378
                logger.error(
3379
                        "There was an error exiting application, can't remove temporary files",
3380
                        ex
3381
                );
3382
            }
3383

    
3384
            logger.info("Quiting application.");
3385

    
3386
            // Para la depuraci?n de memory leaks
3387
            System.gc();
3388

    
3389
            System.exit(0);
3390
        }
3391

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

    
3417
        private void savePluginsProperties() {
3418
            PluginsManager manager = PluginsLocator.getManager();
3419
            List<PluginServices> plugins = manager.getPlugins();
3420
            for (PluginServices plugin : plugins) {
3421
                if (plugin != null) {
3422
                    plugin.savePluginProperties();
3423
                }
3424
            }
3425
        }
3426

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

    
3448
        private IUnsavedData[] getUnsavedData() throws Exception {
3449
            List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3450
            IExtension exclusiveExtension = PluginServices
3451
                    .getExclusiveUIExtension();
3452

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

    
3490
        public UnsavedDataPanel getUnsavedDataPanel() {
3491
            if (panel == null) {
3492
                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3493
            }
3494
            return panel;
3495
        }
3496

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

    
3507
            // there was no unsaved data
3508
            if (unsavedData.length == 0) {
3509
                int option = JOptionPane
3510
                        .showConfirmDialog(frame, Messages
3511
                                .getString("MDIFrame.quiere_salir"), Messages
3512
                                .getString("MDIFrame.salir"),
3513
                                JOptionPane.YES_NO_OPTION);
3514
                return option;
3515
            }
3516

    
3517
            UnsavedDataPanel panel = getUnsavedDataPanel();
3518
            panel.setUnsavedDataArray(unsavedData);
3519

    
3520
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3521

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

    
3526
                }
3527

    
3528
                public void discard(UnsavedDataPanel panel) {
3529
                    proceed(true);
3530
                    PluginServices.getMDIManager().closeWindow(panel);
3531

    
3532
                }
3533

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

    
3565
                            try {
3566
                                unsavedDataArray = getUnsavedData();
3567
                            } catch (Exception e) {
3568
                                // This exception has been registered before
3569
                            }
3570
                            panel.setUnsavedDataArray(unsavedDataArray);
3571
                            return;
3572
                        }
3573
                    }
3574
                    proceed(true);
3575
                    PluginServices.getMDIManager().closeWindow(panel);
3576
                }
3577
            });
3578

    
3579
            PluginServices.getMDIManager().addWindow(panel);
3580
            if (proceed) {
3581
                return JOptionPane.YES_OPTION;
3582
            } else {
3583
                return JOptionPane.NO_OPTION;
3584
            }
3585
        }
3586

    
3587
        private void proceed(boolean proceed) {
3588
            this.proceed = proceed;
3589
        }
3590

    
3591
    }
3592

    
3593
    public static TerminationProcess getTerminationProcess() {
3594
        return (new Launcher()).new TerminationProcess();
3595
    }
3596

    
3597
    private PackageInfo getPackageInfo(String pluginsFolder) {
3598
        try {
3599
            PluginsManager pm = PluginsLocator.getManager();
3600
            return pm.getPackageInfo();
3601
        } catch (Exception e) {
3602
            logger.info("Can't locate PackageInfo from plugin org.gvsig.app", e);
3603
            return null;
3604
        }
3605
    }
3606

    
3607
    /**
3608
     * Launch the gvSIG package installer.
3609
     *
3610
     * @throws Exception if there is any error
3611
     */
3612
    private void doInstall(String[] args) throws Exception {
3613
        String installURL = null;
3614
        String installURLFile = null;
3615
        String gvSIGVersion = null;
3616
        String[] myArgs = new String[3];
3617
        PackageInfo packageInfo = null;
3618

    
3619
        Options options = new Options();
3620
        options.addOption("i", "install", false, "install");
3621
        options.addOption("u", "installURL", true, "installURL");
3622
        options.addOption("f", "installURLFile", true, "installURLFile");
3623
        options.addOption("v", "installVersion", true, "installVersion");
3624
        options.addOption("A", "applicationName", true, "application name, default is gvSIG");
3625
        options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3626
        options.addOption("l", "language", true, "language");
3627

    
3628
        // This options are managed by the gvSIG.sh but need to be declared here to avoid
3629
        // errors.
3630
        options.addOption(null, "debug", false, "Activate the JVM remote debug");
3631
        options.addOption(null, "pause", false, "Pause when activate JVM debug");
3632

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

    
3656
            if (line.hasOption("installVersion")) {
3657
                gvSIGVersion = line.getOptionValue("installVersion");
3658
            }
3659
            if (line.hasOption("applicationName")) {
3660
                myArgs[0] = line.getOptionValue("applicationName");
3661
            } else {
3662
                myArgs[0] = "gvSIG";
3663
            }
3664
            if (line.hasOption("pluginsFolder")) {
3665
                myArgs[1] = line.getOptionValue("pluginsFolder");
3666
            } else {
3667
                myArgs[1] = "gvSIG/extensiones";
3668
            }
3669
            if (line.hasOption("language")) {
3670
                myArgs[2] = "language=" + line.getOptionValue("language");
3671
            } else {
3672
                // prevent null
3673
                myArgs[2] = Locale.getDefault().toString();
3674
            }
3675

    
3676
            if (line.hasOption("installURL")) {
3677
                installURL = line.getOptionValue("installURL");
3678
            } else {
3679
                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3680
            }
3681

    
3682
            if (line.hasOption("installURLFile")) {
3683
                installURLFile = line.getOptionValue("installURLFile");
3684
            } else {
3685
                installURLFile = "gvsig-installer-urls.config";
3686
            }
3687

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

    
3704
        initializeApp(myArgs, "installer");
3705

    
3706
        new DefaultLibrariesInitializer().fullInitialize(true);
3707

    
3708
        initializeInstallerManager();
3709

    
3710
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
3711
        
3712
//        try {
3713
//            logger.info("Loading plugins configurations");
3714
//            this.loadPluginConfigs();
3715
//        } catch (Throwable ex) {
3716
//            logger.warn("Can't load plugins configurations", ex);
3717
//        }
3718
//
3719
//        try {
3720
//            logger.info("Loading plugins");
3721
//            this.loadPluginServices();
3722
//        } catch (Throwable ex) {
3723
//            logger.warn("Can't load plugins", ex);
3724
//        }
3725

    
3726
        AndamiConfig config = getAndamiConfig();
3727

    
3728
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3729

    
3730
        initializeLibraries();
3731

    
3732
        packageInfo = getPackageInfo(myArgs[1]);
3733

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

    
3752
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3753

    
3754
        // Launch installer
3755
        PluginsManager manager = PluginsLocator.getManager();
3756

    
3757
        AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3758
                .getSwingInstallerManager().createInstallPackageWizard(
3759
                        manager.getApplicationFolder(),
3760
                        manager.getInstallFolder());
3761
        installPackageWizard.setWizardActionListener(new InstallerWizardActionListener() {
3762
            public void finish(InstallerWizardPanel installerWizard) {
3763
                logger.info("Finish installation.");
3764
                System.exit(0);
3765
            }
3766

    
3767
            public void cancel(InstallerWizardPanel installerWizard) {
3768
                logger.info("Cancel installation.");
3769
                System.exit(0);
3770
            }
3771
        });
3772

    
3773
        // the wizard will show the Typical or Advanced mode option.
3774
        installPackageWizard.setAskTypicalOrCustom(true);
3775
        // default packages will be selected.
3776
        installPackageWizard.setSelectDefaultPackages(true);
3777

    
3778
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3779

    
3780
        frame.addWindowListener(new WindowListener() {
3781
            public void windowOpened(WindowEvent we) {
3782
                logger.info("Open window installation.");
3783
            }
3784

    
3785
            public void windowClosing(WindowEvent we) {
3786
                logger.info("Closing installation.");
3787
                System.exit(0);
3788
            }
3789

    
3790
            public void windowClosed(WindowEvent we) {
3791
                logger.info("Close installation.");
3792
                System.exit(0);
3793
            }
3794

    
3795
            public void windowIconified(WindowEvent we) {
3796
            }
3797

    
3798
            public void windowDeiconified(WindowEvent we) {
3799
            }
3800

    
3801
            public void windowActivated(WindowEvent we) {
3802
                logger.info("Activate window installation.");
3803
            }
3804

    
3805
            public void windowDeactivated(WindowEvent we) {
3806
                logger.info("Deactivate window installation.");
3807
            }
3808
        });
3809
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3810

    
3811
        frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3812

    
3813
        URL iconURL = getClass().getResource("/images/main/install-icon.png");
3814
        if( iconURL!=null ) {
3815
            ImageIcon icon = new ImageIcon(iconURL);
3816
            frame.setIconImage(icon.getImage());
3817
        }
3818
        frame.pack();
3819
        frame.setLocationRelativeTo(null);
3820

    
3821
        frame.setVisible(true);
3822
    }
3823

    
3824
    public static String getInformation() {
3825
        return getInformation(null);
3826
    }
3827

    
3828
    private static final int INFO_OS_NAME = 0;
3829
    private static final int INFO_OS_ARCH = 1;
3830
    private static final int INFO_OS_VERSION = 2;
3831
    private static final int INFO_OS_ADITIONAL = 3;
3832
    private static final int INFO_JRE_VENDOR = 4;
3833
    private static final int INFO_JRE_VERSION = 5;
3834
    private static final int INFO_JRE_HOME = 6;
3835
    private static final int INFO_PROXY_HOST = 7;
3836
    private static final int INFO_PROXY_PORT = 8;
3837
    private static final int INFO_PROXY_USER = 9;
3838
    private static final int INFO_PROXY_PASSWORD = 10;
3839
    private static final int INFO_APP_LOCALE = 11;
3840
    private static final int INFO_APP_FOLDER = 12;
3841
    private static final int INFO_APP_HOME = 13;
3842
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3843
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3844
    private static final int INFO_APP_THEME = 16;
3845
    private static final int INFO_APP_SKIN = 17;
3846
    private static final int INFO_PACKAGES = 18;
3847

    
3848
    public static String getInformation(PackageInfo[] pkgs) {
3849

    
3850
        String template = "OS\n"
3851
                + "    name    : {" + INFO_OS_NAME + "}\n"
3852
                + "    arch    : {" + INFO_OS_ARCH + "}\n"
3853
                + "    version : {" + INFO_OS_VERSION + "} \n"
3854
                + "{" + INFO_OS_ADITIONAL + "}"
3855
                + "JRE\n"
3856
                + "    vendor  : {" + INFO_JRE_VENDOR + "}\n"
3857
                + "    version : {" + INFO_JRE_VERSION + "}\n"
3858
                + "    home    : {" + INFO_JRE_HOME + "}\n"
3859
                + "HTTP Proxy\n"
3860
                + "    http.proxyHost     : {" + INFO_PROXY_HOST + "}\n"
3861
                + "    http.proxyPort     : {" + INFO_PROXY_PORT + "}\n"
3862
                + "    http.proxyUserName : {" + INFO_PROXY_USER + "}\n"
3863
                + "    http.proxyPassword : {" + INFO_PROXY_PASSWORD + "}\n"
3864
                + "Application\n"
3865
                + "    locale language         : {" + INFO_APP_LOCALE + "}\n"
3866
                + "    application forlder     : {" + INFO_APP_FOLDER + "}\n"
3867
                + "    application home forlder: {" + INFO_APP_HOME + "}\n"
3868
                + "    install forlder         : {" + INFO_APP_INSTALL_FOLDER + "}\n"
3869
                + "    plugins forlder         : {" + INFO_APP_PLUGINS_FOLDER + "}\n"
3870
                + "    theme                   : {" + INFO_APP_THEME + "}\n"
3871
                + "    Skin                    : {" + INFO_APP_SKIN + "}\n"
3872
                + "Installed packages\n"
3873
                + "{" + INFO_PACKAGES + "}";
3874

    
3875
        String values[] = new String[INFO_PACKAGES + 1];
3876

    
3877
        PluginsManager pluginmgr = PluginsLocator.getManager();
3878
        LocaleManager localemgr = PluginsLocator.getLocaleManager();
3879

    
3880
        Properties props = System.getProperties();
3881

    
3882
        // OS information
3883
        values[INFO_OS_NAME] = props.getProperty("os.name");
3884
        values[INFO_OS_ARCH] = props.getProperty("os.arch");
3885
        values[INFO_OS_VERSION] = props.getProperty("os.version");
3886

    
3887
        if (values[INFO_OS_NAME].startsWith("Linux")) {
3888
            try {
3889
                StringWriter writer = new StringWriter();
3890

    
3891
                String[] command = {"lsb_release", "-a"};
3892
                Process p = Runtime.getRuntime().exec(command);
3893
                InputStream is = p.getInputStream();
3894
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
3895
                String line;
3896
                while ((line = reader.readLine()) != null) {
3897
                    writer.write("    " + line + "\n");
3898
                }
3899
                values[INFO_OS_ADITIONAL] = writer.toString();
3900
            } catch (Exception ex) {
3901
                logger.warn("Can't get detailled os information (lsb_release -a).", ex);
3902
            }
3903
        }
3904

    
3905
        values[INFO_JRE_VENDOR] = props.getProperty("java.vendor");
3906
        values[INFO_JRE_VERSION] = props.getProperty("java.version");
3907
        values[INFO_JRE_HOME] = props.getProperty("java.home");
3908
        values[INFO_PROXY_HOST] = props.getProperty("http.proxyHost");
3909
        values[INFO_PROXY_PORT] = props.getProperty("http.proxyPort");
3910
        values[INFO_PROXY_USER] = props.getProperty("http.proxyUserName");
3911

    
3912
        if (props.get("http.proxyPassword") == null) {
3913
            values[INFO_PROXY_PASSWORD] = "(null)";
3914
        } else {
3915
            values[INFO_PROXY_PASSWORD] = "***********";
3916
        }
3917

    
3918
        try {
3919
            values[INFO_APP_SKIN] = MDIManagerFactory.getSkinExtension().getClassName();
3920
        } catch (Throwable e) {
3921
            values[INFO_APP_SKIN] = "(unknow)";
3922
        }
3923
        values[INFO_APP_LOCALE] = localemgr.getCurrentLocale().toString();
3924
        values[INFO_APP_FOLDER] = pluginmgr.getApplicationFolder().getAbsolutePath();
3925
        values[INFO_APP_HOME] = pluginmgr.getApplicationHomeFolder().getAbsolutePath();
3926
        values[INFO_APP_INSTALL_FOLDER] = pluginmgr.getInstallFolder().getAbsolutePath();
3927
        values[INFO_APP_PLUGINS_FOLDER] = StringUtils.join(pluginmgr.getPluginsFolders());
3928
        values[INFO_APP_THEME] = Launcher.theme.getSource().getAbsolutePath();
3929

    
3930
        try {
3931
            if (pkgs == null) {
3932
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3933
                pkgs = installmgr.getInstalledPackages();
3934
            }
3935
            StringWriter writer = new StringWriter();
3936
            for (int i = 0; i < pkgs.length; i++) {
3937
                writer.write("    ");
3938
                writer.write(pkgs[i].toStringCompact());
3939
                writer.write("\n");
3940
            }
3941
            values[INFO_PACKAGES] = writer.toString();
3942

    
3943
        } catch (Throwable e) {
3944
            logger.warn("Can't get installed package information.", e);
3945
        }
3946

    
3947
        String s = MessageFormat.format(template, values);
3948
        return s;
3949
    }
3950

    
3951
    private void logger_info(String msg) {
3952
        String info[] = msg.split("\n");
3953
        for (int i = 0; i < info.length; i++) {
3954
            logger.info(info[i]);
3955
        }
3956
    }
3957

    
3958
    private void saveEnvironInformation(PackageInfo[] pkgs) {
3959
        PluginsManager manager = PluginsLocator.getManager();
3960
        File fout = new File(manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3961
        try {
3962
            FileUtils.write(fout, getInformation(pkgs));
3963
        } catch (IOException e) {
3964
            logger.info("Can't create '" + fout.getAbsolutePath() + "'");
3965
        }
3966
    }
3967

    
3968
    private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3969
        final Set<String> incompatiblePlugins = new HashSet<String>();
3970

    
3971
        // Add installed packages to a Map to optimize searchs
3972
        final Map<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
3973
        for (int i = 0; i < installedPackages.length; i++) {
3974
            packages.put(installedPackages[i].getCode(), installedPackages[i]);
3975
        }
3976
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
3977
        while (it.hasNext()) {
3978
            List<String> pluginNames = new ArrayList<String>();
3979
            Entry<String, PluginConfig> entry = it.next();
3980
            PluginConfig pluginConfig = entry.getValue();
3981
            pluginNames.add(entry.getKey());
3982

    
3983
                        // Locate the package for this plugin.
3984
            // Be care whith alias
3985
            String[] aliases = pluginsConfig.getAliases(pluginConfig);
3986
            if (aliases != null) {
3987
                for (int i = 0; i < aliases.length; i++) {
3988
                    pluginNames.add(aliases[i]);
3989
                }
3990
            }
3991
            PackageInfo pkg = null;
3992
            for (int n = 0; n < pluginNames.size(); n++) {
3993
                pkg = packages.get(pluginNames.get(n));
3994
                if (pkg != null) {
3995
                    break;
3996
                }
3997
            }
3998

    
3999
            // If package is found verify dependencies
4000
            if (pkg != null) {
4001
                Dependencies dependencies = pkg.getDependencies();
4002
                for (int i = 0; i < dependencies.size(); i++) {
4003
                    Dependency dependency = (Dependency) dependencies.get(i);
4004
                    if (Dependency.CONFLICT.equalsIgnoreCase(dependency.getType())) {
4005
                        String code = dependency.getCode();
4006
                        if (pluginsConfig.get(code) != null) {
4007
                            incompatiblePlugins.add(pkg.getCode());
4008
                            incompatiblePlugins.add(code);
4009
                        }
4010
                    }
4011
                }
4012
            }
4013
        }
4014
        if (incompatiblePlugins.isEmpty()) {
4015
            return;
4016
        }
4017
        splashWindow.toBack();
4018
        DisablePluginsConflictingDialog dlg = new DisablePluginsConflictingDialog(packages, incompatiblePlugins);
4019
        dlg.setVisible(true);
4020
        splashWindow.toFront();
4021
        switch (dlg.getAction()) {
4022
            case DisablePluginsConflictingDialog.CLOSE:
4023
                System.exit(0);
4024
                break;
4025
            case DisablePluginsConflictingDialog.CONTINUE:
4026
                break;
4027
        }
4028
        List<String> pluginsToDissable = dlg.getPluginNamesToDisable();
4029
        if (pluginsToDissable == null) {
4030
            return;
4031
        }
4032

    
4033
        Iterator<String> it2 = pluginsToDissable.iterator();
4034
        while (it2.hasNext()) {
4035
            String pluginName = it2.next();
4036
            logger.info("Dissabling plugin '" + pluginName + "' by user action.");
4037
            pluginsConfig.remove(pluginName);
4038
        }
4039
    }
4040

    
4041
    private class DisablePluginsConflictingDialog extends JDialog {
4042

    
4043
        public static final int CONTINUE = 0;
4044
        public static final int CLOSE = 1;
4045

    
4046
        private DisablePluginsConflictingLayoutPanel contents;
4047
        private int action = 0;
4048
        private List<Item> incompatiblePlugins = null;
4049
        private Map<String, PackageInfo> packages;
4050

    
4051
        private class Item {
4052

    
4053
            private String code;
4054
            private PackageInfo pkg;
4055

    
4056
            public Item(String code, PackageInfo pkg) {
4057
                this.code = code;
4058
                this.pkg = pkg;
4059
            }
4060

    
4061
            public String toString() {
4062
                if (this.pkg == null) {
4063
                    return code;
4064
                }
4065
                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
4066
            }
4067

    
4068
            public String getCode() {
4069
                if (pkg == null) {
4070
                    return code;
4071
                }
4072
                return pkg.getCode();
4073
            }
4074
        }
4075

    
4076
        DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
4077
            super((Frame) null, "", true);
4078
            this.setTitle(translate("_Conflicting_plugins"));
4079

    
4080
            this.packages = packages;
4081

    
4082
            this.incompatiblePlugins = new ArrayList<Item>();
4083
            Item item = null;
4084
            Iterator<String> it = incompatiblePlugins.iterator();
4085
            while (it.hasNext()) {
4086
                String code = it.next();
4087
                item = new Item(code, packages.get(code));
4088
                this.incompatiblePlugins.add(item);
4089
                logger.info("Found plugin '" + item.getCode() + "' incopatibles with each other.");
4090
            }
4091
            initComponents();
4092
        }
4093

    
4094
        private void initComponents() {
4095
            this.contents = new DisablePluginsConflictingLayoutPanel();
4096

    
4097
            doTranslations();
4098

    
4099
            this.contents.buttonClose.addActionListener(new ActionListener() {
4100
                public void actionPerformed(ActionEvent arg0) {
4101
                    doClose();
4102
                }
4103
            });
4104
            this.contents.buttonContinue.addActionListener(new ActionListener() {
4105
                public void actionPerformed(ActionEvent arg0) {
4106
                    doContinue();
4107
                }
4108
            });
4109
            this.contents.pluginList.setModel(new DefaultListModel(this.incompatiblePlugins));
4110
            ListSelectionModel sm = this.contents.pluginList.getSelectionModel();
4111
            sm.setSelectionMode(sm.MULTIPLE_INTERVAL_SELECTION);
4112
            this.setContentPane(this.contents);
4113
            this.pack();
4114

    
4115
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
4116
            setLocation((screenSize.width / 2) - (this.getWidth() / 2),
4117
                    (screenSize.height / 2) - (this.getHeight() / 2));
4118
        }
4119

    
4120
        private void doTranslations() {
4121
            DisablePluginsConflictingLayoutPanel c = this.contents;
4122
            c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
4123
            c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
4124
            c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
4125
            c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
4126
            c.buttonClose.setText(translate("_Close"));
4127
            c.buttonContinue.setText(translate("_Continue"));
4128
        }
4129

    
4130
        private String translate(String msg) {
4131
            return PluginServices.getText(this, msg);
4132
        }
4133

    
4134
        private void doClose() {
4135
            this.action = CLOSE;
4136
            this.setVisible(false);
4137
        }
4138

    
4139
        private void doContinue() {
4140
            this.action = CONTINUE;
4141
            this.setVisible(false);
4142
        }
4143

    
4144
        public int getAction() {
4145
            return this.action;
4146
        }
4147

    
4148
        public List<String> getPluginNamesToDisable() {
4149
            if (this.action == CLOSE) {
4150
                return null;
4151
            }
4152
            Object[] selecteds = null;
4153
            selecteds = (Object[]) this.contents.pluginList.getSelectedValues();
4154
            if (selecteds == null || selecteds.length < 1) {
4155
                return null;
4156
            }
4157
            List<String> values = new ArrayList<String>();
4158
            for (int i = 0; i < selecteds.length; i++) {
4159
                values.add(((Item) selecteds[i]).getCode());
4160
            }
4161
            return values;
4162
        }
4163
    }
4164

    
4165
    private void initializeIdentityManagement(File pluginsFolder) {
4166
        File identityManagementConfigFile = null;
4167
        PluginServices plugin = null;
4168
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
4169
        while (it.hasNext()) {
4170
            Entry<String, PluginConfig> entry = it.next();
4171
            File pluginFolder = new File(pluginsFolder, entry.getKey());
4172
            File f = new File(pluginFolder, "identity-management.ini");
4173
            if (f.exists()) {
4174
                if (identityManagementConfigFile != null) {
4175
                    logger.warn("Too many identity-managemnt plugins. Disable all.");
4176
                } else {
4177
                    identityManagementConfigFile = f;
4178
                    plugin = PluginServices.getPluginServices(entry.getKey());
4179
                }
4180
            }
4181
        }
4182
        if(plugin != null){
4183
                new DefaultLibrariesInitializer(plugin.getClassLoader()).fullInitialize(true);
4184
        }
4185
        
4186
        if (identityManagementConfigFile == null || plugin == null) {
4187
            return;
4188
        }
4189
        if (!identityManagementConfigFile.canRead()) {
4190
            return;
4191
        }
4192
        PropertiesConfiguration identityManagementConfig = null;
4193
        try {
4194
            identityManagementConfig = new PropertiesConfiguration(identityManagementConfigFile);
4195
        } catch (Exception ex) {
4196
            logger.warn("Can't open identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.", ex);
4197
            return;
4198
        }
4199
        String identityManagerClassName = identityManagementConfig.getString("IdentityManager", null);
4200
        String identityManagementInitializerClassName = identityManagementConfig.getString("IdentityManagementInitializer", null);
4201
        try {
4202
            if (identityManagerClassName != null) {
4203
                Class identityManagerClass = plugin.getClassLoader().loadClass(identityManagerClassName);
4204
                ToolsLocator.registerIdentityManager(identityManagerClass);
4205
            } else {
4206
                logger.info("Entry IdentityManager not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4207
            }
4208

    
4209
            if (identityManagementInitializerClassName != null) {
4210
                Class identityManagerInitializerClass = plugin.getClassLoader().loadClass(identityManagementInitializerClassName);
4211
                Runnable identityManagerInitializer = (Runnable) identityManagerInitializerClass.newInstance();
4212
                identityManagerInitializer.run();
4213
            } else {
4214
                logger.info("Entry IdentityManagementInitializer not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4215
            }
4216

    
4217
        } catch (Exception ex) {
4218
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4219
            return;
4220
        }
4221
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4222
    }
4223

    
4224
}