Statistics
| Revision:

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

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
        Policy.setPolicy(new Policy() {
467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
684
        message(translate("SplashWindow.enable_controls"));
685
        SwingUtilities.invokeAndWait(new Runnable() {
686
            public void run() {
687
                try {
688
                    frame.enableControls();
689
                    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

    
809
        ToolsLocator.registerDefaultToolsLibraries();
810

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

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

    
824
        configureLocales(args);
825

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

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

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

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

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

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

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

    
908
    private class NotificationAppender extends AppenderSkeleton {
909

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

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

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

    
934
        }
935

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

    
942
    }
943

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1200
        XMLEntity entity = new XMLEntity();
1201

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

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

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

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

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

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

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

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

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

    
1273
        Class<? extends IExtension> skinClass;
1274

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

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

    
1304
    }
1305

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

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

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

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

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

    
1367
    }
1368

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

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

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

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

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

    
1399
    private void initializeExtensions() {
1400

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1646
            Extensions extensionConfig = pluginConfig.getExtensions();
1647

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

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

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

    
1681
        }
1682
    }
1683

    
1684
    private TreeSet<SortableMenu> getOrderedMenus() {
1685

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1752
        }
1753

    
1754
        return orderedMenus;
1755
    }
1756

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

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

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

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

    
1780
    public class PluginMenuItem {
1781

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1897
        Iterator<String> pluginNames = pluginsConfig.keySet().iterator();
1898

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

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

    
1914
                Extension[] exts = pc.getExtensions().getExtension();
1915

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

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

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

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

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

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

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

    
1978
                    SelectableTool[] sTools = toolbars[k].getSelectableTool();
1979

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

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

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

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

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

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

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

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

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

    
2113
                            SelectableTool[] sTools = toolbars[k]
2114
                                    .getSelectableTool();
2115

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

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

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

    
2177
        Plugin[] plugins = andamiConfig.getPlugin();
2178

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

    
2183
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2184

    
2185
        while (i.hasNext()) {
2186
            PluginServices ps = i.next();
2187

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

    
2193
                andamiConfig.addPlugin(p);
2194
            }
2195
        }
2196
    }
2197

    
2198
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2199
        URL[] urls = null;
2200

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

    
2204
        File[] files = libFolderFile.listFiles(new FileFilter() {
2205

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

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

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

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

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

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

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

    
2416
    static String getPluginsDir() {
2417
        return andamiConfig.getPluginsDirectory();
2418
    }
2419

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

    
2424
    static void setPluginsDir(String s) {
2425
        andamiConfig.setPluginsDirectory(s);
2426
    }
2427

    
2428
    static MDIFrame getMDIFrame() {
2429
        return frame;
2430
    }
2431

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

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

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

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

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

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

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

    
2484
                }
2485
            }
2486
        }
2487
        return pluginsConfig;
2488
    }
2489

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

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

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

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

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

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

    
2571
    private static AndamiConfig getDefaultAndamiConfig() {
2572
        AndamiConfig andamiConfig = new AndamiConfig();
2573

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

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

    
2592
        andamiConfig.setPlugin(new Plugin[0]);
2593
        return andamiConfig;
2594
    }
2595

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

    
2599
        if (xml.exists()) {
2600
            InputStreamReader reader = null;
2601

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

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

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

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

    
2666
    }
2667

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

    
2675
        File xml = getPluginsPersistenceFile(false);
2676
        OutputStreamWriter writer = null;
2677

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

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

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

    
2716
    static MDIFrame getFrame() {
2717
        return frame;
2718
    }
2719

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

    
2730
    static HashMap getClassesExtensions() {
2731
        return classesExtensions;
2732
    }
2733

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

    
2738
        while (iter.hasNext()) {
2739
            array.add(iter.next().getExtensions());
2740
        }
2741

    
2742
        return array.toArray(new Extensions[array.size()]);
2743
    }
2744

    
2745
    public static Iterator getExtensionIterator() {
2746
        return extensions.iterator();
2747
    }
2748

    
2749
    public static HashMap getPluginConfig() {
2750
        return pluginsConfig;
2751
    }
2752

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

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

    
2764
        return null;
2765
    }
2766

    
2767
    public static AndamiConfig getAndamiConfig() {
2768
        return andamiConfig;
2769
    }
2770

    
2771
    private static class ExtensionComparator implements Comparator {
2772

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

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

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

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

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

    
2797
    private static class MenuComparator implements Comparator<SortableMenu> {
2798

    
2799
        private static ExtensionComparator extComp = new ExtensionComparator();
2800

    
2801
        public int compare(SortableMenu e1, SortableMenu e2) {
2802

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

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

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

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

    
2831
        }
2832
    }
2833

    
2834
    private static class SortableMenu {
2835

    
2836
        public PluginClassLoader loader;
2837
        public Menu menu;
2838
        public SkinExtensionType extension;
2839

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

    
2847
    }
2848

    
2849
    private static class SortableTool {
2850

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

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

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

    
2876
    private static class ToolBarComparator implements Comparator<SortableTool> {
2877

    
2878
        private static ExtensionComparator extComp = new ExtensionComparator();
2879

    
2880
        public int compare(SortableTool e1, SortableTool e2) {
2881

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

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

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

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

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

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

    
2942
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2943

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

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

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

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

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

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

    
3002
        return UIManager.getSystemLookAndFeelClassName();
3003
    }
3004

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

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

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

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

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

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

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

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

    
3181
    public static File getApplicationHomeFolder() {
3182
        return new File(getAppHomeDir());
3183
    }
3184

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

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

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

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

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

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

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

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

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

    
3280
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3281

    
3282
            public void cancel(UnsavedDataPanel panel) {
3283
                panel.setVisible(false);
3284
            }
3285

    
3286
            public void discard(UnsavedDataPanel panel) {
3287
                panel.setVisible(false);
3288
            }
3289

    
3290
            public void accept(UnsavedDataPanel panel) {
3291
                panel.setVisible(false);
3292

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

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

    
3317
    }
3318

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

    
3326
        private boolean proceed = false;
3327
        private UnsavedDataPanel panel = null;
3328

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

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

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

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

    
3373
            // Finalize all the extensions
3374
            finalizeExtensions();
3375

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

    
3386
            logger.info("Quiting application.");
3387

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

    
3391
            System.exit(0);
3392
        }
3393

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

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

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

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

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

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

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

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

    
3519
            UnsavedDataPanel panel = getUnsavedDataPanel();
3520
            panel.setUnsavedDataArray(unsavedData);
3521

    
3522
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3523

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

    
3528
                }
3529

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

    
3534
                }
3535

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

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

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

    
3589
        private void proceed(boolean proceed) {
3590
            this.proceed = proceed;
3591
        }
3592

    
3593
    }
3594

    
3595
    public static TerminationProcess getTerminationProcess() {
3596
        return (new Launcher()).new TerminationProcess();
3597
    }
3598

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

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

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

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

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

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

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

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

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

    
3706
        initializeApp(myArgs, "installer");
3707

    
3708
        new DefaultLibrariesInitializer().fullInitialize(true);
3709

    
3710
        initializeInstallerManager();
3711

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

    
3728
        AndamiConfig config = getAndamiConfig();
3729

    
3730
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3731

    
3732
        initializeLibraries();
3733

    
3734
        packageInfo = getPackageInfo(myArgs[1]);
3735

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

    
3754
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3755

    
3756
        // Launch installer
3757
        PluginsManager manager = PluginsLocator.getManager();
3758

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

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

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

    
3780
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3781

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

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

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

    
3797
            public void windowIconified(WindowEvent we) {
3798
            }
3799

    
3800
            public void windowDeiconified(WindowEvent we) {
3801
            }
3802

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

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

    
3813
        frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3814

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

    
3823
        frame.setVisible(true);
3824
    }
3825

    
3826
    public static String getInformation() {
3827
        return getInformation(null);
3828
    }
3829

    
3830
    private static final int INFO_OS_NAME = 0;
3831
    private static final int INFO_OS_ARCH = 1;
3832
    private static final int INFO_OS_VERSION = 2;
3833
    private static final int INFO_OS_ADITIONAL = 3;
3834
    private static final int INFO_JRE_VENDOR = 4;
3835
    private static final int INFO_JRE_VERSION = 5;
3836
    private static final int INFO_JRE_HOME = 6;
3837
    private static final int INFO_PROXY_HOST = 7;
3838
    private static final int INFO_PROXY_PORT = 8;
3839
    private static final int INFO_PROXY_USER = 9;
3840
    private static final int INFO_PROXY_PASSWORD = 10;
3841
    private static final int INFO_APP_LOCALE = 11;
3842
    private static final int INFO_APP_FOLDER = 12;
3843
    private static final int INFO_APP_HOME = 13;
3844
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3845
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3846
    private static final int INFO_APP_THEME = 16;
3847
    private static final int INFO_APP_SKIN = 17;
3848
    private static final int INFO_PACKAGES = 18;
3849
    private static final int INFO_TEMP_FOLDER = 19;
3850
    
3851
    public static String getInformation(PackageInfo[] pkgs) {
3852

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

    
3879
        String values[] = new String[INFO_TEMP_FOLDER + 1];
3880

    
3881
        PluginsManager pluginmgr = PluginsLocator.getManager();
3882
        LocaleManager localemgr = PluginsLocator.getLocaleManager();
3883

    
3884
        Properties props = System.getProperties();
3885

    
3886
        // OS information
3887
        values[INFO_OS_NAME] = props.getProperty("os.name");
3888
        values[INFO_OS_ARCH] = props.getProperty("os.arch");
3889
        values[INFO_OS_VERSION] = props.getProperty("os.version");
3890

    
3891
        if (values[INFO_OS_NAME].startsWith("Linux")) {
3892
            try {
3893
                StringWriter writer = new StringWriter();
3894

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

    
3909
        values[INFO_JRE_VENDOR] = props.getProperty("java.vendor");
3910
        values[INFO_JRE_VERSION] = props.getProperty("java.version");
3911
        values[INFO_JRE_HOME] = props.getProperty("java.home");
3912
        values[INFO_PROXY_HOST] = props.getProperty("http.proxyHost");
3913
        values[INFO_PROXY_PORT] = props.getProperty("http.proxyPort");
3914
        values[INFO_PROXY_USER] = props.getProperty("http.proxyUserName");
3915

    
3916
        if (props.get("http.proxyPassword") == null) {
3917
            values[INFO_PROXY_PASSWORD] = "(null)";
3918
        } else {
3919
            values[INFO_PROXY_PASSWORD] = "***********";
3920
        }
3921

    
3922
        try {
3923
            values[INFO_APP_SKIN] = MDIManagerFactory.getSkinExtension().getClassName();
3924
        } catch (Throwable e) {
3925
            values[INFO_APP_SKIN] = "(unknow)";
3926
        }
3927
        values[INFO_TEMP_FOLDER] = ToolsLocator.getFoldersManager().getTemporaryFolder().getAbsolutePath();
3928
        values[INFO_APP_LOCALE] = localemgr.getCurrentLocale().toString();
3929
        values[INFO_APP_FOLDER] = pluginmgr.getApplicationFolder().getAbsolutePath();
3930
        values[INFO_APP_HOME] = pluginmgr.getApplicationHomeFolder().getAbsolutePath();
3931
        values[INFO_APP_INSTALL_FOLDER] = pluginmgr.getInstallFolder().getAbsolutePath();
3932
        values[INFO_APP_PLUGINS_FOLDER] = StringUtils.join(pluginmgr.getPluginsFolders());
3933
        values[INFO_APP_THEME] = Launcher.theme.getSource().getAbsolutePath();
3934

    
3935
        try {
3936
            if (pkgs == null) {
3937
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3938
                pkgs = installmgr.getInstalledPackages();
3939
            }
3940
            StringWriter writer = new StringWriter();
3941
            for (PackageInfo pkg : pkgs) {
3942
                writer.write("    ");
3943
                writer.write(pkg.toStringCompact());
3944
                writer.write("\n");
3945
            }
3946
            values[INFO_PACKAGES] = writer.toString();
3947

    
3948
        } catch (Throwable e) {
3949
            logger.warn("Can't get installed package information.", e);
3950
        }
3951

    
3952
        String s = MessageFormat.format(template, (Object[])values);
3953
        return s;
3954
    }
3955

    
3956
    private void logger_info(String msg) {
3957
        String info[] = msg.split("\n");
3958
        for (String info1 : info) {
3959
            logger.info(info1);
3960
        }
3961
    }
3962

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

    
3973
    private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3974
        final Set<String> incompatiblePlugins = new HashSet<String>();
3975

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

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

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

    
4038
        Iterator<String> it2 = pluginsToDissable.iterator();
4039
        while (it2.hasNext()) {
4040
            String pluginName = it2.next();
4041
            logger.info("Dissabling plugin '" + pluginName + "' by user action.");
4042
            pluginsConfig.remove(pluginName);
4043
        }
4044
    }
4045

    
4046
    private class DisablePluginsConflictingDialog extends JDialog {
4047

    
4048
        public static final int CONTINUE = 0;
4049
        public static final int CLOSE = 1;
4050

    
4051
        private DisablePluginsConflictingLayoutPanel contents;
4052
        private int action = 0;
4053
        private List<Item> incompatiblePlugins = null;
4054
        private Map<String, PackageInfo> packages;
4055

    
4056
        private class Item {
4057

    
4058
            private String code;
4059
            private PackageInfo pkg;
4060

    
4061
            public Item(String code, PackageInfo pkg) {
4062
                this.code = code;
4063
                this.pkg = pkg;
4064
            }
4065

    
4066
            public String toString() {
4067
                if (this.pkg == null) {
4068
                    return code;
4069
                }
4070
                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
4071
            }
4072

    
4073
            public String getCode() {
4074
                if (pkg == null) {
4075
                    return code;
4076
                }
4077
                return pkg.getCode();
4078
            }
4079
        }
4080

    
4081
        DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
4082
            super((Frame) null, "", true);
4083
            this.setTitle(translate("_Conflicting_plugins"));
4084

    
4085
            this.packages = packages;
4086

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

    
4099
        private void initComponents() {
4100
            this.contents = new DisablePluginsConflictingLayoutPanel();
4101

    
4102
            doTranslations();
4103

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

    
4120
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
4121
            setLocation((screenSize.width / 2) - (this.getWidth() / 2),
4122
                    (screenSize.height / 2) - (this.getHeight() / 2));
4123
        }
4124

    
4125
        private void doTranslations() {
4126
            DisablePluginsConflictingLayoutPanel c = this.contents;
4127
            c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
4128
            c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
4129
            c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
4130
            c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
4131
            c.buttonClose.setText(translate("_Close"));
4132
            c.buttonContinue.setText(translate("_Continue"));
4133
        }
4134

    
4135
        private String translate(String msg) {
4136
            return PluginServices.getText(this, msg);
4137
        }
4138

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

    
4144
        private void doContinue() {
4145
            this.action = CONTINUE;
4146
            this.setVisible(false);
4147
        }
4148

    
4149
        public int getAction() {
4150
            return this.action;
4151
        }
4152

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

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

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

    
4222
        } catch (Exception ex) {
4223
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4224
            return;
4225
        }
4226
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4227
    }
4228

    
4229
}