Statistics
| Revision:

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

History | View | Annotate | Download (162 KB)

1 40559 jjdelcerro
/**
2
 * gvSIG. Desktop Geographic Information System.
3 40435 jjdelcerro
 *
4 40559 jjdelcerro
 * Copyright (C) 2007-2013 gvSIG Association.
5 40435 jjdelcerro
 *
6 42362 jjdelcerro
 * 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 40435 jjdelcerro
 *
11 42362 jjdelcerro
 * 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 40435 jjdelcerro
 *
16 42362 jjdelcerro
 * 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 40435 jjdelcerro
 *
20 42362 jjdelcerro
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22 40435 jjdelcerro
 */
23
package org.gvsig.andami;
24
25
import java.awt.BorderLayout;
26 41078 jjdelcerro
import java.awt.Cursor;
27 40435 jjdelcerro
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 40821 jjdelcerro
import java.awt.event.ActionEvent;
34
import java.awt.event.ActionListener;
35 41717 jjdelcerro
import java.awt.event.WindowEvent;
36
import java.awt.event.WindowListener;
37 40435 jjdelcerro
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 41025 jjdelcerro
import java.util.Arrays;
65 41312 jjdelcerro
import java.util.Collections;
66 40435 jjdelcerro
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 40819 jjdelcerro
import java.util.Map.Entry;
75 40435 jjdelcerro
import java.util.Properties;
76
import java.util.Set;
77
import java.util.TreeSet;
78 42364 jjdelcerro
import java.util.logging.Level;
79 40435 jjdelcerro
import java.util.prefs.Preferences;
80
81
import javax.swing.ImageIcon;
82
import javax.swing.JButton;
83
import javax.swing.JComponent;
84 40821 jjdelcerro
import javax.swing.JDialog;
85 40435 jjdelcerro
import javax.swing.JFrame;
86
import javax.swing.JOptionPane;
87
import javax.swing.JPopupMenu;
88 40821 jjdelcerro
import javax.swing.ListSelectionModel;
89 40435 jjdelcerro
import javax.swing.SwingUtilities;
90
import javax.swing.UIManager;
91
92 42200 fdiaz
93 40435 jjdelcerro
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 41696 jjdelcerro
import org.apache.commons.configuration.PropertiesConfiguration;
99 40435 jjdelcerro
import org.apache.commons.io.FileUtils;
100 41312 jjdelcerro
import org.apache.commons.lang3.JavaVersion;
101 41706 jjdelcerro
import org.apache.commons.lang3.StringUtils;
102 41312 jjdelcerro
import org.apache.commons.lang3.SystemUtils;
103 40435 jjdelcerro
import org.apache.log4j.AppenderSkeleton;
104
import org.apache.log4j.PatternLayout;
105
import org.apache.log4j.PropertyConfigurator;
106
import org.apache.log4j.RollingFileAppender;
107
import org.apache.log4j.spi.LoggingEvent;
108
import org.apache.log4j.spi.ThrowableInformation;
109
import org.exolab.castor.xml.MarshalException;
110
import org.exolab.castor.xml.ValidationException;
111 42200 fdiaz
112 40435 jjdelcerro
import org.gvsig.andami.actioninfo.ActionInfo;
113
import org.gvsig.andami.actioninfo.ActionInfoManager;
114
import org.gvsig.andami.config.generate.Andami;
115
import org.gvsig.andami.config.generate.AndamiConfig;
116
import org.gvsig.andami.config.generate.Plugin;
117 42200 fdiaz
import org.gvsig.andami.impl.UnsavedDataException;
118 40435 jjdelcerro
import org.gvsig.andami.messages.Messages;
119
import org.gvsig.andami.messages.NotificationManager;
120 40627 nbrodin
import org.gvsig.andami.persistence.serverData.ServerDataPersistence;
121 40435 jjdelcerro
import org.gvsig.andami.plugins.ExclusiveUIExtension;
122
import org.gvsig.andami.plugins.ExtensionDecorator;
123
import org.gvsig.andami.plugins.IExtension;
124
import org.gvsig.andami.plugins.PluginClassLoader;
125
import org.gvsig.andami.plugins.config.generate.Action;
126
import org.gvsig.andami.plugins.config.generate.ActionTool;
127
import org.gvsig.andami.plugins.config.generate.AlternativeNames;
128
import org.gvsig.andami.plugins.config.generate.ComboButton;
129
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
130
import org.gvsig.andami.plugins.config.generate.ComboScale;
131
import org.gvsig.andami.plugins.config.generate.Depends;
132
import org.gvsig.andami.plugins.config.generate.Extension;
133
import org.gvsig.andami.plugins.config.generate.Extensions;
134
import org.gvsig.andami.plugins.config.generate.LabelSet;
135
import org.gvsig.andami.plugins.config.generate.Menu;
136
import org.gvsig.andami.plugins.config.generate.PluginConfig;
137
import org.gvsig.andami.plugins.config.generate.PopupMenu;
138
import org.gvsig.andami.plugins.config.generate.PopupMenus;
139
import org.gvsig.andami.plugins.config.generate.SelectableTool;
140
import org.gvsig.andami.plugins.config.generate.SkinExtension;
141
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
142
import org.gvsig.andami.plugins.config.generate.ToolBar;
143
import org.gvsig.andami.plugins.status.IExtensionStatus;
144
import org.gvsig.andami.plugins.status.IUnsavedData;
145
import org.gvsig.andami.ui.AndamiEventQueue;
146 40821 jjdelcerro
import org.gvsig.andami.ui.DisablePluginsConflictingLayoutPanel;
147 40435 jjdelcerro
import org.gvsig.andami.ui.MDIManagerLoadException;
148
import org.gvsig.andami.ui.ToolsWindowManager;
149
import org.gvsig.andami.ui.fonts.FontUtils;
150
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
151
import org.gvsig.andami.ui.mdiFrame.MainFrame;
152
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
153
import org.gvsig.andami.ui.splash.MultiSplashWindow;
154
import org.gvsig.andami.ui.theme.Theme;
155
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
156 42200 fdiaz
import org.gvsig.andami.ui.wizard.UnsavedDataPanel.UnsavedDataPanelListener;
157 40819 jjdelcerro
import org.gvsig.installer.lib.api.Dependencies;
158
import org.gvsig.installer.lib.api.Dependency;
159 40435 jjdelcerro
import org.gvsig.installer.lib.api.InstallerLocator;
160
import org.gvsig.installer.lib.api.InstallerManager;
161
import org.gvsig.installer.lib.api.PackageInfo;
162 40819 jjdelcerro
import org.gvsig.installer.lib.api.creation.MakePluginPackageServiceException;
163 40435 jjdelcerro
import org.gvsig.installer.swing.api.SwingInstallerLocator;
164
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
165
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
166
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
167 41696 jjdelcerro
import org.gvsig.tools.ToolsLocator;
168 40435 jjdelcerro
import org.gvsig.tools.exception.ListBaseException;
169
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
170
import org.gvsig.tools.swing.api.ToolsSwingLocator;
171 42200 fdiaz
import org.gvsig.tools.swing.api.windowmanager.WindowManager.MODE;
172 40435 jjdelcerro
import org.gvsig.tools.swing.icontheme.IconTheme;
173
import org.gvsig.tools.swing.icontheme.IconThemeManager;
174
import org.gvsig.tools.util.FolderSet;
175
import org.gvsig.tools.util.FolderSet.FolderEntry;
176
import org.gvsig.utils.DateTime;
177 40821 jjdelcerro
import org.gvsig.utils.DefaultListModel;
178 40435 jjdelcerro
import org.gvsig.utils.XMLEntity;
179
import org.gvsig.utils.xml.XMLEncodingUtils;
180
import org.gvsig.utils.xmlEntity.generate.XmlTag;
181 42200 fdiaz
182 40819 jjdelcerro
import org.slf4j.Logger;
183
import org.slf4j.LoggerFactory;
184 40435 jjdelcerro
185
/**
186
 * <p>
187
 * Andami's launching class. This is the class used to create the Andami's
188
 * plugin environment.<br>
189
 * </p>
190 41775 fdiaz
 *
191 40435 jjdelcerro
 * <p>
192
 * <b>Syntax:</b> <br>
193
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or
194
 * semicolon-separated(windows) list of files containg base library of classes}]
195
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
196
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
197
 * [{list of additional custom application arguments separated by spaces}]
198
 * </p>
199 41775 fdiaz
 *
200
 *
201 40435 jjdelcerro
 * @author $author$
202
 * @version $Revision: 40305 $
203
 */
204
public class Launcher {
205
206 42362 jjdelcerro
    public static abstract class MapWithAlias<Item> extends HashMap<String, Item> {
207 41775 fdiaz
208 42362 jjdelcerro
        private HashMap<String, String> aliases = new HashMap<String, String>();
209 41775 fdiaz
210 42362 jjdelcerro
        public abstract String[] getAliases(Item item);
211 41025 jjdelcerro
212 42362 jjdelcerro
        public boolean isAlias(String key) {
213
            return aliases.get(key) != null;
214
        }
215 41775 fdiaz
216 42362 jjdelcerro
        public String getMainKey(String key) {
217
            Item item = super.get(key);
218
            if (item != null) {
219
                return key;
220
            }
221
            String alias = aliases.get(key);
222
            if (alias != null) {
223
                return alias;
224
            }
225
            return null;
226
        }
227 41775 fdiaz
228 42362 jjdelcerro
        public Item get(Object key) {
229
            Item item = super.get(key);
230
            if (item != null) {
231
                return item;
232
            }
233
            String alias = aliases.get(key);
234
            if (alias != null) {
235
                return super.get(alias);
236
            }
237
            return null;
238
        }
239 41775 fdiaz
240 42362 jjdelcerro
        public boolean containsKey(Object key) {
241
            boolean contains = super.containsKey(key);
242
            if (contains) {
243
                return true;
244
            }
245
            String alias = aliases.get(key);
246
            return super.containsKey(alias);
247
        }
248 41775 fdiaz
249 42362 jjdelcerro
        public Item put(String key, Item value) {
250
            super.put(key, value);
251
            String[] aliases = getAliases(value);
252
            if (aliases == null) {
253
                return value;
254
            }
255
            for (int n = 0; n < aliases.length; n++) {
256
                this.aliases.put(aliases[n].trim(), key);
257
            }
258
            return value;
259
        }
260 41775 fdiaz
261 42362 jjdelcerro
        public void putAll(Map<? extends String, ? extends Item> m) {
262
            Iterator<?> it = m.entrySet().iterator();
263
            while (it.hasNext()) {
264
                Map.Entry<String, Item> x = (Map.Entry<String, Item>) it.next();
265
                this.put(x.getKey(), x.getValue());
266
            }
267
        }
268 40821 jjdelcerro
269 42362 jjdelcerro
        public Item remove(Object key) {
270
            Item item = super.get(key);
271
            if (item == null) {
272
                String alias = aliases.get(key);
273
                if (alias == null) {
274
                    return null;
275
                }
276
                item = super.get(alias);
277
                super.remove(alias);
278
            } else {
279
                super.remove(key);
280
            }
281
            String[] aliases = getAliases(item);
282
            if (aliases == null) {
283
                return item;
284
            }
285
            // Rebuild the alias list
286
            this.aliases = new HashMap<String, String>();
287
            Iterator<java.util.Map.Entry<String, Item>> it = this.entrySet().iterator();
288
            while (it.hasNext()) {
289
                java.util.Map.Entry<String, Item> entry = it.next();
290
                aliases = getAliases(entry.getValue());
291
                if (aliases == null) {
292
                    continue;
293
                }
294
                for (int n = 0; n < aliases.length; n++) {
295
                    this.aliases.put(aliases[n].trim(), entry.getKey());
296
                }
297
            }
298 41775 fdiaz
299 42362 jjdelcerro
            return item;
300
        }
301 41775 fdiaz
302 42362 jjdelcerro
    }
303 41775 fdiaz
304 42362 jjdelcerro
    public static class PluginsConfig extends MapWithAlias<org.gvsig.andami.plugins.config.generate.PluginConfig> {
305 40435 jjdelcerro
306 42362 jjdelcerro
        public String[] getAliases(
307
                org.gvsig.andami.plugins.config.generate.PluginConfig item) {
308
            return getAlternativeNames(item);
309
        }
310 41775 fdiaz
311 42362 jjdelcerro
        static String[] getAlternativeNames(org.gvsig.andami.plugins.config.generate.PluginConfig item) {
312
            AlternativeNames[] x = item.getAlternativeNames();
313
            if (x == null) {
314
                return null;
315
            }
316
            String[] r = new String[x.length];
317
            for (int i = 0; i < x.length; i++) {
318
                r[i] = x[i].getName();
319
            }
320
            return r;
321
        }
322 41775 fdiaz
323 42362 jjdelcerro
    }
324 40435 jjdelcerro
325 42362 jjdelcerro
    public static class PluginsServices extends MapWithAlias<org.gvsig.andami.PluginServices> {
326 41775 fdiaz
327 42362 jjdelcerro
        public String[] getAliases(org.gvsig.andami.PluginServices item) {
328
            return item.getAlternativeNames();
329
        }
330
    }
331 40435 jjdelcerro
332 42362 jjdelcerro
    protected static Logger logger = LoggerFactory.getLogger(Launcher.class
333
            .getName());
334
    protected static Preferences prefs = Preferences.userRoot().node(
335
            "gvsig.connection");
336
    protected static AndamiConfig andamiConfig;
337
    protected static MultiSplashWindow splashWindow;
338
    protected static String appName;
339
    protected static Locale locale;
340
    protected static PluginsConfig pluginsConfig = new PluginsConfig();
341
    protected static PluginsServices pluginsServices = new PluginsServices();
342
    protected static MDIFrame frame;
343
    protected static HashMap<Class<? extends IExtension>, ExtensionDecorator> classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
344
    protected static String andamiConfigPath;
345
    protected static final String nonWinDefaultLookAndFeel = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
346 40435 jjdelcerro
347 42364 jjdelcerro
    protected static List<String> pluginsOrdered = new ArrayList<String>();
348
    protected static List<IExtension> extensions = new ArrayList<IExtension>();
349 42362 jjdelcerro
    protected static String appHomeDir = null;
350
    // it seems castor uses this encoding
351
    protected static final String CASTORENCODING = "UTF8";
352 40435 jjdelcerro
353 42362 jjdelcerro
    protected static ListBaseException launcherrors = null;
354 41775 fdiaz
355 42362 jjdelcerro
    protected static Theme theme = null;
356 40435 jjdelcerro
357 42362 jjdelcerro
    private List<String> deprecatedPluginNames = null;
358 40435 jjdelcerro
359 42362 jjdelcerro
    private static final class ProxyAuth extends Authenticator {
360 40435 jjdelcerro
361 42362 jjdelcerro
        private PasswordAuthentication auth;
362 40435 jjdelcerro
363 42362 jjdelcerro
        private ProxyAuth(String user, String pass) {
364
            auth = new PasswordAuthentication(user, pass.toCharArray());
365
        }
366 40435 jjdelcerro
367 42362 jjdelcerro
        protected PasswordAuthentication getPasswordAuthentication() {
368
            return auth;
369
        }
370
    }
371 40435 jjdelcerro
372 42362 jjdelcerro
    private static Launcher launcherInstance;
373 41775 fdiaz
374 42362 jjdelcerro
    public static Launcher getInstance() {
375
        if (launcherInstance == null) {
376
            launcherInstance = new Launcher();
377
        }
378
        return launcherInstance;
379
    }
380 41312 jjdelcerro
381 42362 jjdelcerro
    public static void main(String[] args) throws Exception {
382
        Launcher launcher = getInstance();
383
        boolean install = false;
384
        for (int i = 0; i < args.length; i++) {
385
            if (args[i].equalsIgnoreCase("--install")) {
386
                install = true;
387
            }
388
        }
389 40435 jjdelcerro
390 42362 jjdelcerro
        try {
391
            if (install) {
392
                launcher.doInstall(args);
393
            } else {
394
                launcher.doMain(args);
395
            }
396
        } catch (Exception e) {
397
            logger.error("excepci?n al arrancar", e);
398
            System.exit(-1);
399
        }
400
    }
401 40435 jjdelcerro
402 42362 jjdelcerro
    protected void downloadExtensions(String extDir) {
403
        // do nothing
404
    }
405 40435 jjdelcerro
406 42362 jjdelcerro
    public static class LaunchException extends ListBaseException {
407 40435 jjdelcerro
408 42362 jjdelcerro
        private static final long serialVersionUID = 4541192746962684705L;
409 40435 jjdelcerro
410 42362 jjdelcerro
        public LaunchException() {
411
            super("Errors in initialization of application.",
412
                    "_errors_in_initialization_of_application",
413
                    serialVersionUID);
414
        }
415 40435 jjdelcerro
416 42362 jjdelcerro
    }
417 40435 jjdelcerro
418 42362 jjdelcerro
    protected void addError(Throwable ex) {
419
        if (launcherrors == null) {
420
            launcherrors = new LaunchException();
421
        }
422
        launcherrors.add(ex);
423
    }
424 40435 jjdelcerro
425 42362 jjdelcerro
    protected void addError(String msg, Throwable cause) {
426
        logger.error(msg, cause);
427
        this.addError(new RuntimeException(msg, cause));
428
    }
429 40435 jjdelcerro
430 42362 jjdelcerro
    protected void addError(String msg) {
431
        this.addError(msg, null);
432
    }
433 41775 fdiaz
434 42362 jjdelcerro
    private String translate(String msg) {
435
        return PluginServices.getText(Launcher.class, msg);
436
    }
437 41775 fdiaz
438 42362 jjdelcerro
    private List<String> getDeprecatedPluginNames() {
439
        if (deprecatedPluginNames == null) {
440
            String[] ss = new String[]{
441
                "org.gvsig.app",
442
                "org.gvsig.coreplugin",
443
                "org.gvsig.editing",
444
                "org.gvsig.installer.app.extension",
445
                "org.gvsig.exportto.app.extension"
446
            };
447
            deprecatedPluginNames = Arrays.asList(ss);
448
        }
449
        return deprecatedPluginNames;
450
    }
451 40435 jjdelcerro
452 42362 jjdelcerro
    public void doMain(String[] args) throws Exception {
453 40435 jjdelcerro
454 42362 jjdelcerro
        if (args.length < 1) {
455
            System.err.println("Usage: Launcher appName plugins-directory [language=locale]");
456
            System.err.println("No arguments specified.");
457
            System.err.println("Use default arguments 'gvSIG gvSIG/extensiones'");
458
            args = new String[]{"gvSIG", "gvSIG/extensiones"};
459
        }
460 40435 jjdelcerro
461 42362 jjdelcerro
        initializeApp(args, null);
462
463 40435 jjdelcerro
                // Solucionamos el problema de permisos que se produc?do con Java
464 42362 jjdelcerro
        // Web Start con este codigo.
465
        // System.setSecurityManager(null);
466
        Policy.setPolicy(new Policy() {
467 40435 jjdelcerro
468 42362 jjdelcerro
            public PermissionCollection getPermissions(CodeSource codesource) {
469
                Permissions perms = new Permissions();
470
                perms.add(new AllPermission());
471
                return (perms);
472
            }
473 40435 jjdelcerro
474 42362 jjdelcerro
            public void refresh() {
475
            }
476
        });
477 41775 fdiaz
478 40435 jjdelcerro
        new DefaultLibrariesInitializer().fullInitialize(true);
479
        InstallerLocator.getInstallerManager().setDownloadBaseURL(
480 42362 jjdelcerro
                new URL("http://downloads.gvsig.org/download/gvsig-desktop/"));
481 40435 jjdelcerro
482 42362 jjdelcerro
        try {
483
            initIconThemes();
484
        } catch (Exception ex) {
485
            this.addError("Can't initialize icon theme", ex);
486
        }
487
        // Registramos los iconos base
488
        try {
489
            registerIcons();
490
        } catch (Exception ex) {
491
            this.addError("Can't register icons", ex);
492
        }
493 40435 jjdelcerro
494 42362 jjdelcerro
        // Obtener la personalizaci?n de la aplicacion.
495
        try {
496
            logger.info("Initialize andami theme");
497
            theme = getTheme(andamiConfig.getPluginsDirectory());
498
        } catch (Exception ex) {
499
            this.addError("Can't get personalized theme for the application",
500
                    ex);
501
        }
502
        UIManager.put("Desktop.background", theme.getBackgroundColor());
503 41775 fdiaz
504 42362 jjdelcerro
        // Mostrar la ventana de inicio
505
        Frame f = new Frame();
506
        splashWindow = new MultiSplashWindow(f, theme, 27);
507 41775 fdiaz
508 42362 jjdelcerro
        // Ponemos los datos del proxy
509
        splashWindow.process(translate("SplashWindow.configuring_proxy"));
510
        logger.info("Configute http proxy");
511
        configureProxy();
512 40435 jjdelcerro
513 42362 jjdelcerro
        // Buscar actualizaciones de los plugins
514
        splashWindow.process(translate("SplashWindow.looking_for_updates"));
515
        try {
516 40435 jjdelcerro
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
517 42362 jjdelcerro
        } catch (Exception ex) {
518
            this.addError("Can't downloads plugins", ex);
519
        }
520 40435 jjdelcerro
521 42362 jjdelcerro
        splashWindow.process(translate("SplashWindow.initialize_install_manager"));
522
        initializeInstallerManager();
523 40819 jjdelcerro
524 42362 jjdelcerro
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
525
        PackageInfo[] installedPackages = null;
526
        try {
527
            installedPackages = installerManager.getInstalledPackages();
528
        } catch (MakePluginPackageServiceException e) {
529
            // Do nothing, ignore errors
530
        }
531
        logger.info("Dump system information");
532
        logger_info(getInformation(installedPackages));
533
        saveEnvironInformation(installedPackages);
534 41775 fdiaz
535 42362 jjdelcerro
        // Se leen los config.xml de los plugins
536
        splashWindow.process(translate("SplashWindow.load_plugins_configuration"));
537
        try {
538
            logger.info("Load plugins information");
539
            this.loadPluginConfigs();
540
            if (pluginsConfig.isEmpty()) {
541
                logger.warn("No valid plugin was found.");
542
                System.exit(-1);
543
            }
544
        } catch (Throwable ex) {
545
            this.addError("Can't load plugins", ex);
546
        }
547 40819 jjdelcerro
548 42362 jjdelcerro
        splashWindow.process(translate("SplashWindow.check_incompatible_plugins"));
549
        fixIncompatiblePlugins(installedPackages);
550 41775 fdiaz
551 42362 jjdelcerro
        // Se configura el classloader del plugin
552
        splashWindow.process(translate("SplashWindow.setup_plugins_configuration"));
553
        try {
554
            logger.info("Configure plugins class loader");
555
            this.loadPluginServices();
556
        } catch (Throwable ex) {
557
            logger.warn("Can't initialize plugin's classloaders  ", ex);
558
        }
559
        try {
560
            registerActions();
561
        } catch (Throwable ex) {
562
            logger.warn("Can't register actions of plugins", ex);
563
        }
564 40435 jjdelcerro
565 42362 jjdelcerro
        initializeIdentityManagement(new File(andamiConfig.getPluginsDirectory()).getAbsoluteFile());
566 41775 fdiaz
567 42362 jjdelcerro
        // Initialize libraries
568
        splashWindow.process(translate("SplashWindow.initialize_plugins_libraries"));
569
        initializeLibraries();
570 41775 fdiaz
571 42362 jjdelcerro
        // Se carga un Skin si alguno ide los plugins trae informacion para ello
572
        splashWindow.process(translate("SplashWindow.looking_for_a_skin"));
573
        logger.info("Initialize skin");
574
        skinPlugin(null);
575 41775 fdiaz
576 42362 jjdelcerro
        // Se configura la cola de eventos
577
        splashWindow.process(translate("setting_up_event_queue"));
578
        EventQueue waitQueue = new AndamiEventQueue();
579
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
580 40435 jjdelcerro
581 42362 jjdelcerro
        // Se configura la internacionalizacion del plugin
582
        splashWindow.process(translate("SplashWindow.starting_plugin_internationalization_system"));
583
        pluginsMessages();
584 40435 jjdelcerro
585 42362 jjdelcerro
        // Se modifica el andami-config con los plugins nuevos
586
        splashWindow.process(translate("SplashWindow.update_framework_configuration"));
587
        updateAndamiConfig();
588 40435 jjdelcerro
589 42362 jjdelcerro
        frame = MDIFrame.getInstance();
590
        // Se configura el nombre e icono de la aplicacion
591
        splashWindow.process(translate("SplashWindow.setting_up_applications_name_and_icons"));
592
        frameIcon(theme);
593 40435 jjdelcerro
594 42362 jjdelcerro
        // Se prepara el MainFrame para albergar las extensiones
595
        splashWindow.process(translate("SplashWindow.preparing_workbench"));
596
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
597
        SwingUtilities.invokeAndWait(new Runnable() {
598
            public void run() {
599
                frame.init();
600
            }
601
        });
602
        ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
603 40435 jjdelcerro
604 42362 jjdelcerro
        // Leer el fichero de persistencia de los plugins
605
        splashWindow.process(translate("SplashWindow.loading_plugin_settings"));
606
        loadPluginsPersistence();
607 40435 jjdelcerro
608
                // Se instalan los controles del skin
609 42362 jjdelcerro
        // Se inicializan todas las extensiones de todos los plugins
610
        splashWindow.process(translate("SplashWindow.initializing_extensions"));
611
        SwingUtilities.invokeAndWait(new Runnable() {
612
            public void run() {
613
                initializeExtensions();
614
            }
615
        });
616 40435 jjdelcerro
617 42362 jjdelcerro
        // Se inicializan la extension exclusiva
618
        splashWindow.process(translate("SplashWindow.setting_up_master_extension"));
619
        SwingUtilities.invokeAndWait(new Runnable() {
620
            public void run() {
621
                initializeExclusiveUIExtension();
622
            }
623
        });
624
        frame.setClassesExtensions(classesExtensions);
625 40435 jjdelcerro
626 42362 jjdelcerro
        // Se instalan los controles de las extensiones de los plugins
627
        message(translate("SplashWindow.installing_extensions_controls"));
628
        SwingUtilities.invokeAndWait(new Runnable() {
629
            public void run() {
630
                installPluginsControls();
631
            }
632
        });
633 40435 jjdelcerro
634 42362 jjdelcerro
        // Se instalan los menus de las extensiones de los plugins
635
        message(translate("SplashWindow.installing_extensions_menus"));
636
        SwingUtilities.invokeAndWait(new Runnable() {
637
            public void run() {
638
                installPluginsMenus();
639
            }
640
        });
641 40435 jjdelcerro
642 42362 jjdelcerro
        message(translate("SplashWindow.initializing_server_data_persistence"));
643
        ServerDataPersistence.registerPersistence();
644 41775 fdiaz
645 42362 jjdelcerro
        // Se instalan las etiquetas de las extensiones de los plugins
646
        message(translate("SplashWindow.installing_extensions_labels"));
647
        SwingUtilities.invokeAndWait(new Runnable() {
648
            public void run() {
649
                installPluginsLabels();
650
            }
651
        });
652 40435 jjdelcerro
653 42362 jjdelcerro
        // Se muestra el frame principal
654
        message(translate("creating_main_window"));
655
        frame.setVisible(true);
656
        frame.setCursor(Cursor.WAIT_CURSOR);
657 40435 jjdelcerro
658
                // Definimos un KeyEventDispatcher global para que las extensiones
659 42362 jjdelcerro
        // puedan registrar sus "teclas rapidas".
660
        message(translate("SplashWindow.initializing_accelerator_keys"));
661
        GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
662
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
663 40435 jjdelcerro
664 42362 jjdelcerro
        message(translate("SplashWindow.enable_controls"));
665
        SwingUtilities.invokeAndWait(new Runnable() {
666
            public void run() {
667
                try {
668
                    frame.enableControls();
669
                } catch (Throwable th) {
670
                    logger.warn("Problems enabling controls", th);
671
                }
672
            }
673
        });
674 41775 fdiaz
675 42362 jjdelcerro
        // Se ejecuta el postInitialize
676
        message(translate("SplashWindow.post_initializing_extensions"));
677
        SwingUtilities.invokeAndWait(new Runnable() {
678
            public void run() {
679
                postInitializeExtensions();
680
            }
681
        });
682 41775 fdiaz
683 42362 jjdelcerro
        message(translate("SplashWindow.enable_controls"));
684
        SwingUtilities.invokeAndWait(new Runnable() {
685
            public void run() {
686
                try {
687
                    frame.enableControls();
688
                    message(translate("StatusBar.Aplicacion_iniciada"));
689
                } catch (Throwable th) {
690
                    logger.warn("Problems enabling controls", th);
691
                }
692
            }
693
        });
694 40435 jjdelcerro
695 42362 jjdelcerro
        splashWindow.close();
696 41775 fdiaz
697 42362 jjdelcerro
        frame.setCursor(Cursor.DEFAULT_CURSOR);
698 40435 jjdelcerro
699 42362 jjdelcerro
        if (launcherrors != null) {
700
            NotificationManager.addError(launcherrors);
701
        }
702
        org.apache.log4j.Logger.getRootLogger().addAppender(
703
                new NotificationAppender());
704 41775 fdiaz
705 42362 jjdelcerro
        /*
706
         * Executes additional tasks required by plugins
707
         */
708
        PluginsLocator.getManager().executeStartupTasks();
709 40435 jjdelcerro
710 42362 jjdelcerro
    }
711 41706 jjdelcerro
712 42362 jjdelcerro
    private void initializeInstallerManager() {
713
        PluginsManager pluginmgr = PluginsLocator.getManager();
714
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
715 41706 jjdelcerro
716 41775 fdiaz
            //
717 42362 jjdelcerro
        // Configure repository of plugins
718
        //
719
        List<File> folders = pluginmgr.getPluginsFolders();
720
        for (File folder : folders) {
721
            installerManager.addLocalAddonRepository(folder, "plugin");
722
        }
723
        installerManager.setDefaultLocalAddonRepository(folders.get(0), "plugin");
724
725 41706 jjdelcerro
            //
726 42362 jjdelcerro
        // Configure repository of iconsets
727
        //
728
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
729
        FolderSet fset = iconManager.getRepository();
730
        Iterator<FolderSet.FolderEntry> it = fset.iterator();
731
        boolean first = true;
732
        while (it.hasNext()) {
733
            FolderEntry entry = it.next();
734
            installerManager.addLocalAddonRepository(entry.getFolder(), "iconset");
735
            if (first) {
736
                first = false;
737
                installerManager.setDefaultLocalAddonRepository(entry.getFolder(), "iconset");
738 41706 jjdelcerro
            }
739 42362 jjdelcerro
        }
740 41775 fdiaz
741 42362 jjdelcerro
    }
742
743
    private void message(final String msg) {
744
        if (!SwingUtilities.isEventDispatchThread()) {
745
            try {
746
                SwingUtilities.invokeAndWait(new Runnable() {
747
                    public void run() {
748
                        message(msg);
749 41706 jjdelcerro
                    }
750 42362 jjdelcerro
                });
751
            } catch (Exception e) {
752
                logger.info(msg);
753
                logger.warn("Error showing message.", e);
754 41706 jjdelcerro
            }
755 42362 jjdelcerro
            return;
756 41706 jjdelcerro
        }
757 42362 jjdelcerro
        if (splashWindow.isVisible()) {
758
            splashWindow.process(msg);
759
        }
760
        if (frame.isVisible()) {
761
            frame.message(msg, JOptionPane.INFORMATION_MESSAGE);
762
        }
763
    }
764 41706 jjdelcerro
765 42362 jjdelcerro
    private void initializeLibraries() {
766
        List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
767
                pluginsOrdered.size() + 1);
768
        classLoaders.add(getClass().getClassLoader());
769
        Iterator<String> iter = pluginsOrdered.iterator();
770 40435 jjdelcerro
771 42362 jjdelcerro
        logger.info("Initializing plugins libraries: ");
772
        while (iter.hasNext()) {
773
            String pName = (String) iter.next();
774
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
775
            logger.info("Initializing plugin libraries (" + pName + ")");
776
            classLoaders.add(ps.getClassLoader());
777
        }
778 40435 jjdelcerro
779
                // Create the libraries initializer and
780 42362 jjdelcerro
        // initialize the plugin libraries
781
        new DefaultLibrariesInitializer(classLoaders
782
                .toArray(new ClassLoader[classLoaders.size()]))
783
                .fullInitialize(true);
784 40435 jjdelcerro
785 42362 jjdelcerro
        // Remove them all, we don't need them anymore
786
        classLoaders.clear();
787
        classLoaders = null;
788
    }
789 40435 jjdelcerro
790 42362 jjdelcerro
    /**
791
     * @param args
792
     * @throws IOException
793
     * @throws ConfigurationException
794
     */
795
    private void initializeApp(String[] args, String applicationClasifier) throws IOException, ConfigurationException {
796
        if (args.length < 1) {
797
            appName = "gvSIG"; // Nombre de aplicacion por defecto es "gvSIG"
798
        } else {
799
            appName = args[0];
800
        }
801
        getOrCreateConfigFolder();
802
        configureLogging(appName, applicationClasifier);
803
        if (!validJVM()) {
804
            logger.error("Not a valid JRE. Exit application.");
805
            System.exit(-1);
806
        }
807
        // Clean temporal files
808
        Utilities.cleanUpTempFiles();
809 40435 jjdelcerro
810 42362 jjdelcerro
        if (args.length < 2) {
811
            loadAndamiConfig("gvSIG/extensiones"); // Valor por defecto
812
        } else {
813
            loadAndamiConfig(args[1]);
814
        }
815 40435 jjdelcerro
816
                // Hacemos visibles los argumentos como una propiedad est?tica
817 42362 jjdelcerro
        // de plugin services para quien lo quiera usar (por ejemplo, para
818
        // cargar un proyecto por l?nea de comandos)
819
        PluginServices.setArguments(args);
820 40435 jjdelcerro
821 42362 jjdelcerro
        configureLocales(args);
822 40435 jjdelcerro
823 42362 jjdelcerro
        logger.info("Configure LookAndFeel");
824
        configureLookAndFeel();
825
    }
826 40435 jjdelcerro
827 42362 jjdelcerro
    /**
828 41775 fdiaz
     *
829 40435 jjdelcerro
     */
830 42362 jjdelcerro
    private void configureLookAndFeel() {
831
        // Se pone el lookAndFeel
832
        try {
833
            String lookAndFeel = getAndamiConfig().getLookAndFeel();
834
            if (lookAndFeel == null) {
835
                lookAndFeel = getDefaultLookAndFeel();
836
            }
837
            UIManager.setLookAndFeel(lookAndFeel);
838
        } catch (Exception e) {
839
            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
840
        }
841
        FontUtils.initFonts();
842
    }
843 40435 jjdelcerro
844 42362 jjdelcerro
    /**
845
     * @param args
846
     * @throws ConfigurationException
847
     */
848
    private void loadAndamiConfig(String pluginFolder)
849
            throws ConfigurationException {
850
        andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
851
        andamiConfigFromXML(andamiConfigPath);
852
        andamiConfig.setPluginsDirectory(pluginFolder);
853
    }
854 40435 jjdelcerro
855 42362 jjdelcerro
    /**
856 41775 fdiaz
     *
857 40435 jjdelcerro
     */
858 42362 jjdelcerro
    private void getOrCreateConfigFolder() {
859
        // Create application configuration folder
860
        appHomeDir = System.getProperty(appName + ".home");
861
        if (appHomeDir == null) {
862
            appHomeDir = System.getProperty("user.home");
863
        }
864 40435 jjdelcerro
865 42362 jjdelcerro
        appHomeDir += File.separator + appName;
866
        File parent = new File(appHomeDir);
867
        parent.mkdirs();
868
    }
869 40435 jjdelcerro
870 42362 jjdelcerro
    /**
871
     * @param args
872
     * @throws IOException
873
     */
874
    private void configureLogging(String appName, String applicationClasifier) throws IOException {
875
        // Configurar el log4j
876 40435 jjdelcerro
877 42362 jjdelcerro
        String pathname;
878
        if (StringUtils.isBlank(applicationClasifier)) {
879
            pathname = appHomeDir + File.separator + appName + ".log";
880
        } else {
881
            pathname = appHomeDir + File.separator + appName + "-" + applicationClasifier + ".log";
882
        }
883
        URL config = Launcher.class.getClassLoader().getResource("log4j.properties");
884
        if (config == null) {
885
            config = Launcher.class.getClassLoader().getResource("default-log4j/log4j.properties");
886
        }
887
        PropertyConfigurator.configure(config);
888
        PatternLayout l = new PatternLayout("%p %t %C - %m%n");
889
        RollingFileAppender fa = new RollingFileAppender(l, pathname, false);
890
        fa.setMaxFileSize("512KB");
891
        fa.setMaxBackupIndex(3);
892
        org.apache.log4j.Logger.getRootLogger().addAppender(fa);
893
        logger.info("Loadded log4j.properties from " + config.toString());
894
        if (StringUtils.isBlank(applicationClasifier)) {
895
            logger.info("Application " + appName);
896
        } else {
897
            logger.info("Application " + appName + "-" + applicationClasifier);
898
        }
899
    }
900 42622 jjdelcerro
901
    public static String getApplicationName() {
902
        return appName;
903
    }
904 40435 jjdelcerro
905 42362 jjdelcerro
    private class NotificationAppender extends AppenderSkeleton {
906 40435 jjdelcerro
907 42362 jjdelcerro
        @Override
908
        protected void append(LoggingEvent event) {
909
            if (event.getLevel() == org.apache.log4j.Level.ERROR
910
                    || event.getLevel() == org.apache.log4j.Level.FATAL) {
911 41775 fdiaz
912 42362 jjdelcerro
                Throwable th = null;
913
                ThrowableInformation thi = event.getThrowableInformation();
914
                if (thi != null) {
915
                    th = thi.getThrowable();
916
                }
917
                NotificationManager.dispatchError(event.getRenderedMessage(), th);
918
                return;
919
            }
920 40435 jjdelcerro
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
921 42362 jjdelcerro
            // NotificationManager.dispatchWarning(event.getRenderedMessage(),
922
            // null);
923
            // return;
924
            // }
925
        }
926 40435 jjdelcerro
927 42362 jjdelcerro
        @Override
928
        public void close() {
929
            // TODO Auto-generated method stub
930 41775 fdiaz
931 42362 jjdelcerro
        }
932 40435 jjdelcerro
933 42362 jjdelcerro
        @Override
934
        public boolean requiresLayout() {
935
            // TODO Auto-generated method stub
936
            return false;
937
        }
938 40435 jjdelcerro
939 42362 jjdelcerro
    }
940 40435 jjdelcerro
941 42362 jjdelcerro
    /**
942
     * Return the directory applicaction is installed.
943
     */
944
    public static String getApplicationDirectory() {
945
        return getApplicationFolder().getAbsolutePath();
946
    }
947 40435 jjdelcerro
948
    public static File getApplicationFolder() {
949
        // TODO: check if there is a better way to handle this
950
        return new File(System.getProperty("user.dir"));
951
    }
952
953 42362 jjdelcerro
    private void registerIcons() {
954
        IconTheme theme = PluginServices.getIconTheme();
955
        ClassLoader loader = Launcher.class.getClassLoader();
956 41775 fdiaz
957 42362 jjdelcerro
        String[][] icons = {
958
            // MultiSplashWindow
959
            {"main", "splash-default"},
960
            // NewStatusBar
961
            {"main", "statusbar-info"},
962
            {"main", "statusbar-warning"},
963
            {"main", "statusbar-error"}
964
        };
965
        for (int i = 0; i < icons.length; i++) {
966 41311 jjdelcerro
            try {
967 42362 jjdelcerro
                IconThemeHelper.registerIcon(icons[i][0], icons[i][1], Launcher.class);
968
            } catch (Exception e) {
969
                logger.info("Can't register icon '" + icons[i][0] + "' (" + icons[i][1] + ").");
970 41311 jjdelcerro
            }
971
        }
972 42362 jjdelcerro
        theme.setDefaultIcon(loader.getResource("images/main/default-icon.png"));
973
    }
974 41775 fdiaz
975 42362 jjdelcerro
    private Properties loadProperties(File f) {
976
        FileInputStream fin = null;
977
        Properties p = null;
978
        try {
979
            fin = new FileInputStream(f);
980
            p = new Properties();
981
            p.load(fin);
982
        } catch (IOException ex) {
983
            // Do nothing
984
        }
985
        return p;
986
    }
987
988
    /**
989
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
990
     * la aplicaci?n.
991
     *
992
     * @return Theme
993
     */
994 41312 jjdelcerro
    private Theme getTheme(String pluginsDirectory) {
995
        File infoFile = new File(Launcher.getApplicationFolder(), "package.info");
996
        File themeFile = null;
997
        List<Theme> themes = new ArrayList<Theme>();
998 40435 jjdelcerro
999 41312 jjdelcerro
        // Try to get theme from args
1000
        String name = PluginServices.getArgumentByName("andamiTheme");
1001 42362 jjdelcerro
        if (name != null) {
1002 41312 jjdelcerro
            themeFile = new File(name);
1003
            logger.info("search andami-theme in {}", themeFile.getAbsolutePath());
1004 42362 jjdelcerro
            if (themeFile.exists()) {
1005 41312 jjdelcerro
                Theme theme = new Theme(loadProperties(infoFile));
1006
                theme.readTheme(themeFile);
1007
                logger.info("andami-theme found in {}", themeFile.getAbsolutePath());
1008
                return theme;
1009
            }
1010
        }
1011 40435 jjdelcerro
1012 41312 jjdelcerro
        // Try to get theme from a plugin
1013
        File pluginsDir = new File(pluginsDirectory);
1014 42362 jjdelcerro
        if (!pluginsDir.isAbsolute()) {
1015 41312 jjdelcerro
            pluginsDir = new File(getApplicationFolder(), pluginsDirectory);
1016
        }
1017 42362 jjdelcerro
        if (pluginsDir.exists()) {
1018
            logger.info("search andami-theme in plugins folder '" + pluginsDir.getAbsolutePath() + "'.");
1019 41312 jjdelcerro
            File[] pluginDirs = pluginsDir.listFiles();
1020 42362 jjdelcerro
            if (pluginDirs.length > 0) {
1021
                for (int i = 0; i < pluginDirs.length; i++) {
1022 41775 fdiaz
                    File pluginThemeFile = new File(pluginDirs[i],
1023 41312 jjdelcerro
                            "theme" + File.separator + "andami-theme.xml");
1024 42362 jjdelcerro
                    if (pluginThemeFile.exists()) {
1025 41312 jjdelcerro
                        Theme theme = new Theme(loadProperties(infoFile));
1026
                        theme.readTheme(pluginThemeFile);
1027
                        themes.add(theme);
1028
                    }
1029
                }
1030
            }
1031
        }
1032 40435 jjdelcerro
1033 41312 jjdelcerro
        // Try to get theme from dir gvSIG in user home
1034
        themeFile = new File(getAppHomeDir(), "theme" + File.separator
1035
                + "andami-theme.xml");
1036
        logger.info("search andami-theme in user's home {}", themeFile
1037
                .getAbsolutePath());
1038 42362 jjdelcerro
        if (themeFile.exists()) {
1039 41312 jjdelcerro
            Theme theme = new Theme(loadProperties(infoFile));
1040
            theme.readTheme(themeFile);
1041
            themes.add(theme);
1042
        }
1043 40435 jjdelcerro
1044 41312 jjdelcerro
        // Try to get theme from the instalation dir of gvSIG.
1045
        themeFile = new File(getApplicationDirectory(), "theme"
1046
                + File.separator + "andami-theme.xml");
1047
        logger.info("search andami-theme in installation folder {}", themeFile
1048
                .getAbsolutePath());
1049 42362 jjdelcerro
        if (themeFile.exists()) {
1050 41312 jjdelcerro
            Theme theme = new Theme(loadProperties(infoFile));
1051
            theme.readTheme(themeFile);
1052
            themes.add(theme);
1053
        }
1054 40435 jjdelcerro
1055 41312 jjdelcerro
        Collections.sort(themes, new Comparator<Theme>() {
1056 42362 jjdelcerro
            public int compare(Theme t1, Theme t2) {
1057
                return t2.getPriority() - t1.getPriority();
1058 41312 jjdelcerro
            }
1059
        });
1060 42362 jjdelcerro
        if (logger.isInfoEnabled()) {
1061 41312 jjdelcerro
            logger.info("Found andami-themes in:");
1062 42362 jjdelcerro
            for (Theme theme : themes) {
1063
                logger.info(" - " + theme.getPriority() + ", " + theme.getSource().getAbsolutePath());
1064 41312 jjdelcerro
            }
1065
        }
1066
        Theme theme = themes.get(0);
1067 42362 jjdelcerro
        logger.info("Using theme '" + theme.getSource() + "'.");
1068 41312 jjdelcerro
        return theme;
1069
    }
1070 40435 jjdelcerro
1071 42362 jjdelcerro
    /**
1072
     * Establece los datos que tengamos guardados respecto de la configuracion
1073
     * del proxy.
1074
     */
1075
    private void configureProxy() {
1076
        String host = prefs.get("firewall.http.host", "");
1077
        String port = prefs.get("firewall.http.port", "");
1078 40435 jjdelcerro
1079 42362 jjdelcerro
        System.getProperties().put("http.proxyHost", host);
1080
        System.getProperties().put("http.proxyPort", port);
1081 40435 jjdelcerro
1082 42362 jjdelcerro
        // Ponemos el usuario y clave del proxy, si existe
1083
        String proxyUser = prefs.get("firewall.http.user", null);
1084
        String proxyPassword = prefs.get("firewall.http.password", null);
1085
        if (proxyUser != null) {
1086
            System.getProperties().put("http.proxyUserName", proxyUser);
1087
            System.getProperties().put("http.proxyPassword", proxyPassword);
1088 40435 jjdelcerro
1089 42362 jjdelcerro
            Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
1090
        } else {
1091
            Authenticator.setDefault(new ProxyAuth("", ""));
1092
        }
1093
    }
1094 40435 jjdelcerro
1095 42362 jjdelcerro
    /**
1096
     * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana
1097
     * principal de Andami. TODO Pendiente de ver como se asigna un
1098
     * pluginServices para el launcher.
1099
     *
1100
     * @author LWS
1101
     */
1102
    private void restoreMDIStatus(XMLEntity xml) {
1103
        if (xml == null) {
1104
            xml = new XMLEntity();
1105
        }
1106 40435 jjdelcerro
        // ====================================
1107
        // restore frame size
1108
        Dimension sz = new Dimension(
1109 42362 jjdelcerro
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[0],
1110
                MainFrame.MAIN_FRAME_SIZE_DEFAULT[1]);
1111 40435 jjdelcerro
        if (xml.contains(MainFrame.MAIN_FRAME_SIZE)) {
1112
            int[] wh = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_SIZE);
1113
            sz = new Dimension(wh[0], wh[1]);
1114
        }
1115
        frame.setSize(sz);
1116
        // ==========================================
1117
        // restore frame location
1118
        Point pos = new Point(
1119 42362 jjdelcerro
                MainFrame.MAIN_FRAME_POS_DEFAULT[0],
1120
                MainFrame.MAIN_FRAME_POS_DEFAULT[1]);
1121 40435 jjdelcerro
        if (xml.contains(MainFrame.MAIN_FRAME_POS)) {
1122
            int[] xy = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_POS);
1123
            pos = new Point(xy[0], xy[1]);
1124
        }
1125
        frame.setLocation(pos);
1126
        // =============================================
1127
        // restore frame state (Maximized, minimized, etc);
1128
        int state = MainFrame.MAIN_FRAME_EXT_STATE_DEFAULT;
1129
        if (xml.contains(MainFrame.MAIN_FRAME_EXT_STATE)) {
1130
            state = xml.getIntProperty(MainFrame.MAIN_FRAME_EXT_STATE);
1131
        }
1132
        frame.setExtendedState(state);
1133 42362 jjdelcerro
    }
1134 40435 jjdelcerro
1135 42362 jjdelcerro
    private XMLEntity saveMDIStatus() {
1136
        XMLEntity xml = new XMLEntity();
1137
        // save frame size
1138
        int[] wh = new int[2];
1139
        wh[0] = frame.getWidth();
1140
        wh[1] = frame.getHeight();
1141
        xml.putProperty(MainFrame.MAIN_FRAME_SIZE, wh);
1142
        // save frame location
1143
        int[] xy = new int[2];
1144
        xy[0] = frame.getX();
1145
        xy[1] = frame.getY();
1146
        xml.putProperty(MainFrame.MAIN_FRAME_POS, xy);
1147
        // save frame status
1148
        xml.putProperty(MainFrame.MAIN_FRAME_EXT_STATE,
1149
                frame.getExtendedState());
1150
        return xml;
1151
    }
1152 40435 jjdelcerro
1153 42362 jjdelcerro
    private boolean validJVM() {
1154
        if (!SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_4)) {
1155
            logger.warn("gvSIG requires Java version 1.4 or higher.");
1156
            logger.warn("The Java HOME is '" + SystemUtils.getJavaHome().getAbsolutePath() + "'.");
1157
            return false;
1158
        }
1159
        if (SystemUtils.isJavaAwtHeadless()) {
1160
            logger.warn("The java used by gvSIG does not contain the libraries for access to the graphical interface (AWT-headless)");
1161
            logger.warn("The Java HOME is '" + SystemUtils.getJavaHome().getAbsolutePath() + "'.");
1162
            return false;
1163
        }
1164
        return true;
1165
    }
1166 40435 jjdelcerro
1167 42362 jjdelcerro
    private void loadPluginsPersistence() throws ConfigurationException {
1168
        XMLEntity entity = persistenceFromXML();
1169 40435 jjdelcerro
1170 42362 jjdelcerro
        for (int i = 0; i < entity.getChildrenCount(); i++) {
1171
            XMLEntity plugin = entity.getChild(i);
1172
            String pName = plugin
1173
                    .getStringProperty("com.iver.andami.pluginName");
1174 40435 jjdelcerro
1175 42362 jjdelcerro
            if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
1176
                pName = "org.gvsig.app";
1177
            }
1178
            if (pluginsServices.get(pName) != null) {
1179
                ((PluginServices) pluginsServices.get(pName))
1180
                        .setPersistentXML(plugin);
1181
            } else {
1182
                if (pName.startsWith("Andami.Launcher")) {
1183
                    restoreMDIStatus(plugin);
1184
                }
1185
            }
1186
        }
1187
    }
1188 40435 jjdelcerro
1189 42362 jjdelcerro
    /**
1190
     * Salva la persistencia de los plugins.
1191
     *
1192
     * @author LWS
1193
     */
1194
    private void savePluginPersistence() {
1195
        Iterator<String> i = pluginsConfig.keySet().iterator();
1196 40435 jjdelcerro
1197 42362 jjdelcerro
        XMLEntity entity = new XMLEntity();
1198 40435 jjdelcerro
1199 42362 jjdelcerro
        while (i.hasNext()) {
1200
            String pName = i.next();
1201
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
1202
            XMLEntity ent = ps.getPersistentXML();
1203 40435 jjdelcerro
1204 42362 jjdelcerro
            if (ent != null) {
1205
                ent.putProperty("com.iver.andami.pluginName", pName);
1206
                entity.addChild(ent);
1207
            }
1208
        }
1209
        XMLEntity ent = saveMDIStatus();
1210
        if (ent != null) {
1211
            ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
1212
            entity.addChild(ent);
1213
        }
1214
        try {
1215
            persistenceToXML(entity);
1216
        } catch (ConfigurationException e1) {
1217
            this
1218
                    .addError(
1219
                            Messages
1220
                            .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1221
                            e1);
1222
        }
1223
    }
1224 40435 jjdelcerro
1225 42362 jjdelcerro
    private void installPluginsLabels() {
1226
        Iterator<String> i = pluginsConfig.keySet().iterator();
1227 40435 jjdelcerro
1228 42362 jjdelcerro
        while (i.hasNext()) {
1229
            String name = i.next();
1230
            PluginConfig pc = pluginsConfig.get(name);
1231
            PluginServices ps = (PluginServices) pluginsServices.get(name);
1232 40435 jjdelcerro
1233 42362 jjdelcerro
            LabelSet[] ls = pc.getLabelSet();
1234 40435 jjdelcerro
1235 42362 jjdelcerro
            for (int j = 0; j < ls.length; j++) {
1236
                PluginClassLoader loader = ps.getClassLoader();
1237 40435 jjdelcerro
1238 42362 jjdelcerro
                try {
1239
                    Class clase = loader.loadClass(ls[j].getClassName());
1240
                    frame.setStatusBarLabels(clase, ls[j].getLabel());
1241
                } catch (Throwable e) {
1242
                    this.addError(
1243
                            Messages.getString("Launcher.labelset_class"), e);
1244
                }
1245
            }
1246
        }
1247
    }
1248 40435 jjdelcerro
1249 42362 jjdelcerro
    private String configureSkin(XMLEntity xml, String defaultSkin) {
1250
        if (defaultSkin == null) {
1251
            for (int i = 0; i < xml.getChildrenCount(); i++) {
1252
                if (xml.getChild(i).contains("Skin-Selected")) {
1253
                    String className = xml.getChild(i).getStringProperty(
1254
                            "Skin-Selected");
1255
                    return className;
1256
                }
1257
            }
1258
        }
1259
        // return "com.iver.core.mdiManager.NewSkin";
1260
        return defaultSkin;
1261
    }
1262 40435 jjdelcerro
1263 42362 jjdelcerro
    private void fixSkin(SkinExtension skinExtension,
1264
            PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1265
        // now insert the skin selected.
1266
        MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1267 40435 jjdelcerro
                // MDIManagerFactory.setSkinExtension(se,
1268 42362 jjdelcerro
        // ps.getClassLoader());
1269 40435 jjdelcerro
1270 42362 jjdelcerro
        Class<? extends IExtension> skinClass;
1271 40435 jjdelcerro
1272 42362 jjdelcerro
        try {
1273
            skinClass = (Class<? extends IExtension>) pluginClassLoader
1274
                    .loadClass(skinExtension.getClassName());
1275 40435 jjdelcerro
1276 42362 jjdelcerro
            IExtension skinInstance = skinClass.newInstance();
1277
            ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1278
                    skinInstance, ExtensionDecorator.INACTIVE);
1279
            classesExtensions.put(skinClass, newExtensionDecorator);
1280
        } catch (ClassNotFoundException e) {
1281
            logger.error(Messages
1282
                    .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1283
                    e);
1284
            throw new MDIManagerLoadException(e);
1285
        } catch (InstantiationException e) {
1286
            logger
1287
                    .error(
1288
                            Messages
1289
                            .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1290
                            e);
1291
            throw new MDIManagerLoadException(e);
1292
        } catch (IllegalAccessException e) {
1293
            logger
1294
                    .error(
1295
                            Messages
1296
                            .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1297
                            e);
1298
            throw new MDIManagerLoadException(e);
1299
        }
1300 40435 jjdelcerro
1301 42362 jjdelcerro
    }
1302 40435 jjdelcerro
1303 42362 jjdelcerro
    /**
1304
     * DOCUMENT ME!
1305
     *
1306
     * @throws MDIManagerLoadException
1307
     */
1308
    private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1309
        XMLEntity entity = null;
1310
        try {
1311
            entity = persistenceFromXML();
1312
        } catch (ConfigurationException e1) {
1313
            // TODO Auto-generated catch block
1314
            e1.printStackTrace();
1315
        }
1316
        Iterator<String> i = pluginsConfig.keySet().iterator();
1317 40435 jjdelcerro
1318 42362 jjdelcerro
        SkinExtension skinExtension = null;
1319
        PluginClassLoader pluginClassLoader = null;
1320
        List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1321
        while (i.hasNext()) {
1322
            String name = i.next();
1323
            PluginConfig pc = pluginsConfig.get(name);
1324
            PluginServices ps = pluginsServices.get(name);
1325 40435 jjdelcerro
1326 42362 jjdelcerro
            if (pc.getExtensions().getSkinExtension() != null) {
1327 40435 jjdelcerro
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1328 42362 jjdelcerro
                // logger.warn(Messages.getString(
1329
                // "Launcher.Dos_skin_extension"));
1330
                // }
1331 40435 jjdelcerro
1332 42362 jjdelcerro
                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1333
                for (int numExten = 0; numExten < se.length; numExten++) {
1334
                    skinExtensions.add(se[numExten]);
1335
                }
1336
                for (int j = 0; j < se.length; j++) {
1337
                    String configuredSkin = this.configureSkin(entity,
1338
                            defaultSkin);
1339
                    if ((configuredSkin != null)
1340
                            && configuredSkin.equals(se[j].getClassName())) {
1341
                        skinExtension = se[j];
1342
                        pluginClassLoader = ps.getClassLoader();
1343
                    }
1344
                }
1345
            }
1346
        }
1347 40435 jjdelcerro
1348 42362 jjdelcerro
        if ((skinExtension != null) && (pluginClassLoader != null)) {
1349
            // configured skin was found
1350
            fixSkin(skinExtension, pluginClassLoader);
1351
        } else {
1352
            if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1353
                // try first NewSkin (from CorePlugin)
1354
                skinPlugin("com.iver.core.mdiManager.NewSkin");
1355
            } else if (skinExtensions.size() > 0) {
1356
                // try to load the first skin found
1357
                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1358
                skinPlugin((String) se.getClassName());
1359
            } else {
1360
                throw new MDIManagerLoadException("No Skin-Extension installed");
1361
            }
1362
        }
1363 40435 jjdelcerro
1364 42362 jjdelcerro
    }
1365 40435 jjdelcerro
1366 42362 jjdelcerro
    private static void frameIcon(Theme theme) {
1367
        Iterator<String> i = pluginsConfig.keySet().iterator();
1368 40435 jjdelcerro
1369 42362 jjdelcerro
        while (i.hasNext()) {
1370
            String pName = i.next();
1371
            PluginConfig pc = pluginsConfig.get(pName);
1372
            if (pc.getIcon() != null) {
1373
                if (theme.getIcon() != null) {
1374
                    frame.setIconImage(theme.getIcon().getImage());
1375
                } else {
1376 40435 jjdelcerro
1377 42362 jjdelcerro
                    ImageIcon icon = PluginServices.getIconTheme().get(
1378
                            pc.getIcon().getSrc());
1379
                    frame.setIconImage(icon.getImage());
1380 40435 jjdelcerro
1381 42362 jjdelcerro
                }
1382
                if (theme.getName() != null) {
1383
                    frame.setTitlePrefix(theme.getName());
1384
                } else {
1385
                    frame.setTitlePrefix(pc.getIcon().getText());
1386
                }
1387
                if (theme.getBackgroundImage() != null) {
1388 40435 jjdelcerro
1389 42362 jjdelcerro
                    PluginServices.getMDIManager().setBackgroundImage(
1390
                            theme.getBackgroundImage(), theme.getTypeDesktop());
1391
                }
1392
            }
1393
        }
1394
    }
1395 40435 jjdelcerro
1396 42362 jjdelcerro
    private void initializeExtensions() {
1397 40435 jjdelcerro
1398 42362 jjdelcerro
        List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1399
                pluginsOrdered.size());
1400
        classLoaders.add(getClass().getClassLoader());
1401
        Iterator<String> iter = pluginsOrdered.iterator();
1402 40435 jjdelcerro
1403
                // logger.debug("Initializing plugins libraries: ");
1404 42362 jjdelcerro
        // while (iter.hasNext()) {
1405
        // String pName = (String) iter.next();
1406
        // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1407
        // classLoaders.add(ps.getClassLoader());
1408
        // }
1409
        //
1410
        // // Create the libraries initializer and
1411
        // // initialize the plugin libraries
1412
        // new DefaultLibrariesInitializer(
1413
        // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1414
        // .fullInitialize();
1415
        //
1416
        // // Remove them all, we don't need them anymore
1417
        // classLoaders.clear();
1418
        // classLoaders = null;
1419
        logger.info("Initializing plugins: ");
1420
        // iter = pluginsOrdered.iterator();
1421
        while (iter.hasNext()) {
1422
            String pName = (String) iter.next();
1423
            logger.info("Initializing plugin " + pName);
1424
            PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1425
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
1426 40435 jjdelcerro
1427 42362 jjdelcerro
            Extension[] exts = pc.getExtensions().getExtension();
1428 40435 jjdelcerro
1429 42362 jjdelcerro
            TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1430
                    new ExtensionComparator());
1431 40435 jjdelcerro
1432 42362 jjdelcerro
            for (int j = 0; j < exts.length; j++) {
1433
                if (!exts[j].getActive()) {
1434
                    continue;
1435
                }
1436 40435 jjdelcerro
1437 42362 jjdelcerro
                if (orderedExtensions.contains(exts[j])) {
1438
                    logger.warn("Two extensions with the same priority ("
1439
                            + exts[j].getClassName() + ")");
1440
                }
1441 40435 jjdelcerro
1442 42362 jjdelcerro
                orderedExtensions.add(exts[j]);
1443
            }
1444 40435 jjdelcerro
1445 42362 jjdelcerro
            Iterator<Extension> e = orderedExtensions.iterator();
1446 40435 jjdelcerro
1447 42362 jjdelcerro
            logger.info("Initializing extensions of plugin " + pName + ": ");
1448
            while (e.hasNext()) {
1449
                Extension extension = e.next();
1450
                org.gvsig.andami.plugins.IExtension extensionInstance;
1451 40435 jjdelcerro
1452 42362 jjdelcerro
                try {
1453
                    logger.info("Initializing " + extension.getClassName()
1454
                            + "...");
1455
                    message(extension.getClassName() + "...");
1456
                    Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1457
                            .getClassLoader().loadClass(
1458
                                    extension.getClassName());
1459
                    extensionInstance = extensionClass.newInstance();
1460
                    if (extensionInstance instanceof org.gvsig.andami.plugins.Extension) {
1461
                        ((org.gvsig.andami.plugins.Extension) extensionInstance).setPlugin(ps);
1462
                    } else {
1463
                        logger.warn("The extension " + extensionClass.getName() + " don't extends of Extension.");
1464
                    }
1465 40435 jjdelcerro
1466
                                        // CON DECORATOR
1467 42362 jjdelcerro
                    // ANTES: classesExtensions.put(extensionClass,
1468
                    // extensionInstance);
1469
                    // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1470
                    // instancia para
1471
                    // poder ampliar con nuevas propiedades (AlwaysVisible, por
1472
                    // ejemplo)
1473
                    // Para crear la nueva clase ExtensionDecorator, le pasamos
1474
                    // como par?metro
1475
                    // la extensi?n original que acabamos de crear
1476
                    // 0-> Inactivo, controla la extension
1477
                    // 1-> Siempre visible
1478
                    // 2-> Invisible
1479
                    ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1480
                            extensionInstance, ExtensionDecorator.INACTIVE);
1481
                    classesExtensions
1482
                            .put(extensionClass, newExtensionDecorator);
1483 40435 jjdelcerro
1484 42362 jjdelcerro
                    extensionInstance.initialize();
1485
                    extensions.add(extensionInstance);
1486 40435 jjdelcerro
1487 42362 jjdelcerro
                } catch (NoClassDefFoundError e1) {
1488
                    this.addError("Can't find class extension ("
1489
                            + extension.getClassName() + ")", e1);
1490
                } catch (Throwable e1) {
1491
                    this.addError("Can't initialize extension '"
1492
                            + extension.getClassName() + "'.", e1);
1493
                }
1494
            }
1495
        }
1496
    }
1497 40435 jjdelcerro
1498 42362 jjdelcerro
    private void postInitializeExtensions() {
1499
        logger.info("PostInitializing extensions: ");
1500 40435 jjdelcerro
1501 42362 jjdelcerro
        for (int i = 0; i < extensions.size(); i++) {
1502
            org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1503
                    .get(i);
1504
            String name = extensionInstance.getClass().getName();
1505
            logger.info("PostInitializing " + name + "...");
1506
            message(name + "...");
1507
            try {
1508
                extensionInstance.postInitialize();
1509
            } catch (Throwable ex) {
1510
                this.addError("postInitialize of extension '"
1511
                        + extensionInstance.getClass().getName() + "' failed",
1512
                        ex);
1513
            }
1514
        }
1515
    }
1516 40435 jjdelcerro
1517 42362 jjdelcerro
    private void registerActionOfExtensions(ActionInfoManager actionManager,
1518
            Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1519
        ActionInfo actionInfo;
1520
        while (extensiones.hasMoreElements()) {
1521
            SkinExtensionType extension = extensiones.nextElement();
1522
            Class<? extends IExtension> classExtension;
1523
            try {
1524
                classExtension = (Class<? extends IExtension>) loader
1525
                        .loadClass(extension.getClassName());
1526 40435 jjdelcerro
1527 42362 jjdelcerro
                Enumeration<Action> actions = extension.enumerateAction();
1528
                while (actions.hasMoreElements()) {
1529
                    Action action = actions.nextElement();
1530
                    if (action.getName() == null) {
1531
                        logger.info("invalid action name (null) in " + extension.getClassName() + " of " + loader.toString());
1532
                    } else {
1533
                        actionInfo = actionManager.createAction(
1534
                                classExtension, action.getName(),
1535
                                action.getLabel(), action.getActionCommand(),
1536
                                action.getIcon(), action.getAccelerator(), action.getPosition(),
1537
                                action.getTooltip());
1538
                        actionManager.registerAction(actionInfo);
1539
                        if (action.getPosition() < 100000000) {
1540
                            logger.info("Invalid position in action (" + actionInfo.toString() + ").");
1541
                            action.setPosition(action.getPosition() + 1000000000);
1542
                        }
1543
                    }
1544
                }
1545 40435 jjdelcerro
1546 42362 jjdelcerro
                Enumeration<Menu> menus = extension.enumerateMenu();
1547
                while (menus.hasMoreElements()) {
1548
                    Menu menu = menus.nextElement();
1549
                    if (!menu.getIs_separator()) {
1550
                        actionInfo = actionManager.createAction(
1551
                                classExtension, menu.getName(), menu.getText(),
1552
                                menu.getActionCommand(), menu.getIcon(),
1553
                                menu.getKey(), menu.getPosition(),
1554
                                menu.getTooltip());
1555
                        actionInfo = actionManager.registerAction(actionInfo);
1556
                        if (actionInfo != null) {
1557
                            menu.setActionCommand(actionInfo.getCommand());
1558
                            menu.setTooltip(actionInfo.getTooltip());
1559
                            menu.setIcon(actionInfo.getIconName());
1560
                            menu.setPosition(actionInfo.getPosition());
1561
                            menu.setKey(actionInfo.getAccelerator());
1562
                            menu.setName(actionInfo.getName());
1563
                        }
1564
                    }
1565
                    if (menu.getPosition() < 100000000) {
1566
                        logger.info("Invalid position in menu (" + menu.getText() + ").");
1567
                        menu.setPosition(menu.getPosition() + 1000000000);
1568
                    }
1569 40435 jjdelcerro
1570 42362 jjdelcerro
                }
1571
                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1572
                while (toolBars.hasMoreElements()) {
1573
                    ToolBar toolBar = toolBars.nextElement();
1574 40435 jjdelcerro
1575 42362 jjdelcerro
                    Enumeration<ActionTool> actionTools = toolBar
1576
                            .enumerateActionTool();
1577
                    while (actionTools.hasMoreElements()) {
1578
                        ActionTool actionTool = actionTools.nextElement();
1579
                        actionInfo = actionManager.createAction(
1580
                                classExtension, actionTool.getName(),
1581
                                actionTool.getText(),
1582
                                actionTool.getActionCommand(),
1583
                                actionTool.getIcon(),
1584
                                null,
1585
                                actionTool.getPosition(),
1586
                                actionTool.getTooltip());
1587
                        actionInfo = actionManager.registerAction(actionInfo);
1588
                        if (actionInfo != null) {
1589
                            actionTool.setActionCommand(actionInfo.getCommand());
1590
                            actionTool.setTooltip(actionInfo.getTooltip());
1591
                            actionTool.setIcon(actionInfo.getIconName());
1592
                            actionTool.setPosition(actionInfo.getPosition());
1593
                            actionTool.setName(actionInfo.getName());
1594
                        }
1595
                    }
1596 40435 jjdelcerro
1597 42362 jjdelcerro
                    Enumeration<SelectableTool> selectableTool = toolBar
1598
                            .enumerateSelectableTool();
1599
                    while (selectableTool.hasMoreElements()) {
1600
                        SelectableTool actionTool = selectableTool
1601
                                .nextElement();
1602
                        actionInfo = actionManager.createAction(
1603
                                classExtension, actionTool.getName(),
1604
                                actionTool.getText(),
1605
                                actionTool.getActionCommand(),
1606
                                actionTool.getIcon(),
1607
                                null,
1608
                                actionTool.getPosition(),
1609
                                actionTool.getTooltip());
1610
                        actionInfo = actionManager.registerAction(actionInfo);
1611
                        if (actionInfo != null) {
1612
                            actionTool.setActionCommand(actionInfo.getCommand());
1613
                            actionTool.setTooltip(actionInfo.getTooltip());
1614
                            actionTool.setIcon(actionInfo.getIconName());
1615
                            actionTool.setPosition(actionInfo.getPosition());
1616
                            actionTool.setName(actionInfo.getName());
1617
                        }
1618
                    }
1619
                }
1620
            } catch (ClassNotFoundException e) {
1621
                logger.warn(
1622
                        "Can't register actions of extension '"
1623
                        + extension.getClassName() + "'", e);
1624
            }
1625
        }
1626
    }
1627 41775 fdiaz
1628 42362 jjdelcerro
    @SuppressWarnings("unchecked")
1629
    private void registerActions() {
1630
        logger.info("registerActions");
1631 40435 jjdelcerro
1632 42362 jjdelcerro
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1633
        Iterator<String> it = pluginsConfig.keySet().iterator();
1634 40435 jjdelcerro
1635 42362 jjdelcerro
        while (it.hasNext()) {
1636
            String pluginName = it.next();
1637
            PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1638
            PluginServices pluginService = pluginsServices.get(pluginName);
1639
            PluginClassLoader loader = pluginService.getClassLoader();
1640 40435 jjdelcerro
1641 42362 jjdelcerro
            logger.info("registerActions of plugin '" + pluginName + "'.");
1642 40435 jjdelcerro
1643 42362 jjdelcerro
            Extensions extensionConfig = pluginConfig.getExtensions();
1644 41775 fdiaz
1645 42362 jjdelcerro
            Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1646
            registerActionOfExtensions(actionManager, extensiones, loader);
1647 41775 fdiaz
1648 42362 jjdelcerro
            Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1649
            registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1650 40435 jjdelcerro
1651 42362 jjdelcerro
            PopupMenus pluginPopupMenus = pluginConfig.getPopupMenus();
1652
            if (pluginPopupMenus != null) {
1653
                PopupMenu[] menus1 = pluginPopupMenus.getPopupMenu();
1654
                for (int j = 0; j < menus1.length; j++) {
1655
                    PopupMenu popupMenu = menus1[j];
1656
                    Enumeration<Menu> menus2 = popupMenu.enumerateMenu();
1657
                    while (menus2.hasMoreElements()) {
1658
                        Menu menu = menus2.nextElement();
1659
                        if (!menu.getIs_separator()) {
1660
                            if (menu.getName() == null) {
1661
                                logger.info("Null name for popmenu '" + menu.getText() + "' in plugin " + pluginService.getPluginName());
1662
                            } else {
1663
                                ActionInfo actionInfo = actionManager.getAction(menu.getName());
1664
                                if (actionInfo != null) {
1665
                                    menu.setActionCommand(actionInfo.getCommand());
1666
                                    menu.setTooltip(actionInfo.getTooltip());
1667
                                    menu.setIcon(actionInfo.getIconName());
1668
                                    menu.setPosition(actionInfo.getPosition());
1669
                                    menu.setText(actionInfo.getLabel());
1670
                                    menu.setKey(actionInfo.getAccelerator());
1671
                                }
1672
                            }
1673
                        }
1674
                    }
1675
                }
1676
            }
1677 40435 jjdelcerro
1678 42362 jjdelcerro
        }
1679
    }
1680 40435 jjdelcerro
1681 42362 jjdelcerro
    private TreeSet<SortableMenu> getOrderedMenus() {
1682 41775 fdiaz
1683 42362 jjdelcerro
        TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1684
                new MenuComparator());
1685 40435 jjdelcerro
1686 42362 jjdelcerro
        Iterator<String> i = pluginsConfig.keySet().iterator();
1687 40435 jjdelcerro
1688 42362 jjdelcerro
        while (i.hasNext()) {
1689
            String pName = i.next();
1690
            try {
1691
                PluginServices ps = pluginsServices.get(pName);
1692
                PluginConfig pc = pluginsConfig.get(pName);
1693 41775 fdiaz
1694 42362 jjdelcerro
                Extension[] exts = pc.getExtensions().getExtension();
1695 40435 jjdelcerro
1696 42362 jjdelcerro
                for (int j = 0; j < exts.length; j++) {
1697
                    if (!exts[j].getActive()) {
1698
                        continue;
1699
                    }
1700 40435 jjdelcerro
1701 42362 jjdelcerro
                    Menu[] menus = exts[j].getMenu();
1702 40435 jjdelcerro
1703 42362 jjdelcerro
                    for (int k = 0; k < menus.length; k++) {
1704
                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1705
                                exts[j], menus[k]);
1706 40435 jjdelcerro
1707 42362 jjdelcerro
                        if (orderedMenus.contains(sm)) {
1708
                            this
1709
                                    .addError(Messages
1710
                                            .getString("Launcher.Two_menus_with_the_same_position")
1711
                                            + " - "
1712
                                            + menus[k].getText()
1713
                                            + " - " + exts[j].getClassName());
1714
                        }
1715 40435 jjdelcerro
1716 42362 jjdelcerro
                        orderedMenus.add(sm);
1717
                    }
1718
                }
1719 40435 jjdelcerro
1720 42362 jjdelcerro
                // Se instalan las extensiones de MDI
1721
                SkinExtension[] skinExts = pc.getExtensions()
1722
                        .getSkinExtension();
1723
                for (int j = 0; j < skinExts.length; j++) {
1724 40435 jjdelcerro
1725 42362 jjdelcerro
                    if (skinExts[j] != null) {
1726
                        Menu[] menu = skinExts[j].getMenu();
1727 40435 jjdelcerro
1728 42362 jjdelcerro
                        for (int k = 0; k < menu.length; k++) {
1729
                            SortableMenu sm = new SortableMenu(ps
1730
                                    .getClassLoader(), skinExts[j], menu[k]);
1731 40435 jjdelcerro
1732 42362 jjdelcerro
                            if (orderedMenus.contains(sm)) {
1733
                                this
1734
                                        .addError(Messages
1735
                                                .getString("Launcher.Two_menus_with_the_same_position")
1736
                                                + skinExts[j].getClassName());
1737
                            }
1738 40435 jjdelcerro
1739 42362 jjdelcerro
                            orderedMenus.add(sm);
1740
                        }
1741
                    }
1742
                }
1743 40435 jjdelcerro
1744 42362 jjdelcerro
            } catch (Throwable e) {
1745
                addError("Error initializing menus of plugin '" + pName + "'",
1746
                        e);
1747
            }
1748 40435 jjdelcerro
1749 42362 jjdelcerro
        }
1750 40435 jjdelcerro
1751 42362 jjdelcerro
        return orderedMenus;
1752
    }
1753 40435 jjdelcerro
1754 42362 jjdelcerro
    private void installPluginsMenus() {
1755
        logger.info("installPluginsMenus");
1756 40435 jjdelcerro
1757 42362 jjdelcerro
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1758 40435 jjdelcerro
1759 42362 jjdelcerro
        // Se itera por los menus ordenados
1760
        Iterator<SortableMenu> e = orderedMenus.iterator();
1761 40435 jjdelcerro
1762 42362 jjdelcerro
        // Se ordenan los menues
1763
        while (e.hasNext()) {
1764
            try {
1765
                SortableMenu sm = e.next();
1766
                logger.debug(sm.menu.getPosition() + ":" + sm.menu.getText() + ":" + sm.loader.getPluginName() + ":" + sm.extension.getClassName());
1767
                frame.addMenu(sm.loader, sm.extension, sm.menu);
1768
            } catch (Throwable ex) {
1769
                this.addError(
1770
                        Messages.getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1771
                        ex
1772
                );
1773
            }
1774
        }
1775
    }
1776 40435 jjdelcerro
1777 42362 jjdelcerro
    public class PluginMenuItem {
1778 40435 jjdelcerro
1779 42362 jjdelcerro
        private Menu menu;
1780
        private PluginClassLoader loader;
1781
        private SkinExtensionType extension;
1782 40435 jjdelcerro
1783 42362 jjdelcerro
        PluginMenuItem(PluginClassLoader loader,
1784
                SkinExtensionType extension, Menu menu) {
1785
            this.menu = menu;
1786
            this.loader = loader;
1787
            this.extension = extension;
1788
        }
1789 40435 jjdelcerro
1790 42362 jjdelcerro
        public PluginServices getPlugin() {
1791
            String pluginName = loader.getPluginName();
1792
            return PluginServices.getPluginServices(pluginName);
1793
        }
1794 40435 jjdelcerro
1795 42362 jjdelcerro
        public String getExtensionName() {
1796
            return this.extension.getClassName();
1797
        }
1798 41775 fdiaz
1799 42362 jjdelcerro
        public IExtension getExtension() {
1800
            Class<?> extensionClass;
1801
            try {
1802
                extensionClass = loader.loadClass(this.extension.getClassName());
1803
            } catch (ClassNotFoundException e) {
1804
                return null;
1805
            }
1806
            return PluginServices.getExtension(extensionClass);
1807
        }
1808 41775 fdiaz
1809 42362 jjdelcerro
        public String getText() {
1810
            return this.menu.getText();
1811
        }
1812 41775 fdiaz
1813 42362 jjdelcerro
        public long getPosition() {
1814
            return this.menu.getPosition();
1815
        }
1816 41775 fdiaz
1817 42362 jjdelcerro
        public String getName() {
1818
            return this.menu.getName();
1819
        }
1820 40435 jjdelcerro
1821 42362 jjdelcerro
        public boolean isParent() {
1822
            return menu.getIs_separator();
1823
        }
1824 41775 fdiaz
1825 42362 jjdelcerro
        public String getPluginName() {
1826
            return this.loader.getPluginName();
1827
        }
1828 41775 fdiaz
1829 42362 jjdelcerro
        public ActionInfo getAction() {
1830
            ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1831
            return manager.getAction(this.menu.getName());
1832
        }
1833
    }
1834 41775 fdiaz
1835 42362 jjdelcerro
    public List<PluginMenuItem> getPluginMenuItems() {
1836
        List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1837 41775 fdiaz
1838 42362 jjdelcerro
        TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1839
        Iterator<SortableMenu> e = orderedMenus.iterator();
1840
        while (e.hasNext()) {
1841
            SortableMenu sm = e.next();
1842
            PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1843
            menuItems.add(item);
1844
        }
1845
        return menuItems;
1846
    }
1847 41775 fdiaz
1848 42362 jjdelcerro
    /**
1849
     * Installs the menus, toolbars, actiontools, selectable toolbars and
1850
     * combos. The order in which they are shown is determined here.
1851
     */
1852
    private void installPluginsControls() {
1853
        logger.info("installPluginsControls (toolbars)");
1854 40435 jjdelcerro
1855 42362 jjdelcerro
        Iterator<String> i = pluginsConfig.keySet().iterator();
1856 40435 jjdelcerro
1857 42362 jjdelcerro
        Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1858
        Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1859
        Set<Extension> orderedExtensions = new TreeSet<Extension>(
1860
                new ExtensionComparator());
1861 41775 fdiaz
1862 40435 jjdelcerro
                // First of all, sort the extensions.
1863 42362 jjdelcerro
        // We need to iterate on the plugins, and iterate on each plugin's
1864
        // extensions
1865
        // (each plugin may contain one or more extensions)
1866
        while (i.hasNext()) { // iterate on the plugins
1867
            String pName = i.next();
1868
            try {
1869
                PluginConfig pc = pluginsConfig.get(pName);
1870
                PluginServices ps = pluginsServices.get(pName);
1871 40435 jjdelcerro
1872 42362 jjdelcerro
                Extension[] exts = pc.getExtensions().getExtension();
1873 40435 jjdelcerro
1874 42362 jjdelcerro
                for (int j = 0; j < exts.length; j++) { // iterate on the
1875
                    // extensions
1876
                    String cname = "unknow";
1877
                    try {
1878
                        cname = exts[j].getClassName();
1879
                        if (exts[j].getActive()
1880
                                && !cname.equals(LibraryExtension.class
1881
                                        .getName())) {
1882
                            if (orderedExtensions.contains(exts[j])) {
1883
                                this
1884
                                        .addError(Messages
1885
                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1886
                                                + cname);
1887
                            }
1888 40435 jjdelcerro
1889 42362 jjdelcerro
                            orderedExtensions.add(exts[j]);
1890
                            extensionPluginServices.put(exts[j], ps);
1891
                            extensionPluginConfig.put(exts[j], pc);
1892
                        }
1893
                    } catch (Throwable e) {
1894
                        addError("Error initializing controls of plugin '"
1895
                                + pName + "' extension '" + cname + "'", e);
1896
                    }
1897
                }
1898
            } catch (Throwable e) {
1899
                addError("Error initializing controls of plugin '" + pName
1900
                        + "'", e);
1901
            }
1902
        }
1903 40435 jjdelcerro
1904 42362 jjdelcerro
        TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1905
                new ToolComparator());
1906
        Iterator<Extension> e = orderedExtensions.iterator();
1907 40435 jjdelcerro
1908
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1909 42362 jjdelcerro
        // selectabletools)
1910
        // and load the combo-scales and combo-buttons for the status bar
1911
        while (e.hasNext()) {
1912
            Extension ext = e.next();
1913
            String extName = "unknow";
1914
            try {
1915
                extName = ext.getClassName();
1916
                ToolBar[] toolbars = ext.getToolBar();
1917 40435 jjdelcerro
1918 42362 jjdelcerro
                // get tools from toolbars
1919
                for (int k = 0; k < toolbars.length; k++) {
1920
                    ActionTool[] tools = toolbars[k].getActionTool();
1921 40435 jjdelcerro
1922 42362 jjdelcerro
                    for (int t = 0; t < tools.length; t++) {
1923
                        SortableTool sm = new SortableTool(
1924
                                (extensionPluginServices.get(ext))
1925
                                .getClassLoader(), ext, toolbars[k],
1926
                                tools[t]);
1927
                        orderedTools.add(sm);
1928
                    }
1929 40435 jjdelcerro
1930 42362 jjdelcerro
                    SelectableTool[] sTools = toolbars[k].getSelectableTool();
1931 40435 jjdelcerro
1932 42362 jjdelcerro
                    for (int t = 0; t < sTools.length; t++) {
1933
                        SortableTool sm = new SortableTool(
1934
                                (extensionPluginServices.get(ext))
1935
                                .getClassLoader(), ext, toolbars[k],
1936
                                sTools[t]);
1937
                        orderedTools.add(sm);
1938
                    }
1939
                }
1940 40435 jjdelcerro
1941 42362 jjdelcerro
                // get controls for statusBar
1942
                PluginServices ps = extensionPluginServices.get(ext);
1943
                PluginClassLoader loader = ps.getClassLoader();
1944 40435 jjdelcerro
1945 42362 jjdelcerro
                // ArrayList componentList = new ArrayList();
1946
                ComboScale[] comboScaleArray = ext.getComboScale();
1947
                for (int k = 0; k < comboScaleArray.length; k++) {
1948
                    org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1949
                    String label = comboScaleArray[k].getLabel();
1950
                    if (label != null) {
1951
                        combo.setLabel(label);
1952
                    }
1953
                    String name = comboScaleArray[k].getName();
1954
                    if (name != null) {
1955
                        combo.setName(name);
1956
                    }
1957
                    String[] elementsString = ((String) comboScaleArray[k]
1958
                            .getElements()).split(";");
1959
                    long[] elements = new long[elementsString.length];
1960
                    for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
1961
                        try {
1962
                            elements[currentElem] = Long
1963
                                    .parseLong(elementsString[currentElem]);
1964
                        } catch (NumberFormatException nfex1) {
1965
                            this
1966
                                    .addError(ext.getClassName()
1967
                                            + " -- "
1968
                                            + Messages
1969
                                            .getString("error_parsing_comboscale_elements"));
1970
                            elements[currentElem] = 0;
1971
                        }
1972
                    }
1973
                    combo.setItems(elements);
1974
                    try {
1975
                        long value = Long.parseLong((String) comboScaleArray[k]
1976
                                .getValue());
1977
                        combo.setScale(value);
1978
                    } catch (NumberFormatException nfex2) {
1979
                        this
1980
                                .addError(ext.getClassName()
1981
                                        + " -- "
1982
                                        + Messages
1983
                                        .getString("error_parsing_comboscale_value"));
1984
                    }
1985
                    try {
1986
                        frame.addStatusBarControl(loader.loadClass(ext
1987
                                .getClassName()), combo);
1988
                    } catch (ClassNotFoundException e1) {
1989
                        this
1990
                                .addError(
1991
                                        Messages
1992
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1993
                                        e1);
1994
                    }
1995
                }
1996 40435 jjdelcerro
1997 42362 jjdelcerro
                ComboButton[] comboButtonArray = ext.getComboButton();
1998
                for (int k = 0; k < comboButtonArray.length; k++) {
1999
                    ComboButtonElement[] elementList = comboButtonArray[k]
2000
                            .getComboButtonElement();
2001
                    org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
2002
                    String name = comboButtonArray[k].getName();
2003
                    if (name != null) {
2004
                        combo.setName(name);
2005
                    }
2006
                    for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
2007
                        ComboButtonElement element = elementList[currentElement];
2008
                        ImageIcon icon;
2009
                        URL iconLocation = loader
2010
                                .getResource(element.getIcon());
2011
                        if (iconLocation == null) {
2012
                            this.addError(Messages.getString("Icon_not_found_")
2013
                                    + element.getIcon());
2014
                        } else {
2015
                            icon = new ImageIcon(iconLocation);
2016
                            JButton button = new JButton(icon);
2017
                            combo.addButton(button);
2018
                            button.setActionCommand(element.getActionCommand());
2019
                        }
2020
                    }
2021
                    try {
2022
                        frame.addStatusBarControl(loader.loadClass(ext
2023
                                .getClassName()), combo);
2024
                    } catch (ClassNotFoundException e1) {
2025
                        this
2026
                                .addError(
2027
                                        Messages
2028
                                        .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
2029
                                        e1);
2030
                    }
2031
                }
2032
            } catch (Throwable e2) {
2033
                addError(
2034
                        "Error initializing tools and status bars of extension '"
2035
                        + extName + "'", e2);
2036
            }
2037
        }
2038 40435 jjdelcerro
2039
                // Add the tools from MDI extensions to the ordered tool-list, so that
2040 42362 jjdelcerro
        // we get a sorted list containing all the tools
2041
        i = pluginsConfig.keySet().iterator();
2042
        while (i.hasNext()) {
2043
            String pName = (String) i.next();
2044
            try {
2045
                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
2046
                PluginServices ps = (PluginServices) pluginsServices.get(pName);
2047 40435 jjdelcerro
2048 42362 jjdelcerro
                SkinExtension[] skinExts = pc.getExtensions()
2049
                        .getSkinExtension();
2050
                for (int j = 0; j < skinExts.length; j++) {
2051 40435 jjdelcerro
2052 42362 jjdelcerro
                    if (skinExts[j] != null) {
2053
                        ToolBar[] toolbars = skinExts[j].getToolBar();
2054 40435 jjdelcerro
2055 42362 jjdelcerro
                        for (int k = 0; k < toolbars.length; k++) {
2056
                            ActionTool[] tools = toolbars[k].getActionTool();
2057 40435 jjdelcerro
2058 42362 jjdelcerro
                            for (int t = 0; t < tools.length; t++) {
2059
                                SortableTool stb = new SortableTool(ps
2060
                                        .getClassLoader(), skinExts[j],
2061
                                        toolbars[k], tools[t]);
2062
                                orderedTools.add(stb);
2063
                            }
2064 40435 jjdelcerro
2065 42362 jjdelcerro
                            SelectableTool[] sTools = toolbars[k]
2066
                                    .getSelectableTool();
2067 40435 jjdelcerro
2068 42362 jjdelcerro
                            for (int t = 0; t < sTools.length; t++) {
2069
                                SortableTool stb = new SortableTool(ps
2070
                                        .getClassLoader(), skinExts[j],
2071
                                        toolbars[k], sTools[t]);
2072
                                orderedTools.add(stb);
2073
                            }
2074
                        }
2075
                    }
2076
                }
2077
                // Install popup menus
2078
                PopupMenus pus = pc.getPopupMenus();
2079
                if (pus != null) {
2080
                    PopupMenu[] menus = pus.getPopupMenu();
2081
                    for (int j = 0; j < menus.length; j++) {
2082
                        String menuName = "(unknow)";
2083
                        try {
2084
                            menuName = menus[j].getName();
2085
                            frame.addPopupMenu(ps.getClassLoader(), menus[j]);
2086
                        } catch (Throwable ex) {
2087
                            addError("Error adding popup menu' " + menuName + "' in plugin '" + pName + "'.");
2088
                        }
2089
                    }
2090
                }
2091
            } catch (Throwable e3) {
2092
                addError("Error initializing skins of the plugin '" + pName
2093
                        + "'", e3);
2094
            }
2095
        }
2096 40435 jjdelcerro
2097
                // loop on the ordered extension list, to add them to the interface in
2098 42362 jjdelcerro
        // an ordered way
2099
        Iterator<SortableTool> t = orderedTools.iterator();
2100
        while (t.hasNext()) {
2101
            SortableTool stb = t.next();
2102
            try {
2103
                if (stb.actiontool != null) {
2104
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2105
                            stb.actiontool);
2106
                } else {
2107
                    frame.addTool(stb.loader, stb.extension, stb.toolbar,
2108
                            stb.selectabletool);
2109
                }
2110
            } catch (ClassNotFoundException ex) {
2111
                this
2112
                        .addError(
2113
                                Messages
2114
                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
2115
                                ex);
2116
            } catch (Throwable e2) {
2117
                addError("Error adding tools to the interface of extension '"
2118
                        + stb.extension.getClassName() + "'", e2);
2119
            }
2120
        }
2121
    }
2122 40435 jjdelcerro
2123 42362 jjdelcerro
    /**
2124
     * Adds new plugins to the the andami-config file.
2125
     */
2126
    private void updateAndamiConfig() {
2127
        Set<String> olds = new HashSet<String>();
2128 40435 jjdelcerro
2129 42362 jjdelcerro
        Plugin[] plugins = andamiConfig.getPlugin();
2130 40435 jjdelcerro
2131 42362 jjdelcerro
        for (int i = 0; i < plugins.length; i++) {
2132
            olds.add(plugins[i].getName());
2133
        }
2134 40435 jjdelcerro
2135 42362 jjdelcerro
        Iterator<PluginServices> i = pluginsServices.values().iterator();
2136 40435 jjdelcerro
2137 42362 jjdelcerro
        while (i.hasNext()) {
2138
            PluginServices ps = i.next();
2139 40435 jjdelcerro
2140 42362 jjdelcerro
            if (!olds.contains(ps.getPluginName())) {
2141
                Plugin p = new Plugin();
2142
                p.setName(ps.getPluginName());
2143
                p.setUpdate(false);
2144 40435 jjdelcerro
2145 42362 jjdelcerro
                andamiConfig.addPlugin(p);
2146
            }
2147
        }
2148
    }
2149 41775 fdiaz
2150 42362 jjdelcerro
    private URL[] getPluginClasspathURLs(PluginConfig pluginConfig) {
2151
        URL[] urls = null;
2152 40435 jjdelcerro
2153 42362 jjdelcerro
        String libfolderPath = pluginConfig.getLibraries().getLibraryDir();
2154
        File libFolderFile = new File(pluginConfig.getPluginFolder(), libfolderPath);
2155 40435 jjdelcerro
2156 42362 jjdelcerro
        File[] files = libFolderFile.listFiles(new FileFilter() {
2157 40435 jjdelcerro
2158 42362 jjdelcerro
            public boolean accept(File pathname) {
2159
                return (pathname.getName().toUpperCase().endsWith(".JAR")
2160
                        || pathname.getName().toUpperCase().endsWith(".ZIP"));
2161
            }
2162
        });
2163
        if (files == null) {
2164
            urls = new URL[0];
2165
        } else {
2166
            urls = new URL[files.length];
2167
            for (int j = 0; j < files.length; j++) {
2168
                try {
2169
                    urls[j] = new URL("file:" + files[j]);
2170
                } catch (MalformedURLException e) {
2171
                    logger.warn("Can't add file '" + files[j] + "' to the classpath of plugin '" + pluginConfig.getPluginName() + "'.");
2172 41706 jjdelcerro
                }
2173
            }
2174
        }
2175 42362 jjdelcerro
        return urls;
2176
    }
2177 40435 jjdelcerro
2178 42364 jjdelcerro
    private static class OrderedPlugins extends ArrayList<String> {
2179
2180
        private List<String> problems = new ArrayList<String>();
2181
        private int retries = 0;
2182
        private PluginsConfig pluginsConfig = null;
2183
        private List<String> deprcatedPluginNames = null;
2184
2185
        OrderedPlugins(PluginsConfig pluginsConfig, List<String>deprcatedPluginNames) {
2186
            super();
2187
            this.pluginsConfig = pluginsConfig;
2188
            this.deprcatedPluginNames = deprcatedPluginNames;
2189
            List<String> pluginNames = new ArrayList<String>();
2190
            for (String pluginName : pluginsConfig.keySet()) {
2191
                pluginNames.add(pluginName);
2192
            }
2193
            Collections.sort(pluginNames);
2194
            for (String pluginName : pluginNames) {
2195
                this.add(pluginName);
2196
            }
2197
        }
2198
2199
        public List<String> getProblems() {
2200
            return this.problems;
2201
        }
2202
2203
        private void addProblem(String msg) {
2204
           this.problems.add(msg);
2205
        }
2206
2207
        public boolean add(String pluginName) {
2208
            return this.add(pluginName,new ArrayList<String>());
2209
        }
2210
2211
        private boolean add(String pluginName, List<String>processing) {
2212
            pluginName = this.pluginsConfig.getMainKey(pluginName);
2213
            if( this.contains(pluginName) ) {
2214
                return true;
2215
            }
2216
            if( processing.contains(pluginName) ) {
2217
                this.addProblem("Dependencias ciclicas procesando '"+pluginName+"'.");
2218
                return true;
2219
            }
2220
            PluginConfig pluginConfig = this.pluginsConfig.get(pluginName);
2221
            Depends[] dependencies = pluginConfig.getDepends();
2222
            if( dependencies.length==0 ) {
2223
               super.add(pluginName);
2224
               return true;
2225
            }
2226
            if( this.retries > 100 ) {
2227
               this.addProblem("Posible dependencias ciclicas procesando '"+pluginName+"'." );
2228
               return false;
2229
            }
2230
            processing.add(pluginName);
2231
            boolean dependenciesAvailables = true;
2232
            for (Depends dependency : dependencies) {
2233
                String dependencyName = dependency.getPluginName();
2234
                if (deprcatedPluginNames.contains(dependencyName)) {
2235
                    this.addProblem("Plugin '" + pluginName + "' use a deprecated plugin name '" + dependencyName + "' as dependency. Must use '" + pluginsConfig.getMainKey(dependencyName) + "'.");
2236
                }
2237
                PluginConfig dependencyConfig = this.pluginsConfig.get(dependencyName);
2238
                if( dependencyConfig == null) {
2239
                  if( dependency.getOptional() ) {
2240
                    this.addProblem("Plugin '" + pluginName + "', declare an optional dependency '" + dependencyName + "' that not found.");
2241 42362 jjdelcerro
                    continue;
2242 42364 jjdelcerro
                  }
2243
                  dependenciesAvailables = false;
2244
                  this.addProblem("Plugin '"+pluginName+"' declara a dependency '"+dependencyName+"' that not found.");
2245
                  continue;
2246 42362 jjdelcerro
                }
2247 42364 jjdelcerro
                this.retries++;
2248
                if( ! (this.add(dependencyName, processing)) ) {
2249
                  dependenciesAvailables = false;
2250
                }
2251
                this.retries--;
2252
            }
2253
            if( dependenciesAvailables ) {
2254
                super.add(pluginName);
2255
            } else {
2256
              this.addProblem("Plugin '"+pluginName+"' no disponible, alguna dependencia no resuelta.");
2257
              return false;
2258
            }
2259
            return true;
2260
        }
2261
    }
2262
2263
    private void loadPluginServices() {
2264
        OrderedPlugins orderedPlugins = new OrderedPlugins(pluginsConfig, getDeprecatedPluginNames());
2265
2266
        if( !orderedPlugins.getProblems().isEmpty() ) {
2267
            for (String problem : orderedPlugins.getProblems()) {
2268
                logger.warn(problem);
2269
            }
2270
        }
2271 40435 jjdelcerro
2272 42364 jjdelcerro
        for (String pluginName : orderedPlugins) {
2273
            PluginConfig config = pluginsConfig.get(pluginName);
2274 40435 jjdelcerro
2275 42364 jjdelcerro
            URL[] urls = getPluginClasspathURLs(config);
2276
2277
            List<PluginClassLoader> loaders = new ArrayList<PluginClassLoader>();
2278
            for (Depends dependency : config.getDepends()) {
2279
                String dependencyName = dependency.getPluginName();
2280
                PluginServices dependencyPluginService = pluginsServices.get(dependencyName);
2281
                if( dependencyPluginService == null ) {
2282
                    if( dependency.getOptional() ) {
2283
                        logger.info("Procesing plugin '"+pluginName+", optional dependency not found ("+dependencyName+").");
2284 42362 jjdelcerro
                    } else {
2285 42364 jjdelcerro
                        logger.warn("Procesing plugin '"+pluginName+", dependency not found ("+dependencyName+").");
2286 42362 jjdelcerro
                    }
2287
                    continue;
2288
                }
2289 42364 jjdelcerro
                loaders.add(dependencyPluginService.getClassLoader());
2290 42362 jjdelcerro
            }
2291 42364 jjdelcerro
            try {
2292
                PluginClassLoader loader = new PluginClassLoader(
2293
                        urls,
2294
                        config.getPluginFolder().getAbsolutePath(),
2295
                        Launcher.class.getClassLoader(),
2296
                        loaders
2297
                );
2298
                PluginServices ps = new PluginServices(
2299
                        loader,
2300
                        PluginsConfig.getAlternativeNames(config)
2301
                );
2302
                logger.info("Plugin '" + pluginName + "' created");
2303
                pluginsServices.put(ps.getPluginName(), ps);
2304
                pluginsOrdered.add(pluginName);
2305
            } catch (IOException ex) {
2306
                logger.warn("Can't create PluginServices for '" + pluginName + "'.", ex);
2307 42362 jjdelcerro
            }
2308
        }
2309 42364 jjdelcerro
2310 42362 jjdelcerro
        // Se eliminan los plugins que no fueron instalados
2311 42364 jjdelcerro
        List<String> pluginsToRemove = new ArrayList<String>();
2312
        for (String pluginName : pluginsConfig.keySet()) {
2313
            PluginServices pluginService = pluginsServices.get(pluginName);
2314
            if( pluginService == null ) {
2315
                pluginsToRemove.add(pluginName);
2316
            }
2317 42362 jjdelcerro
        }
2318 42364 jjdelcerro
        for (String pluginName : pluginsToRemove) {
2319
            logger.warn("Removed plugin "+pluginName+".");
2320
            pluginsConfig.remove(pluginName);
2321
       }
2322 42362 jjdelcerro
    }
2323 42364 jjdelcerro
2324
    /*
2325 42362 jjdelcerro
    private void dumpPluginsDependencyInformation() {
2326
        logger.info("Plugin dependency information");
2327
        Iterator<String> i = pluginsConfig.keySet().iterator();
2328
        while (i.hasNext()) {
2329
            String pluginName = i.next();
2330
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2331
            logger.info("  Plugin " + pluginName);
2332
            Depends[] dependencies = config.getDepends();
2333
            for (int j = 0; j < dependencies.length; j++) {
2334
                Depends dependency = dependencies[j];
2335
                String dependencyName = dependency.getPluginName();
2336
                logger.info("    Dependency " + dependencyName);
2337
            }
2338
        }
2339
    }
2340 42364 jjdelcerro
    */
2341 42362 jjdelcerro
    private void pluginsMessages() {
2342
        Iterator<String> iterator = pluginsOrdered.iterator();
2343
        PluginConfig config;
2344
        PluginServices ps;
2345 40435 jjdelcerro
2346 42362 jjdelcerro
        while (iterator.hasNext()) {
2347
            String pluginName = iterator.next();
2348
            config = pluginsConfig.get(pluginName);
2349
            ps = pluginsServices.get(pluginName);
2350 40435 jjdelcerro
2351 42362 jjdelcerro
            if ((config.getResourceBundle() != null)
2352
                    && !config.getResourceBundle().getName().equals("")) {
2353
                // add the locale files associated with the plugin
2354
                org.gvsig.i18n.Messages.addResourceFamily(config
2355
                        .getResourceBundle().getName(), ps.getClassLoader(),
2356
                        pluginName);
2357
                org.gvsig.i18n.Messages.addResourceFamily("i18n." + config
2358
                        .getResourceBundle().getName(), ps.getClassLoader(),
2359
                        pluginName);
2360
            }
2361
        }
2362
    }
2363 40435 jjdelcerro
2364 42362 jjdelcerro
    static public PluginServices getPluginServices(String name) {
2365
        return (PluginServices) pluginsServices.get(name);
2366
    }
2367 40435 jjdelcerro
2368 42362 jjdelcerro
    static String getPluginsDir() {
2369
        return andamiConfig.getPluginsDirectory();
2370
    }
2371 41775 fdiaz
2372 42362 jjdelcerro
    static File getPluginFolder(String pluginName) {
2373
        return pluginsConfig.get(pluginName).getPluginFolder();
2374
    }
2375 40435 jjdelcerro
2376 42362 jjdelcerro
    static void setPluginsDir(String s) {
2377
        andamiConfig.setPluginsDirectory(s);
2378
    }
2379 40435 jjdelcerro
2380 42362 jjdelcerro
    static MDIFrame getMDIFrame() {
2381
        return frame;
2382
    }
2383 40435 jjdelcerro
2384 42362 jjdelcerro
    private PluginsConfig loadPluginConfigs() {
2385
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
2386
        List<File> repositoriesFolders = installerManager.getLocalAddonRepositories("plugin");
2387
        for (File repositoryFolder : repositoriesFolders) {
2388
            logger.info("Loading plugins configuration from repository folder " + repositoryFolder.getAbsolutePath() + ".");
2389 41775 fdiaz
2390 42362 jjdelcerro
            if (!repositoryFolder.exists()) {
2391
                logger.warn("Plugins repository folder not found '" + repositoryFolder.getAbsolutePath() + "'.");
2392
                continue;
2393
            }
2394 40435 jjdelcerro
2395 42362 jjdelcerro
            File[] pluginsFolders = repositoryFolder.listFiles();
2396
            if (pluginsFolders.length == 0) {
2397
                logger.info("Plugins repository folder is empty '" + repositoryFolder.getAbsolutePath() + "'.");
2398
                continue;
2399
            }
2400
2401
            for (int i = 0; i < pluginsFolders.length; i++) {
2402
                File pluginFolder = pluginsFolders[i];
2403
                if (!pluginFolder.isDirectory()) {
2404 41706 jjdelcerro
                    continue;
2405
                }
2406 42362 jjdelcerro
                String pluginName = pluginFolder.getName();
2407
                File pluginConfigFile = new File(pluginFolder, "config.xml");
2408
                if (!pluginConfigFile.exists()) {
2409
                    logger.info("Plugin '" + pluginName + "' not has a config.xml file (" + pluginConfigFile.getAbsolutePath() + ".");
2410 41706 jjdelcerro
                    continue;
2411
                }
2412 42362 jjdelcerro
                try {
2413
                    FileInputStream is = new FileInputStream(pluginConfigFile);
2414
                    Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2415
                    if (xml == null) {
2416
                        // the encoding was not correctly detected, use system default
2417
                        xml = new FileReader(pluginConfigFile);
2418
                    } else {
2419
                        // use a buffered reader to improve performance
2420
                        xml = new BufferedReader(xml);
2421 41706 jjdelcerro
                    }
2422 42362 jjdelcerro
                    PluginConfig pluginConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2423
                    pluginConfig.setPluginName(pluginName);
2424
                    pluginConfig.setPluginFolder(pluginFolder);
2425
                    pluginsConfig.put(pluginName, pluginConfig);
2426 40435 jjdelcerro
2427 42362 jjdelcerro
                } catch (FileNotFoundException e) {
2428
                    logger.info("Can't read plugin config file from plugin '" + pluginName + "' ('" + pluginConfigFile.getAbsolutePath() + ").");
2429 40435 jjdelcerro
2430 42362 jjdelcerro
                } catch (MarshalException e) {
2431
                    logger.warn("Can't load plugin the config file from plugin '" + pluginName + "' is incorect. " + e.getMessage() + " ('" + pluginConfigFile.getAbsolutePath() + ").", e);
2432 40435 jjdelcerro
2433 42362 jjdelcerro
                } catch (ValidationException e) {
2434
                    logger.warn("Can't load plugin the config file from plugin '" + pluginName + "' is invalid. " + e.getMessage() + " ('" + pluginConfigFile.getAbsolutePath() + ").", e);
2435 41706 jjdelcerro
2436
                }
2437
            }
2438
        }
2439 42362 jjdelcerro
        return pluginsConfig;
2440
    }
2441 41706 jjdelcerro
2442 42362 jjdelcerro
    private static Locale getLocale(String language, String country,
2443
            String variant) {
2444
        if (variant != null) {
2445
            return new Locale(language, country, variant);
2446
        } else if (country != null) {
2447
            return new Locale(language, country);
2448
        } else if (language != null) {
2449
            return new Locale(language);
2450
        } else {
2451
            return new Locale("es");
2452
        }
2453
    }
2454 40435 jjdelcerro
2455 42362 jjdelcerro
    private static void andamiConfigToXML(String file) throws IOException,
2456
            MarshalException, ValidationException {
2457 40435 jjdelcerro
                // write on a temporary file in order to not destroy current file if
2458 42362 jjdelcerro
        // there is some problem while marshaling
2459
        File tmpFile = new File(file + "-"
2460
                + DateTime.getCurrentDate().getTime());
2461
        File xml = new File(file);
2462
        File parent = xml.getParentFile();
2463
        parent.mkdirs();
2464 40435 jjdelcerro
2465 42362 jjdelcerro
        BufferedOutputStream os = new BufferedOutputStream(
2466
                new FileOutputStream(tmpFile));
2467
        OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2468
        andamiConfig.marshal(writer);
2469
        writer.close();
2470 40435 jjdelcerro
2471
                // if marshaling process finished correctly, move the file to the
2472 42362 jjdelcerro
        // correct one
2473
        xml.delete();
2474
        if (!tmpFile.renameTo(xml)) {
2475
            // if rename was not succesful, try copying it
2476
            FileChannel sourceChannel = new FileInputStream(tmpFile)
2477
                    .getChannel();
2478
            FileChannel destinationChannel = new FileOutputStream(xml)
2479
                    .getChannel();
2480
            sourceChannel.transferTo(0, sourceChannel.size(),
2481
                    destinationChannel);
2482
            sourceChannel.close();
2483
            destinationChannel.close();
2484
        }
2485
    }
2486 40435 jjdelcerro
2487 42362 jjdelcerro
    private static void andamiConfigFromXML(String file)
2488
            throws ConfigurationException {
2489
        File xml = new File(file);
2490 40435 jjdelcerro
2491 42362 jjdelcerro
        InputStreamReader reader = null;
2492
        try {
2493
            // Se lee la configuraci?n
2494
            reader = XMLEncodingUtils.getReader(xml);
2495
            andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2496
        } catch (FileNotFoundException e) {
2497
            // Si no existe se ponen los valores por defecto
2498
            andamiConfig = getDefaultAndamiConfig();
2499
        } catch (MarshalException e) {
2500
            // try to close the stream, maybe it remains open
2501
            if (reader != null) {
2502
                try {
2503
                    reader.close();
2504
                } catch (IOException e1) {
2505
                }
2506
            }
2507 40435 jjdelcerro
                        // if there was a problem reading the file, backup it and create a
2508 42362 jjdelcerro
            // new one with default values
2509
            String backupFile = file + "-"
2510
                    + DateTime.getCurrentDate().getTime();
2511
            NotificationManager
2512
                    .addError(
2513
                            Messages
2514
                            .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2515
                            + backupFile, new ConfigurationException(e));
2516
            xml.renameTo(new File(backupFile));
2517
            andamiConfig = getDefaultAndamiConfig();
2518
        } catch (ValidationException e) {
2519
            throw new ConfigurationException(e);
2520
        }
2521
    }
2522 40435 jjdelcerro
2523 42362 jjdelcerro
    private static AndamiConfig getDefaultAndamiConfig() {
2524
        AndamiConfig andamiConfig = new AndamiConfig();
2525 40435 jjdelcerro
2526 42362 jjdelcerro
        Andami andami = new Andami();
2527
        andami.setUpdate(true);
2528
        andamiConfig.setAndami(andami);
2529
        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2530
        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2531
        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2532 40435 jjdelcerro
2533 42362 jjdelcerro
        if (System.getProperty("javawebstart.version") != null) // Es java web
2534
        // start)
2535
        {
2536
            andamiConfig
2537
                    .setPluginsDirectory(new File(appHomeDir, "extensiones")
2538
                            .getAbsolutePath());
2539
        } else {
2540
            andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2541
                    .getAbsolutePath());
2542
        }
2543 40435 jjdelcerro
2544 42362 jjdelcerro
        andamiConfig.setPlugin(new Plugin[0]);
2545
        return andamiConfig;
2546
    }
2547 40435 jjdelcerro
2548 42362 jjdelcerro
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
2549
        File xml = getPluginsPersistenceFile(true);
2550 40435 jjdelcerro
2551 42362 jjdelcerro
        if (xml.exists()) {
2552
            InputStreamReader reader = null;
2553 40435 jjdelcerro
2554 42362 jjdelcerro
            try {
2555
                reader = XMLEncodingUtils.getReader(xml);
2556
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2557
                return new XMLEntity(tag);
2558
            } catch (FileNotFoundException e) {
2559
                throw new ConfigurationException(e);
2560
            } catch (MarshalException e) {
2561 40435 jjdelcerro
2562
                                // try to reopen with default encoding (for backward
2563 42362 jjdelcerro
                // compatibility)
2564
                try {
2565
                    reader = new FileReader(xml);
2566
                    XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2567
                    return new XMLEntity(tag);
2568 40435 jjdelcerro
2569 42362 jjdelcerro
                } catch (MarshalException ex) {
2570
                    // try to close the stream, maybe it remains open
2571
                    if (reader != null) {
2572
                        try {
2573
                            reader.close();
2574
                        } catch (IOException e1) {
2575
                        }
2576
                    }
2577
                    // backup the old file
2578
                    String backupFile = getPluginsPersistenceFile(true)
2579
                            .getPath()
2580
                            + "-" + DateTime.getCurrentDate().getTime();
2581
                    NotificationManager
2582
                            .addError(
2583
                                    Messages
2584
                                    .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2585
                                    + backupFile,
2586
                                    new ConfigurationException(e));
2587
                    xml.renameTo(new File(backupFile));
2588
                    // create a new, empty configuration
2589
                    return new XMLEntity();
2590
                } catch (FileNotFoundException ex) {
2591
                    return new XMLEntity();
2592
                } catch (ValidationException ex) {
2593
                    throw new ConfigurationException(e);
2594
                }
2595
            } catch (ValidationException e) {
2596
                throw new ConfigurationException(e);
2597
            }
2598
        } else {
2599
            return new XMLEntity();
2600
        }
2601
    }
2602 40435 jjdelcerro
2603 42362 jjdelcerro
    private static File getPluginsPersistenceFile(boolean read) {
2604
        if (read) {
2605
            File pluginsPersistenceFile = new File(getAppHomeDir(),
2606
                    "plugins-persistence-2_0.xml");
2607
            if (pluginsPersistenceFile.exists()) {
2608
                return pluginsPersistenceFile;
2609
            }
2610
            pluginsPersistenceFile = new File(getAppHomeDir(),
2611
                    "plugins-persistence.xml");
2612
            if (pluginsPersistenceFile.exists()) {
2613
                return pluginsPersistenceFile;
2614
            }
2615
        }
2616
        return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2617 40435 jjdelcerro
2618 42362 jjdelcerro
    }
2619 40435 jjdelcerro
2620 42362 jjdelcerro
    private static void persistenceToXML(XMLEntity entity)
2621
            throws ConfigurationException {
2622 40435 jjdelcerro
                // write on a temporary file in order to not destroy current file if
2623 42362 jjdelcerro
        // there is some problem while marshaling
2624
        File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2625
                + "-" + DateTime.getCurrentDate().getTime());
2626 40435 jjdelcerro
2627 42362 jjdelcerro
        File xml = getPluginsPersistenceFile(false);
2628
        OutputStreamWriter writer = null;
2629 40435 jjdelcerro
2630 42362 jjdelcerro
        try {
2631
            writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2632
                    CASTORENCODING);
2633
            entity.getXmlTag().marshal(writer);
2634
            writer.close();
2635 40435 jjdelcerro
2636
                        // if marshaling process finished correctly, move the file to the
2637 42362 jjdelcerro
            // correct one
2638
            xml.delete();
2639
            if (!tmpFile.renameTo(xml)) {
2640
                // if rename was not succesful, try copying it
2641
                FileChannel sourceChannel = new FileInputStream(tmpFile)
2642
                        .getChannel();
2643
                FileChannel destinationChannel = new FileOutputStream(xml)
2644
                        .getChannel();
2645
                sourceChannel.transferTo(0, sourceChannel.size(),
2646
                        destinationChannel);
2647
                sourceChannel.close();
2648
                destinationChannel.close();
2649 40435 jjdelcerro
2650 42362 jjdelcerro
            }
2651
        } catch (FileNotFoundException e) {
2652
            throw new ConfigurationException(e);
2653
        } catch (MarshalException e) {
2654
            // try to close the stream, maybe it remains open
2655
            if (writer != null) {
2656
                try {
2657
                    writer.close();
2658
                } catch (IOException e1) {
2659
                }
2660
            }
2661
        } catch (ValidationException e) {
2662
            throw new ConfigurationException(e);
2663
        } catch (IOException e) {
2664
            throw new ConfigurationException(e);
2665
        }
2666
    }
2667 40435 jjdelcerro
2668 42362 jjdelcerro
    static MDIFrame getFrame() {
2669
        return frame;
2670
    }
2671 40435 jjdelcerro
2672 42362 jjdelcerro
    /**
2673
     * Gracefully closes the application. It shows dialogs to save data, finish
2674
     * processes, etc, then it terminates the extensions, removes temporal files
2675
     * and finally exits.
2676
     */
2677
    public synchronized static void closeApplication() {
2678
        TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2679
        terminationProcess.run();
2680
    }
2681 40435 jjdelcerro
2682 42362 jjdelcerro
    static HashMap getClassesExtensions() {
2683
        return classesExtensions;
2684
    }
2685 40435 jjdelcerro
2686 42362 jjdelcerro
    private static Extensions[] getExtensions() {
2687
        List<Extensions> array = new ArrayList<Extensions>();
2688
        Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2689 40435 jjdelcerro
2690 42362 jjdelcerro
        while (iter.hasNext()) {
2691
            array.add(iter.next().getExtensions());
2692
        }
2693 40435 jjdelcerro
2694 42362 jjdelcerro
        return array.toArray(new Extensions[array.size()]);
2695
    }
2696 40435 jjdelcerro
2697 42362 jjdelcerro
    public static Iterator getExtensionIterator() {
2698
        return extensions.iterator();
2699
    }
2700 40435 jjdelcerro
2701 42362 jjdelcerro
    public static HashMap getPluginConfig() {
2702
        return pluginsConfig;
2703
    }
2704 40435 jjdelcerro
2705 42362 jjdelcerro
    public static Extension getExtension(String s) {
2706
        Extensions[] exts = getExtensions();
2707 40435 jjdelcerro
2708 42362 jjdelcerro
        for (int i = 0; i < exts.length; i++) {
2709
            for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2710
                if (exts[i].getExtension(j).getClassName().equals(s)) {
2711
                    return exts[i].getExtension(j);
2712
                }
2713
            }
2714
        }
2715 40435 jjdelcerro
2716 42362 jjdelcerro
        return null;
2717
    }
2718 40435 jjdelcerro
2719 42362 jjdelcerro
    public static AndamiConfig getAndamiConfig() {
2720
        return andamiConfig;
2721
    }
2722 40435 jjdelcerro
2723 42362 jjdelcerro
    private static class ExtensionComparator implements Comparator {
2724 40435 jjdelcerro
2725 42362 jjdelcerro
        public int compare(Object o1, Object o2) {
2726
            Extension e1 = (Extension) o1;
2727
            Extension e2 = (Extension) o2;
2728 40435 jjdelcerro
2729 42362 jjdelcerro
            if (!e1.hasPriority() && !e2.hasPriority()) {
2730
                return -1;
2731
            }
2732 40435 jjdelcerro
2733 42362 jjdelcerro
            if (e1.hasPriority() && !e2.hasPriority()) {
2734
                return Integer.MIN_VALUE;
2735
            }
2736 40435 jjdelcerro
2737 42362 jjdelcerro
            if (e2.hasPriority() && !e1.hasPriority()) {
2738
                return Integer.MAX_VALUE;
2739
            }
2740 40435 jjdelcerro
2741 42362 jjdelcerro
            if (e1.getPriority() != e2.getPriority()) {
2742
                return e2.getPriority() - e1.getPriority();
2743
            } else {
2744
                return (e2.toString().compareTo(e1.toString()));
2745
            }
2746
        }
2747
    }
2748 40435 jjdelcerro
2749 42362 jjdelcerro
    private static class MenuComparator implements Comparator<SortableMenu> {
2750 40435 jjdelcerro
2751 42362 jjdelcerro
        private static ExtensionComparator extComp = new ExtensionComparator();
2752 40435 jjdelcerro
2753 42362 jjdelcerro
        public int compare(SortableMenu e1, SortableMenu e2) {
2754 40435 jjdelcerro
2755 42362 jjdelcerro
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2756
                if (e1.extension instanceof SkinExtensionType) {
2757
                    return 1;
2758
                } else if (e2.extension instanceof SkinExtensionType) {
2759
                    return -1;
2760
                } else {
2761
                    return extComp.compare(e1.extension, e2.extension);
2762
                }
2763
            }
2764 40435 jjdelcerro
2765 42362 jjdelcerro
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2766
                return Integer.MIN_VALUE;
2767
            }
2768 40435 jjdelcerro
2769 42362 jjdelcerro
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2770
                return Integer.MAX_VALUE;
2771
            }
2772 41775 fdiaz
2773 42362 jjdelcerro
            if (e1.menu.getPosition() == e2.menu.getPosition()) {
2774 40435 jjdelcerro
                                // we don't return 0 unless both objects are the same, otherwise
2775 42362 jjdelcerro
                // the objects get overwritten in the treemap
2776
                return (e1.toString().compareTo(e2.toString()));
2777
            }
2778
            if (e1.menu.getPosition() > e2.menu.getPosition()) {
2779
                return Integer.MAX_VALUE;
2780
            }
2781
            return Integer.MIN_VALUE;
2782 41775 fdiaz
2783 42362 jjdelcerro
        }
2784
    }
2785 40435 jjdelcerro
2786 42362 jjdelcerro
    private static class SortableMenu {
2787 40435 jjdelcerro
2788 42362 jjdelcerro
        public PluginClassLoader loader;
2789
        public Menu menu;
2790
        public SkinExtensionType extension;
2791 40435 jjdelcerro
2792 42362 jjdelcerro
        public SortableMenu(PluginClassLoader loader,
2793
                SkinExtensionType skinExt, Menu menu2) {
2794
            extension = skinExt;
2795
            menu = menu2;
2796
            this.loader = loader;
2797
        }
2798 41775 fdiaz
2799 42362 jjdelcerro
    }
2800 40435 jjdelcerro
2801 42362 jjdelcerro
    private static class SortableTool {
2802 40435 jjdelcerro
2803 42362 jjdelcerro
        public PluginClassLoader loader;
2804
        public ToolBar toolbar;
2805
        public ActionTool actiontool;
2806
        public SelectableTool selectabletool;
2807
        public SkinExtensionType extension;
2808 40435 jjdelcerro
2809 42362 jjdelcerro
        public SortableTool(PluginClassLoader loader,
2810
                SkinExtensionType skinExt, ToolBar toolbar2,
2811
                ActionTool actiontool2) {
2812
            extension = skinExt;
2813
            toolbar = toolbar2;
2814
            actiontool = actiontool2;
2815
            this.loader = loader;
2816
        }
2817 40435 jjdelcerro
2818 42362 jjdelcerro
        public SortableTool(PluginClassLoader loader,
2819
                SkinExtensionType skinExt, ToolBar toolbar2,
2820
                SelectableTool selectabletool2) {
2821
            extension = skinExt;
2822
            toolbar = toolbar2;
2823
            selectabletool = selectabletool2;
2824
            this.loader = loader;
2825
        }
2826
    }
2827 40435 jjdelcerro
2828 42362 jjdelcerro
    private static class ToolBarComparator implements Comparator<SortableTool> {
2829 40435 jjdelcerro
2830 42362 jjdelcerro
        private static ExtensionComparator extComp = new ExtensionComparator();
2831 40435 jjdelcerro
2832 42362 jjdelcerro
        public int compare(SortableTool e1, SortableTool e2) {
2833 40435 jjdelcerro
2834
                        // if the toolbars have the same name, they are considered to be
2835 42362 jjdelcerro
            // the same toolbar, so we don't need to do further comparing
2836
            if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2837
                return 0;
2838
            }
2839 40435 jjdelcerro
2840 42362 jjdelcerro
            if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2841
                if (e1.extension instanceof SkinExtensionType) {
2842
                    return 1;
2843
                } else if (e2.extension instanceof SkinExtensionType) {
2844
                    return -1;
2845
                } else {
2846
                    return extComp.compare(e1.extension, e2.extension);
2847
                }
2848
            }
2849 40435 jjdelcerro
2850 42362 jjdelcerro
            if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2851
                return Integer.MIN_VALUE;
2852
            }
2853 40435 jjdelcerro
2854 42362 jjdelcerro
            if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2855
                return Integer.MAX_VALUE;
2856
            }
2857
            if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2858
                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2859
            }
2860 40435 jjdelcerro
2861 42362 jjdelcerro
            if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2862
                    && e1.toolbar.getSelectableTool().equals(
2863
                            e2.toolbar.getSelectableTool())) {
2864
                return 0;
2865
            }
2866
            return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2867
        }
2868
    }
2869 40435 jjdelcerro
2870 42362 jjdelcerro
    /**
2871
     * <p>
2872
     * This class is used to compare tools (selectabletool and actiontool),
2873
     * using the "position" attribute.
2874
     * </p>
2875
     * <p>
2876
     * The ordering criteria are:
2877
     * </p>
2878
     * <ul>
2879
     * <li>If the tools are placed in different toolbars, they use the toolbars'
2880
     * order. (using the ToolBarComparator).</li>
2881
     * <li></li>
2882
     * <li>If any of the tools has not 'position' attribute, the tool which
2883
     * <strong>has</strong> the attribute will be placed first.</li>
2884
     * <li>If both tools have the same position (or they don't have a 'position'
2885
     * attribute), the priority of the extensions where the tool is
2886
     * defined.</li>
2887
     * </ul>
2888
     *
2889
     * @author cesar
2890
     * @version $Revision: 40305 $
2891
     */
2892
    private static class ToolComparator implements Comparator<SortableTool> {
2893 40435 jjdelcerro
2894 42362 jjdelcerro
        private static ToolBarComparator toolBarComp = new ToolBarComparator();
2895 40435 jjdelcerro
2896 42362 jjdelcerro
        public int compare(SortableTool e1, SortableTool e2) {
2897
            // compare the toolbars which contain the tools
2898
            long result = toolBarComp.compare(e1, e2);
2899
            if (result != 0) { // if the toolbars are different, use their order
2900
                return result > 0 ? 1 : -1;
2901
            }
2902
            // otherwise, compare the tools
2903
            long e1Position = -1, e2Position = -1;
2904 40435 jjdelcerro
2905 42362 jjdelcerro
            if (e1.actiontool != null) {
2906
                if (e1.actiontool.hasPosition()) {
2907
                    e1Position = e1.actiontool.getPosition();
2908
                }
2909
            } else if (e1.selectabletool != null) {
2910
                if (e1.selectabletool.hasPosition()) {
2911
                    e1Position = e1.selectabletool.getPosition();
2912
                }
2913
            }
2914 40435 jjdelcerro
2915 42362 jjdelcerro
            if (e2.actiontool != null) {
2916
                if (e2.actiontool.hasPosition()) {
2917
                    e2Position = e2.actiontool.getPosition();
2918
                }
2919
            } else if (e2.selectabletool != null) {
2920
                if (e2.selectabletool.hasPosition()) {
2921
                    e2Position = e2.selectabletool.getPosition();
2922
                }
2923
            }
2924 40435 jjdelcerro
2925 42362 jjdelcerro
            if ((e1Position == -1) && (e2Position != -1)) {
2926
                return 1;
2927
            }
2928
            if ((e1Position != -1) && (e2Position == -1)) {
2929
                return -1;
2930
            }
2931
            if ((e1Position != -1) && (e2Position != -1)) {
2932
                result = e1Position - e2Position;
2933 40435 jjdelcerro
                                // we don't return 0 unless both objects are the same, otherwise
2934 42362 jjdelcerro
                // the objects get overwritten in the treemap
2935
                if (result != 0) {
2936
                    return result > 0 ? 1 : -1;
2937
                }
2938
            }
2939
            return e1.toString().compareTo(e2.toString());
2940
        }
2941
    }
2942 40435 jjdelcerro
2943 42362 jjdelcerro
    public static String getDefaultLookAndFeel() {
2944
        String osName = (String) System.getProperty("os.name");
2945 40435 jjdelcerro
2946 42362 jjdelcerro
        if ((osName.length() > 4)
2947
                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2948
            return nonWinDefaultLookAndFeel;
2949
        }
2950
        if (osName.toLowerCase().startsWith("mac os x")) {
2951
            return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2952
        }
2953 40435 jjdelcerro
2954 42362 jjdelcerro
        return UIManager.getSystemLookAndFeelClassName();
2955
    }
2956 40435 jjdelcerro
2957 42362 jjdelcerro
    /**
2958
     * Gets the ISO 839 two-characters-long language code matching the provided
2959
     * language code (which may be an ISO 839-2/T three-characters-long code or
2960
     * an ISO 839-1 two-characters-long code).
2961
     *
2962
     * If the provided parameter is already two characters long, it returns the
2963
     * parameter without any modification.
2964
     *
2965
     * @param langCode A language code representing either an ISO 839-2/T
2966
     * language code or an ISO 839-1 code.
2967
     * @return A two-characters-long code specifying an ISO 839 language code.
2968
     */
2969
    private static String normalizeLanguageCode(String langCode) {
2970
        final String fileName = "iso_639.tab";
2971
        if (langCode.length() == 2) {
2972
            return langCode;
2973
        } else if (langCode.length() == 3) {
2974
            if (langCode.equals("va") || langCode.equals("val")) { // special
2975
                // case
2976
                // for
2977
                // Valencian
2978
                return "ca";
2979
            }
2980
            URL isoCodes = Launcher.class.getClassLoader()
2981
                    .getResource(fileName);
2982
            if (isoCodes != null) {
2983
                try {
2984
                    BufferedReader reader = new BufferedReader(
2985
                            new InputStreamReader(isoCodes.openStream(),
2986
                                    "ISO-8859-1"));
2987
                    String line;
2988 40435 jjdelcerro
2989 42362 jjdelcerro
                    while ((line = reader.readLine()) != null) {
2990
                        String[] language = line.split("\t");
2991
                        if (language[0].equals(langCode)) {
2992 40435 jjdelcerro
                                                        // the three
2993 42362 jjdelcerro
                            // characters code
2994
                            return language[2]; // third column i the two
2995
                            // characters code
2996
                        }
2997
                    }
2998
                } catch (IOException ex) {
2999
                    logger.error(Messages
3000
                            .getString("Error_reading_isocodes_file"), ex);
3001
                    return "es";
3002
                }
3003
            } else {
3004
                logger.error(Messages.getString("Error_reading_isocodes_file"));
3005
                return "es";
3006
            }
3007
        }
3008
        return "es";
3009
    }
3010 40435 jjdelcerro
3011 42362 jjdelcerro
    /**
3012
     * Configures the locales (languages and local resources) to be used by the
3013
     * application.
3014
     *
3015
     * First it tries to get the locale from the command line parameters, then
3016
     * the andami-config file is checked.
3017
     *
3018
     * The locale name is normalized to get a two characters language code as
3019
     * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
3020
     * also accepted from the command line or the configuration file).
3021
     *
3022
     * Finally, the gvsig-i18n library and the default locales for Java and
3023
     * Swing are configured.
3024
     *
3025
     */
3026 41284 jjdelcerro
    private static void configureLocales(String[] args) {
3027
        // Configurar el locale
3028
        String localeStr = null;
3029 40821 jjdelcerro
3030 41284 jjdelcerro
        localeStr = PluginServices.getArgumentByName("language");
3031 42362 jjdelcerro
        if (localeStr == null) {
3032 41284 jjdelcerro
            localeStr = andamiConfig.getLocaleLanguage();
3033
        }
3034
        localeStr = normalizeLanguageCode(localeStr);
3035 41916 jjdelcerro
        locale = getLocale(
3036 42200 fdiaz
                localeStr,
3037 41916 jjdelcerro
                andamiConfig.getLocaleCountry(),
3038
                andamiConfig.getLocaleVariant()
3039
        );
3040 41314 jjdelcerro
        org.gvsig.i18n.Messages.setCurrentLocale(locale);
3041 41284 jjdelcerro
        JComponent.setDefaultLocale(locale);
3042 41314 jjdelcerro
        /*
3043 42362 jjdelcerro
         org.gvsig.i18n.Messages.addLocale(locale);
3044
         // add english and spanish as fallback languages
3045
         if ( localeStr.equals("es") || localeStr.equals("ca")
3046
         || localeStr.equals("gl") || localeStr.equals("eu")
3047
         || localeStr.equals("va") ) {
3048
         // prefer Spanish for languages spoken in Spain
3049
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3050
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3051
         } else {
3052
         // prefer English for the rest
3053
         org.gvsig.i18n.Messages.addLocale(new Locale("en"));
3054
         org.gvsig.i18n.Messages.addLocale(new Locale("es"));
3055
         }
3056
         */
3057 40435 jjdelcerro
        // Create classloader for the i18n resources in the
3058
        // andami and user i18n folder. Those values will have
3059
        // precedence over any other values added afterwards
3060 42362 jjdelcerro
        File appI18nFolder = new File(getApplicationFolder(), "i18n");
3061 40435 jjdelcerro
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
3062 42362 jjdelcerro
        if (!userI18nFolder.exists()) {
3063 41284 jjdelcerro
            try {
3064
                FileUtils.forceMkdir(userI18nFolder);
3065
            } catch (IOException e) {
3066
                logger.info("Can't create i18n folder in gvSIG home (" + userI18nFolder + ").", e);
3067
            }
3068 40821 jjdelcerro
        }
3069 41314 jjdelcerro
//        logger.info("Loading i18n resources from the application and user "
3070
//                + "folders: {}, {}", appI18nFolder, userI18nFolder);
3071 40435 jjdelcerro
3072 41284 jjdelcerro
        URL[] i18nURLs = getURLsFromI18nFolders(userI18nFolder, appI18nFolder);
3073 41314 jjdelcerro
        ClassLoader i18nClassLoader = URLClassLoader.newInstance(i18nURLs, null);
3074 42362 jjdelcerro
        logger.info("loading resources from classloader " + i18nClassLoader.toString() + ".");
3075 41284 jjdelcerro
        org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
3076 40435 jjdelcerro
                "Andami Launcher");
3077 41775 fdiaz
3078 42362 jjdelcerro
        // Finally load the andami own i18n resources
3079
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
3080
                "Andami Launcher");
3081 41284 jjdelcerro
    }
3082 40435 jjdelcerro
3083 42362 jjdelcerro
    private static URL[] getURLsFromI18nFolders(File userFolder, File appFolder) {
3084
        List<URL> urls = new ArrayList<URL>();
3085
        File[] files = new File[]{userFolder, appFolder};
3086
        for (int n1 = 0; n1 < files.length; n1++) {
3087
            File folder = files[n1];
3088 41322 jjdelcerro
//                try {
3089
//                    urls.add(folder.toURI().toURL());
3090
//                } catch (MalformedURLException ex) {
3091
//                    logger.warn("Can't convert file to url (file="+userFolder.getAbsolutePath()+").", ex);
3092
//                    return null;
3093
//                }
3094 42362 jjdelcerro
            File[] subFiles = folder.listFiles();
3095
            for (int n2 = 0; n2 < subFiles.length; n2++) {
3096
                File subFolder = subFiles[n2];
3097
                if ("andami".equalsIgnoreCase(subFolder.getName())) {
3098
                    // Skip andami and add the last.
3099
                    continue;
3100
                }
3101
                if (subFolder.isDirectory()) {
3102
                    try {
3103
                        urls.add(subFolder.toURI().toURL());
3104
                    } catch (MalformedURLException ex) {
3105
                        logger.warn("Can't convert file to url (file=" + subFolder.getAbsolutePath() + ").", ex);
3106
                        return null;
3107 41314 jjdelcerro
                    }
3108 41284 jjdelcerro
                }
3109
            }
3110
        }
3111 42362 jjdelcerro
        File folder = new File(appFolder, "andami");
3112
        try {
3113
            urls.add(folder.toURI().toURL());
3114
        } catch (MalformedURLException ex) {
3115
            logger.warn("Can't convert file to url (file=" + folder.getAbsolutePath() + ").", ex);
3116
            return null;
3117
        }
3118
        return urls.toArray(new URL[urls.size()]);
3119
    }
3120 41775 fdiaz
3121 42362 jjdelcerro
    /**
3122
     * Gets Home Directory location of the application into users home folder.
3123
     *
3124
     * May be set from outside the aplication by means of
3125
     * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
3126
     *
3127
     * @return
3128
     */
3129
    public static String getAppHomeDir() {
3130
        return appHomeDir;
3131
    }
3132 41775 fdiaz
3133 40435 jjdelcerro
    public static File getApplicationHomeFolder() {
3134
        return new File(getAppHomeDir());
3135
    }
3136
3137 42362 jjdelcerro
    /**
3138
     * Sets Home Directory location of the application. May be set from outside
3139
     * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3140
     * the name of the application
3141
     *
3142
     * @param appHomeDir
3143
     */
3144
    public static void setAppHomeDir(String appHomeDir) {
3145
        Launcher.appHomeDir = appHomeDir;
3146
    }
3147 40435 jjdelcerro
3148 42362 jjdelcerro
    /**
3149
     * Initialize the extesion that have to take the control of the state of
3150
     * action controls of the UI of all extensions. <br>
3151
     * <br>
3152
     * For use this option you have to add an argument to the command line like
3153
     * this: <br>
3154
     * <br>
3155
     * -exclusiveUI={pathToExtensionClass} <br>
3156
     *
3157
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3158
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3159
     */
3160
    private static void initializeExclusiveUIExtension() {
3161
        String name = PluginServices.getArgumentByName("exclusiveUI");
3162
        if (name == null) {
3163
            return;
3164
        }
3165 40435 jjdelcerro
3166 42362 jjdelcerro
        Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3167
                .iterator();
3168
        int charIndex;
3169
        Class<? extends IExtension> key;
3170
        while (iter.hasNext()) {
3171
            key = iter.next();
3172
            charIndex = key.getName().indexOf(name);
3173
            // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3174
            if (charIndex == 0) {
3175
                IExtension ext = classesExtensions.get(key);
3176
                if (ext instanceof ExtensionDecorator) {
3177
                    ext = ((ExtensionDecorator) ext).getExtension();
3178
                }
3179
                if (ext instanceof ExclusiveUIExtension) {
3180
                    PluginServices
3181
                            .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3182
                }
3183
                break;
3184
            }
3185
        }
3186 40435 jjdelcerro
3187 42362 jjdelcerro
        logger
3188
                .error(Messages
3189
                        .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3190
                        + " '" + name + "'");
3191
    }
3192 40435 jjdelcerro
3193 42362 jjdelcerro
    public static void initIconThemes() {
3194
        PluginsManager pluginsManager = PluginsLocator.getManager();
3195
        IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3196 41775 fdiaz
3197 42362 jjdelcerro
        File f = new File(pluginsManager.getApplicationFolder(), "icon-theme");
3198
        if (!f.exists()) {
3199
            try {
3200
                f.mkdir();
3201
            } catch (Exception ex) {
3202
                // Do nothing
3203
            }
3204
        }
3205
        iconManager.getRepository().add(f, "_Global");
3206 41775 fdiaz
3207 42362 jjdelcerro
        f = new File(pluginsManager.getApplicationHomeFolder(), "icon-theme");
3208
        if (!f.exists()) {
3209
            try {
3210
                f.mkdir();
3211
            } catch (Exception ex) {
3212
                // Do nothing
3213
            }
3214
        }
3215
        iconManager.getRepository().add(f, "_User");
3216 41775 fdiaz
3217 42362 jjdelcerro
        Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3218
        String defaultThemeID = prefs.get("default-theme", null);
3219
        if (defaultThemeID != null) {
3220
            IconTheme iconTheme = iconManager.get(defaultThemeID);
3221
            if (iconTheme != null) {
3222
                iconManager.setCurrent(iconTheme);
3223
            }
3224
        }
3225
    }
3226 40435 jjdelcerro
3227 42362 jjdelcerro
    public static void manageUnsavedData(String prompt) throws Exception {
3228
        final UnsavedDataPanel panel = new UnsavedDataPanel(prompt);
3229
        final List<IUnsavedData> unsavedData = PluginsLocator.getManager().getUnsavedData();
3230 42200 fdiaz
        panel.setUnsavedData(unsavedData);
3231
3232
        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3233
3234
            public void cancel(UnsavedDataPanel panel) {
3235
                panel.setVisible(false);
3236
            }
3237
3238
            public void discard(UnsavedDataPanel panel) {
3239
                panel.setVisible(false);
3240
            }
3241
3242
            public void accept(UnsavedDataPanel panel) {
3243
                panel.setVisible(false);
3244
3245
                try {
3246
                    PluginsLocator.getManager().saveUnsavedData(panel.getSelectedsUnsavedDataList());
3247
                } catch (UnsavedDataException e) {
3248
                    StringBuilder msg = new StringBuilder();
3249 42362 jjdelcerro
                    msg.append(PluginServices.getText(this, "The_following_resources_could_not_be_saved"));
3250 42200 fdiaz
                    msg.append("\n");
3251
                    for (Iterator iterator = e.getUnsavedData().iterator(); iterator.hasNext();) {
3252
                        IUnsavedData unsavedData = (IUnsavedData) iterator.next();
3253
                        msg.append(unsavedData.getResourceName());
3254
                        msg.append(" -- ");
3255
                        msg.append(unsavedData.getDescription());
3256
                        msg.append("\n");
3257
                    }
3258 42362 jjdelcerro
                    JOptionPane.showMessageDialog(panel, msg, PluginServices.getText(this, "Resources_was_not_saved"), JOptionPane.ERROR_MESSAGE);
3259
                }
3260 42200 fdiaz
            }
3261
        });
3262
3263
        //TODO: mostrar panel WindowManager
3264
        ToolsSwingLocator.getWindowManager().showWindow(
3265 42362 jjdelcerro
                panel,
3266
                PluginServices.getText(panel, "Resource_was_not_saved"),
3267
                MODE.DIALOG);
3268 42200 fdiaz
3269 42362 jjdelcerro
    }
3270 42200 fdiaz
3271 42362 jjdelcerro
    /**
3272
     * Manages Andami termination process
3273
     *
3274
     * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3275
     */
3276
    public class TerminationProcess {
3277 40435 jjdelcerro
3278 42362 jjdelcerro
        private boolean proceed = false;
3279
        private UnsavedDataPanel panel = null;
3280 40435 jjdelcerro
3281 42362 jjdelcerro
        public void run() {
3282
            try {
3283
                int exit = manageUnsavedData();
3284
                if ((exit == JOptionPane.NO_OPTION)
3285
                        || (exit == JOptionPane.CLOSED_OPTION)) {
3286
                    // the user doesn't want to exit
3287
                    return;
3288
                }
3289
                closeAndami();
3290
            } catch (Exception e) {
3291
                logger.warn("It is not possible to close the application", e);
3292 40435 jjdelcerro
                                // It is not possible to close the application.
3293 42362 jjdelcerro
                // this exception has been registered before
3294
            }
3295
        }
3296 40435 jjdelcerro
3297 42362 jjdelcerro
        /**
3298
         * Finishes the application without asking user if want or not to save
3299
         * unsaved data.
3300
         */
3301
        public void closeAndami() {
3302
            PluginsManager pluginsManager = PluginsLocator.getManager();
3303
            pluginsManager.executeShutdownTasks();
3304 40435 jjdelcerro
3305 42362 jjdelcerro
            try {
3306
                saveAndamiConfig();
3307
            } catch (Exception ex) {
3308
                logger.error(
3309
                        "There was an error exiting application, can't save andami-config.xml",
3310
                        ex
3311
                );
3312
            }
3313 40435 jjdelcerro
3314 42362 jjdelcerro
            try {
3315
                // Persistencia de los plugins
3316
                savePluginPersistence();
3317
                savePluginsProperties();
3318
            } catch (Exception ex) {
3319
                logger.error(
3320
                        "There was an error exiting application, can't save plugins properties",
3321
                        ex
3322
                );
3323
            }
3324 40435 jjdelcerro
3325 42362 jjdelcerro
            // Finalize all the extensions
3326
            finalizeExtensions();
3327 40435 jjdelcerro
3328 42362 jjdelcerro
            try {
3329
                // Clean any temp data created
3330
                Utilities.cleanUpTempFiles();
3331
            } catch (Exception ex) {
3332
                logger.error(
3333
                        "There was an error exiting application, can't remove temporary files",
3334
                        ex
3335
                );
3336
            }
3337 40435 jjdelcerro
3338 42362 jjdelcerro
            logger.info("Quiting application.");
3339 40435 jjdelcerro
3340 42362 jjdelcerro
            // Para la depuraci?n de memory leaks
3341
            System.gc();
3342 40435 jjdelcerro
3343 42362 jjdelcerro
            System.exit(0);
3344
        }
3345
3346
        public void saveAndamiConfig() {
3347
            // Configuraci?n de Andami
3348
            try {
3349
                andamiConfigToXML(andamiConfigPath);
3350
            } catch (MarshalException e) {
3351
                logger
3352
                        .error(
3353
                                Messages
3354
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3355
                                e);
3356
            } catch (ValidationException e) {
3357
                logger
3358
                        .error(
3359
                                Messages
3360
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3361
                                e);
3362
            } catch (IOException e) {
3363
                logger
3364
                        .error(
3365
                                Messages
3366
                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3367
                                e);
3368 41311 jjdelcerro
            }
3369 42362 jjdelcerro
        }
3370 41311 jjdelcerro
3371 42362 jjdelcerro
        private void savePluginsProperties() {
3372
            PluginsManager manager = PluginsLocator.getManager();
3373
            List<PluginServices> plugins = manager.getPlugins();
3374
            for (PluginServices plugin : plugins) {
3375
                if (plugin != null) {
3376
                    plugin.savePluginProperties();
3377
                }
3378
            }
3379
        }
3380 40435 jjdelcerro
3381 42362 jjdelcerro
        /**
3382
         * Exectutes the terminate method for all the extensions, in the reverse
3383
         * order they were initialized
3384
         *
3385
         */
3386
        private void finalizeExtensions() {
3387
            for (int i = extensions.size() - 1; i >= 0; i--) {
3388
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3389
                        .get(i);
3390
                String extensionName = "(unknow)";
3391
                try {
3392
                    extensionName = extensionInstance.getClass().getName();
3393
                    extensionInstance.terminate();
3394
                } catch (Exception ex) {
3395
                    logger.error(MessageFormat.format(
3396
                            "There was an error extension ending {0}",
3397
                            extensionName), ex);
3398
                }
3399
            }
3400
        }
3401 40435 jjdelcerro
3402 42362 jjdelcerro
        private IUnsavedData[] getUnsavedData() throws Exception {
3403
            List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3404
            IExtension exclusiveExtension = PluginServices
3405
                    .getExclusiveUIExtension();
3406 40435 jjdelcerro
3407 42362 jjdelcerro
            for (int i = extensions.size() - 1; i >= 0; i--) {
3408
                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3409
                        .get(i);
3410
                IExtensionStatus status = null;
3411
                if (exclusiveExtension != null) {
3412
                    status = exclusiveExtension.getStatus(extensionInstance);
3413
                } else {
3414
                    status = extensionInstance.getStatus();
3415
                }
3416
                if (status != null) {
3417
                    try {
3418
                        if (status.hasUnsavedData()) {
3419
                            IUnsavedData[] array = status.getUnsavedData();
3420
                            for (int element = 0; element < array.length; element++) {
3421
                                unsavedDataList.add(array[element]);
3422
                            }
3423
                        }
3424
                    } catch (Exception e) {
3425
                        logger.info("Error calling the hasUnsavedData method",
3426
                                new Exception());
3427
                        int option = JOptionPane
3428
                                .showConfirmDialog(
3429
                                        frame,
3430
                                        Messages
3431
                                        .getString("error_getting_unsaved_data"),
3432
                                        Messages.getString("MDIFrame.salir"),
3433
                                        JOptionPane.YES_NO_OPTION);
3434
                        if (option == JOptionPane.NO_OPTION) {
3435
                            throw e;
3436
                        }
3437
                    }
3438
                }
3439
            }
3440
            return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3441
                    .size()]);
3442
        }
3443 40435 jjdelcerro
3444 42362 jjdelcerro
        public UnsavedDataPanel getUnsavedDataPanel() {
3445
            if (panel == null) {
3446
                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3447
            }
3448
            return panel;
3449
        }
3450 40435 jjdelcerro
3451 42362 jjdelcerro
        /**
3452
         * Checks if the extensions have some unsaved data, and shows a dialog
3453
         * to allow saving it. This dialog also allows to don't exit Andami.
3454
         *
3455
         * @return true if the user confirmed he wishes to exit, false otherwise
3456
         * @throws Exception
3457
         */
3458
        public int manageUnsavedData() throws Exception {
3459
            IUnsavedData[] unsavedData = getUnsavedData();
3460 40435 jjdelcerro
3461 42362 jjdelcerro
            // there was no unsaved data
3462
            if (unsavedData.length == 0) {
3463
                int option = JOptionPane
3464
                        .showConfirmDialog(frame, Messages
3465
                                .getString("MDIFrame.quiere_salir"), Messages
3466
                                .getString("MDIFrame.salir"),
3467
                                JOptionPane.YES_NO_OPTION);
3468
                return option;
3469
            }
3470 40435 jjdelcerro
3471 42362 jjdelcerro
            UnsavedDataPanel panel = getUnsavedDataPanel();
3472
            panel.setUnsavedDataArray(unsavedData);
3473 40435 jjdelcerro
3474 42362 jjdelcerro
            panel.addActionListener(panel.new UnsavedDataPanelListener() {
3475 40435 jjdelcerro
3476 42362 jjdelcerro
                public void cancel(UnsavedDataPanel panel) {
3477
                    proceed(false);
3478
                    PluginServices.getMDIManager().closeWindow(panel);
3479 40435 jjdelcerro
3480 42362 jjdelcerro
                }
3481 40435 jjdelcerro
3482 42362 jjdelcerro
                public void discard(UnsavedDataPanel panel) {
3483
                    proceed(true);
3484
                    PluginServices.getMDIManager().closeWindow(panel);
3485 40435 jjdelcerro
3486 42362 jjdelcerro
                }
3487 40435 jjdelcerro
3488 42362 jjdelcerro
                public void accept(UnsavedDataPanel panel) {
3489
                    IUnsavedData[] unsavedDataArray = panel
3490
                            .getSelectedsUnsavedData();
3491
                    boolean saved;
3492
                    for (int i = 0; i < unsavedDataArray.length; i++) {
3493
                        try {
3494
                            saved = unsavedDataArray[i].saveData();
3495
                        } catch (Exception ex) {
3496
                            PluginServices.getLogger().error(
3497
                                    "Error saving"
3498
                                    + unsavedDataArray[i]
3499
                                    .getResourceName(), ex);
3500
                            saved = false;
3501
                        }
3502
                        if (!saved) {
3503
                            JOptionPane
3504
                                    .showMessageDialog(
3505
                                            panel,
3506
                                            PluginServices
3507
                                            .getText(this,
3508
                                                    "The_following_resource_could_not_be_saved_")
3509
                                            + "\n"
3510
                                            + unsavedDataArray[i]
3511
                                            .getResourceName()
3512
                                            + " -- "
3513
                                            + unsavedDataArray[i]
3514
                                            .getDescription(),
3515
                                            PluginServices.getText(this,
3516
                                                    "unsaved_resources"),
3517
                                            JOptionPane.ERROR_MESSAGE);
3518 40435 jjdelcerro
3519 42362 jjdelcerro
                            try {
3520
                                unsavedDataArray = getUnsavedData();
3521
                            } catch (Exception e) {
3522
                                // This exception has been registered before
3523
                            }
3524
                            panel.setUnsavedDataArray(unsavedDataArray);
3525
                            return;
3526
                        }
3527
                    }
3528
                    proceed(true);
3529
                    PluginServices.getMDIManager().closeWindow(panel);
3530
                }
3531
            });
3532 40435 jjdelcerro
3533 42362 jjdelcerro
            PluginServices.getMDIManager().addWindow(panel);
3534
            if (proceed) {
3535
                return JOptionPane.YES_OPTION;
3536
            } else {
3537
                return JOptionPane.NO_OPTION;
3538
            }
3539
        }
3540 40435 jjdelcerro
3541 42362 jjdelcerro
        private void proceed(boolean proceed) {
3542
            this.proceed = proceed;
3543
        }
3544 40435 jjdelcerro
3545 42362 jjdelcerro
    }
3546 40435 jjdelcerro
3547 42362 jjdelcerro
    public static TerminationProcess getTerminationProcess() {
3548
        return (new Launcher()).new TerminationProcess();
3549
    }
3550 40435 jjdelcerro
3551 42362 jjdelcerro
    private PackageInfo getPackageInfo(String pluginsFolder) {
3552
        try {
3553
            PluginsManager pm = PluginsLocator.getManager();
3554
            return pm.getPackageInfo();
3555
        } catch (Exception e) {
3556
            logger.info("Can't locate PackageInfo from plugin org.gvsig.app", e);
3557
            return null;
3558
        }
3559
    }
3560 40435 jjdelcerro
3561 42362 jjdelcerro
    /**
3562
     * Launch the gvSIG package installer.
3563
     *
3564
     * @throws Exception if there is any error
3565
     */
3566 41717 jjdelcerro
    private void doInstall(String[] args) throws Exception {
3567
        String installURL = null;
3568
        String installURLFile = null;
3569
        String gvSIGVersion = null;
3570
        String[] myArgs = new String[3];
3571
        PackageInfo packageInfo = null;
3572 40435 jjdelcerro
3573 41717 jjdelcerro
        Options options = new Options();
3574
        options.addOption("i", "install", false, "install");
3575
        options.addOption("u", "installURL", true, "installURL");
3576
        options.addOption("f", "installURLFile", true, "installURLFile");
3577
        options.addOption("v", "installVersion", true, "installVersion");
3578
        options.addOption("A", "applicationName", true, "application name, default is gvSIG");
3579
        options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3580
        options.addOption("l", "language", true, "language");
3581 40435 jjdelcerro
3582 42362 jjdelcerro
        // This options are managed by the gvSIG.sh but need to be declared here to avoid
3583 41717 jjdelcerro
        // errors.
3584
        options.addOption(null, "debug", false, "Activate the JVM remote debug");
3585
        options.addOption(null, "pause", false, "Pause when activate JVM debug");
3586 40435 jjdelcerro
3587 41717 jjdelcerro
        /*
3588
         * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3589 41775 fdiaz
         *
3590 41717 jjdelcerro
         * --install
3591
         * --applicationName=gvSIG
3592
         * --language=es
3593
         * --pluginsFolder=gvSIG/extensiones
3594 41775 fdiaz
         *
3595 41717 jjdelcerro
         * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3596
         * --installVersion=2.0.0
3597
         * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3598
         * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3599 41775 fdiaz
         *
3600 41717 jjdelcerro
         */
3601
        CommandLineParser parser = new PosixParser();
3602
        CommandLine line = null;
3603
        try {
3604
            line = parser.parse(options, args);
3605
            boolean hasAllMandatoryOptions = true;
3606 42362 jjdelcerro
            if (!line.hasOption("install")) {
3607 41717 jjdelcerro
                hasAllMandatoryOptions = false;
3608
            }
3609 40435 jjdelcerro
3610 42362 jjdelcerro
            if (line.hasOption("installVersion")) {
3611 41717 jjdelcerro
                gvSIGVersion = line.getOptionValue("installVersion");
3612
            }
3613 42362 jjdelcerro
            if (line.hasOption("applicationName")) {
3614 41717 jjdelcerro
                myArgs[0] = line.getOptionValue("applicationName");
3615
            } else {
3616
                myArgs[0] = "gvSIG";
3617
            }
3618 42362 jjdelcerro
            if (line.hasOption("pluginsFolder")) {
3619 41717 jjdelcerro
                myArgs[1] = line.getOptionValue("pluginsFolder");
3620
            } else {
3621
                myArgs[1] = "gvSIG/extensiones";
3622
            }
3623 42362 jjdelcerro
            if (line.hasOption("language")) {
3624 41717 jjdelcerro
                myArgs[2] = "language=" + line.getOptionValue("language");
3625
            } else {
3626
                // prevent null
3627 41916 jjdelcerro
                myArgs[2] = Locale.getDefault().toString();
3628 41717 jjdelcerro
            }
3629 40435 jjdelcerro
3630 42362 jjdelcerro
            if (line.hasOption("installURL")) {
3631 41717 jjdelcerro
                installURL = line.getOptionValue("installURL");
3632
            } else {
3633
                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3634
            }
3635 40435 jjdelcerro
3636 42362 jjdelcerro
            if (line.hasOption("installURLFile")) {
3637 41717 jjdelcerro
                installURLFile = line.getOptionValue("installURLFile");
3638
            } else {
3639 42685 jjdelcerro
                installURLFile = "gvsig-installer-urls.config";
3640 41717 jjdelcerro
            }
3641 40435 jjdelcerro
3642 42362 jjdelcerro
            if (!hasAllMandatoryOptions) {
3643
                System.err.println(Messages.get("usage") + ": Launcher "
3644
                        + "--install "
3645
                        + "[--applicationName=appName] "
3646
                        + "[--pluginsFolder=plugins-directory] "
3647
                        + "[--installURLFile=File] "
3648
                        + "[--installURL=URL] "
3649
                        + "[--language=locale]"
3650 41717 jjdelcerro
                );
3651
                return;
3652
            }
3653
        } catch (ParseException exp) {
3654 41916 jjdelcerro
            System.err.println("Unexpected exception:" + exp.getMessage());
3655 41717 jjdelcerro
            System.exit(-1);
3656
        }
3657 40435 jjdelcerro
3658 41717 jjdelcerro
        initializeApp(myArgs, "installer");
3659 41775 fdiaz
3660 41916 jjdelcerro
        new DefaultLibrariesInitializer().fullInitialize(true);
3661 42200 fdiaz
3662 41717 jjdelcerro
        initializeInstallerManager();
3663 41775 fdiaz
3664 41717 jjdelcerro
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
3665 42685 jjdelcerro
3666
//        try {
3667
//            logger.info("Loading plugins configurations");
3668
//            this.loadPluginConfigs();
3669
//        } catch (Throwable ex) {
3670
//            logger.warn("Can't load plugins configurations", ex);
3671
//        }
3672
//
3673
//        try {
3674
//            logger.info("Loading plugins");
3675
//            this.loadPluginServices();
3676
//        } catch (Throwable ex) {
3677
//            logger.warn("Can't load plugins", ex);
3678
//        }
3679 40435 jjdelcerro
3680 41916 jjdelcerro
        AndamiConfig config = getAndamiConfig();
3681
3682
        initializeIdentityManagement(new File(config.getPluginsDirectory()).getAbsoluteFile());
3683 42200 fdiaz
3684 41916 jjdelcerro
        initializeLibraries();
3685
3686 41717 jjdelcerro
        packageInfo = getPackageInfo(myArgs[1]);
3687 40435 jjdelcerro
3688 41717 jjdelcerro
        // set the gvSIG version to the install manager, to compose the download URL
3689 42362 jjdelcerro
        if (packageInfo != null) {
3690 41717 jjdelcerro
            installerManager.setVersion(packageInfo.getVersion());
3691
        } else {
3692
            installerManager.setVersion(gvSIGVersion);
3693
        }
3694 42362 jjdelcerro
        if (!installURL.contains(";")
3695 41717 jjdelcerro
                && !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION)
3696 42362 jjdelcerro
                && !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION)) {
3697
            if (packageInfo != null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA)
3698 41717 jjdelcerro
                    || packageInfo.getState().startsWith(InstallerManager.STATE.RC)
3699 42362 jjdelcerro
                    || packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL))) {
3700 41717 jjdelcerro
                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";
3701
            }
3702
        }
3703
        // Configure default index download URL
3704
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3705 40435 jjdelcerro
3706 41717 jjdelcerro
        SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3707 40435 jjdelcerro
3708 41717 jjdelcerro
        // Launch installer
3709
        PluginsManager manager = PluginsLocator.getManager();
3710 40435 jjdelcerro
3711 41717 jjdelcerro
        AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3712
                .getSwingInstallerManager().createInstallPackageWizard(
3713
                        manager.getApplicationFolder(),
3714
                        manager.getInstallFolder());
3715
        installPackageWizard.setWizardActionListener(new InstallerWizardActionListener() {
3716
            public void finish(InstallerWizardPanel installerWizard) {
3717
                logger.info("Finish installation.");
3718
                System.exit(0);
3719
            }
3720 40435 jjdelcerro
3721 41717 jjdelcerro
            public void cancel(InstallerWizardPanel installerWizard) {
3722
                logger.info("Cancel installation.");
3723
                System.exit(0);
3724
            }
3725
        });
3726 40435 jjdelcerro
3727 41717 jjdelcerro
        // the wizard will show the Typical or Advanced mode option.
3728
        installPackageWizard.setAskTypicalOrCustom(true);
3729
        // default packages will be selected.
3730
        installPackageWizard.setSelectDefaultPackages(true);
3731 40435 jjdelcerro
3732 41717 jjdelcerro
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3733 40435 jjdelcerro
3734 41717 jjdelcerro
        frame.addWindowListener(new WindowListener() {
3735
            public void windowOpened(WindowEvent we) {
3736
                logger.info("Open window installation.");
3737
            }
3738 42362 jjdelcerro
3739 41717 jjdelcerro
            public void windowClosing(WindowEvent we) {
3740
                logger.info("Closing installation.");
3741
                System.exit(0);
3742
            }
3743 42362 jjdelcerro
3744 41717 jjdelcerro
            public void windowClosed(WindowEvent we) {
3745
                logger.info("Close installation.");
3746
                System.exit(0);
3747
            }
3748 42362 jjdelcerro
3749 41717 jjdelcerro
            public void windowIconified(WindowEvent we) {
3750
            }
3751 42362 jjdelcerro
3752 41717 jjdelcerro
            public void windowDeiconified(WindowEvent we) {
3753
            }
3754 42362 jjdelcerro
3755 41717 jjdelcerro
            public void windowActivated(WindowEvent we) {
3756
                logger.info("Activate window installation.");
3757
            }
3758 42362 jjdelcerro
3759 41717 jjdelcerro
            public void windowDeactivated(WindowEvent we) {
3760
                logger.info("Deactivate window installation.");
3761
            }
3762
        });
3763
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3764 40435 jjdelcerro
3765 41717 jjdelcerro
        frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3766
3767 42449 jjdelcerro
        URL iconURL = getClass().getResource("/images/main/install-icon.png");
3768
        if( iconURL!=null ) {
3769
            ImageIcon icon = new ImageIcon(iconURL);
3770
            frame.setIconImage(icon.getImage());
3771
        }
3772 41717 jjdelcerro
        frame.pack();
3773
        frame.setLocationRelativeTo(null);
3774
3775
        frame.setVisible(true);
3776
    }
3777
3778 42362 jjdelcerro
    public static String getInformation() {
3779
        return getInformation(null);
3780
    }
3781 40435 jjdelcerro
3782 42362 jjdelcerro
    private static final int INFO_OS_NAME = 0;
3783
    private static final int INFO_OS_ARCH = 1;
3784
    private static final int INFO_OS_VERSION = 2;
3785
    private static final int INFO_OS_ADITIONAL = 3;
3786
    private static final int INFO_JRE_VENDOR = 4;
3787
    private static final int INFO_JRE_VERSION = 5;
3788
    private static final int INFO_JRE_HOME = 6;
3789
    private static final int INFO_PROXY_HOST = 7;
3790
    private static final int INFO_PROXY_PORT = 8;
3791
    private static final int INFO_PROXY_USER = 9;
3792
    private static final int INFO_PROXY_PASSWORD = 10;
3793
    private static final int INFO_APP_LOCALE = 11;
3794
    private static final int INFO_APP_FOLDER = 12;
3795
    private static final int INFO_APP_HOME = 13;
3796
    private static final int INFO_APP_INSTALL_FOLDER = 14;
3797
    private static final int INFO_APP_PLUGINS_FOLDER = 15;
3798
    private static final int INFO_APP_THEME = 16;
3799
    private static final int INFO_APP_SKIN = 17;
3800
    private static final int INFO_PACKAGES = 18;
3801 41775 fdiaz
3802 42362 jjdelcerro
    public static String getInformation(PackageInfo[] pkgs) {
3803 41775 fdiaz
3804 42362 jjdelcerro
        String template = "OS\n"
3805
                + "    name    : {" + INFO_OS_NAME + "}\n"
3806
                + "    arch    : {" + INFO_OS_ARCH + "}\n"
3807
                + "    version : {" + INFO_OS_VERSION + "} \n"
3808
                + "{" + INFO_OS_ADITIONAL + "}"
3809
                + "JRE\n"
3810
                + "    vendor  : {" + INFO_JRE_VENDOR + "}\n"
3811
                + "    version : {" + INFO_JRE_VERSION + "}\n"
3812
                + "    home    : {" + INFO_JRE_HOME + "}\n"
3813
                + "HTTP Proxy\n"
3814
                + "    http.proxyHost     : {" + INFO_PROXY_HOST + "}\n"
3815
                + "    http.proxyPort     : {" + INFO_PROXY_PORT + "}\n"
3816
                + "    http.proxyUserName : {" + INFO_PROXY_USER + "}\n"
3817
                + "    http.proxyPassword : {" + INFO_PROXY_PASSWORD + "}\n"
3818
                + "Application\n"
3819
                + "    locale language         : {" + INFO_APP_LOCALE + "}\n"
3820
                + "    application forlder     : {" + INFO_APP_FOLDER + "}\n"
3821
                + "    application home forlder: {" + INFO_APP_HOME + "}\n"
3822
                + "    install forlder         : {" + INFO_APP_INSTALL_FOLDER + "}\n"
3823
                + "    plugins forlder         : {" + INFO_APP_PLUGINS_FOLDER + "}\n"
3824
                + "    theme                   : {" + INFO_APP_THEME + "}\n"
3825
                + "    Skin                    : {" + INFO_APP_SKIN + "}\n"
3826
                + "Installed packages\n"
3827
                + "{" + INFO_PACKAGES + "}";
3828 41775 fdiaz
3829 42362 jjdelcerro
        String values[] = new String[INFO_PACKAGES + 1];
3830 40435 jjdelcerro
3831 42362 jjdelcerro
        PluginsManager pluginmgr = PluginsLocator.getManager();
3832
        LocaleManager localemgr = PluginsLocator.getLocaleManager();
3833 41775 fdiaz
3834 42362 jjdelcerro
        Properties props = System.getProperties();
3835 41775 fdiaz
3836 42362 jjdelcerro
        // OS information
3837
        values[INFO_OS_NAME] = props.getProperty("os.name");
3838
        values[INFO_OS_ARCH] = props.getProperty("os.arch");
3839
        values[INFO_OS_VERSION] = props.getProperty("os.version");
3840 41775 fdiaz
3841 42362 jjdelcerro
        if (values[INFO_OS_NAME].startsWith("Linux")) {
3842
            try {
3843
                StringWriter writer = new StringWriter();
3844 40435 jjdelcerro
3845 42362 jjdelcerro
                String[] command = {"lsb_release", "-a"};
3846
                Process p = Runtime.getRuntime().exec(command);
3847
                InputStream is = p.getInputStream();
3848
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
3849
                String line;
3850
                while ((line = reader.readLine()) != null) {
3851
                    writer.write("    " + line + "\n");
3852 41706 jjdelcerro
                }
3853 42362 jjdelcerro
                values[INFO_OS_ADITIONAL] = writer.toString();
3854
            } catch (Exception ex) {
3855
                logger.warn("Can't get detailled os information (lsb_release -a).", ex);
3856 41706 jjdelcerro
            }
3857 42362 jjdelcerro
        }
3858 40435 jjdelcerro
3859 42362 jjdelcerro
        values[INFO_JRE_VENDOR] = props.getProperty("java.vendor");
3860
        values[INFO_JRE_VERSION] = props.getProperty("java.version");
3861
        values[INFO_JRE_HOME] = props.getProperty("java.home");
3862
        values[INFO_PROXY_HOST] = props.getProperty("http.proxyHost");
3863
        values[INFO_PROXY_PORT] = props.getProperty("http.proxyPort");
3864
        values[INFO_PROXY_USER] = props.getProperty("http.proxyUserName");
3865 40435 jjdelcerro
3866 42362 jjdelcerro
        if (props.get("http.proxyPassword") == null) {
3867
            values[INFO_PROXY_PASSWORD] = "(null)";
3868
        } else {
3869
            values[INFO_PROXY_PASSWORD] = "***********";
3870
        }
3871 40435 jjdelcerro
3872 42362 jjdelcerro
        try {
3873
            values[INFO_APP_SKIN] = MDIManagerFactory.getSkinExtension().getClassName();
3874
        } catch (Throwable e) {
3875
            values[INFO_APP_SKIN] = "(unknow)";
3876
        }
3877
        values[INFO_APP_LOCALE] = localemgr.getCurrentLocale().toString();
3878
        values[INFO_APP_FOLDER] = pluginmgr.getApplicationFolder().getAbsolutePath();
3879
        values[INFO_APP_HOME] = pluginmgr.getApplicationHomeFolder().getAbsolutePath();
3880
        values[INFO_APP_INSTALL_FOLDER] = pluginmgr.getInstallFolder().getAbsolutePath();
3881
        values[INFO_APP_PLUGINS_FOLDER] = StringUtils.join(pluginmgr.getPluginsFolders());
3882
        values[INFO_APP_THEME] = Launcher.theme.getSource().getAbsolutePath();
3883 40435 jjdelcerro
3884 42362 jjdelcerro
        try {
3885
            if (pkgs == null) {
3886
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3887
                pkgs = installmgr.getInstalledPackages();
3888 41706 jjdelcerro
            }
3889 42362 jjdelcerro
            StringWriter writer = new StringWriter();
3890
            for (int i = 0; i < pkgs.length; i++) {
3891
                writer.write("    ");
3892
                writer.write(pkgs[i].toStringCompact());
3893
                writer.write("\n");
3894
            }
3895
            values[INFO_PACKAGES] = writer.toString();
3896 41775 fdiaz
3897 42362 jjdelcerro
        } catch (Throwable e) {
3898
            logger.warn("Can't get installed package information.", e);
3899 41706 jjdelcerro
        }
3900 40435 jjdelcerro
3901 42362 jjdelcerro
        String s = MessageFormat.format(template, values);
3902
        return s;
3903
    }
3904 41775 fdiaz
3905 42362 jjdelcerro
    private void logger_info(String msg) {
3906
        String info[] = msg.split("\n");
3907
        for (int i = 0; i < info.length; i++) {
3908
            logger.info(info[i]);
3909
        }
3910
    }
3911 40435 jjdelcerro
3912 42362 jjdelcerro
    private void saveEnvironInformation(PackageInfo[] pkgs) {
3913
        PluginsManager manager = PluginsLocator.getManager();
3914
        File fout = new File(manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3915
        try {
3916
            FileUtils.write(fout, getInformation(pkgs));
3917
        } catch (IOException e) {
3918
            logger.info("Can't create '" + fout.getAbsolutePath() + "'");
3919
        }
3920
    }
3921 41775 fdiaz
3922 42362 jjdelcerro
    private void fixIncompatiblePlugins(PackageInfo[] installedPackages) {
3923
        final Set<String> incompatiblePlugins = new HashSet<String>();
3924 41775 fdiaz
3925 42362 jjdelcerro
        // Add installed packages to a Map to optimize searchs
3926
        final Map<String, PackageInfo> packages = new HashMap<String, PackageInfo>();
3927
        for (int i = 0; i < installedPackages.length; i++) {
3928
            packages.put(installedPackages[i].getCode(), installedPackages[i]);
3929
        }
3930
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
3931
        while (it.hasNext()) {
3932
            List<String> pluginNames = new ArrayList<String>();
3933
            Entry<String, PluginConfig> entry = it.next();
3934
            PluginConfig pluginConfig = entry.getValue();
3935
            pluginNames.add(entry.getKey());
3936
3937 40819 jjdelcerro
                        // Locate the package for this plugin.
3938 42362 jjdelcerro
            // Be care whith alias
3939
            String[] aliases = pluginsConfig.getAliases(pluginConfig);
3940
            if (aliases != null) {
3941
                for (int i = 0; i < aliases.length; i++) {
3942
                    pluginNames.add(aliases[i]);
3943
                }
3944
            }
3945
            PackageInfo pkg = null;
3946
            for (int n = 0; n < pluginNames.size(); n++) {
3947
                pkg = packages.get(pluginNames.get(n));
3948
                if (pkg != null) {
3949
                    break;
3950
                }
3951
            }
3952 41775 fdiaz
3953 42362 jjdelcerro
            // If package is found verify dependencies
3954
            if (pkg != null) {
3955
                Dependencies dependencies = pkg.getDependencies();
3956
                for (int i = 0; i < dependencies.size(); i++) {
3957
                    Dependency dependency = (Dependency) dependencies.get(i);
3958
                    if (Dependency.CONFLICT.equalsIgnoreCase(dependency.getType())) {
3959
                        String code = dependency.getCode();
3960
                        if (pluginsConfig.get(code) != null) {
3961
                            incompatiblePlugins.add(pkg.getCode());
3962
                            incompatiblePlugins.add(code);
3963
                        }
3964
                    }
3965
                }
3966
            }
3967
        }
3968
        if (incompatiblePlugins.isEmpty()) {
3969
            return;
3970
        }
3971
        splashWindow.toBack();
3972
        DisablePluginsConflictingDialog dlg = new DisablePluginsConflictingDialog(packages, incompatiblePlugins);
3973
        dlg.setVisible(true);
3974
        splashWindow.toFront();
3975
        switch (dlg.getAction()) {
3976
            case DisablePluginsConflictingDialog.CLOSE:
3977
                System.exit(0);
3978
                break;
3979
            case DisablePluginsConflictingDialog.CONTINUE:
3980
                break;
3981
        }
3982
        List<String> pluginsToDissable = dlg.getPluginNamesToDisable();
3983
        if (pluginsToDissable == null) {
3984
            return;
3985
        }
3986 41775 fdiaz
3987 42362 jjdelcerro
        Iterator<String> it2 = pluginsToDissable.iterator();
3988
        while (it2.hasNext()) {
3989
            String pluginName = it2.next();
3990
            logger.info("Dissabling plugin '" + pluginName + "' by user action.");
3991
            pluginsConfig.remove(pluginName);
3992
        }
3993
    }
3994 41775 fdiaz
3995 42362 jjdelcerro
    private class DisablePluginsConflictingDialog extends JDialog {
3996 41775 fdiaz
3997 42362 jjdelcerro
        public static final int CONTINUE = 0;
3998
        public static final int CLOSE = 1;
3999 41775 fdiaz
4000 42362 jjdelcerro
        private DisablePluginsConflictingLayoutPanel contents;
4001
        private int action = 0;
4002
        private List<Item> incompatiblePlugins = null;
4003
        private Map<String, PackageInfo> packages;
4004 41775 fdiaz
4005 42362 jjdelcerro
        private class Item {
4006 40821 jjdelcerro
4007 42362 jjdelcerro
            private String code;
4008
            private PackageInfo pkg;
4009 40821 jjdelcerro
4010 42362 jjdelcerro
            public Item(String code, PackageInfo pkg) {
4011
                this.code = code;
4012
                this.pkg = pkg;
4013
            }
4014 41775 fdiaz
4015 42362 jjdelcerro
            public String toString() {
4016
                if (this.pkg == null) {
4017
                    return code;
4018
                }
4019
                return this.pkg.getName() + " (" + this.pkg.getCode() + ")";
4020
            }
4021 41775 fdiaz
4022 42362 jjdelcerro
            public String getCode() {
4023
                if (pkg == null) {
4024
                    return code;
4025
                }
4026
                return pkg.getCode();
4027
            }
4028
        }
4029 41775 fdiaz
4030 42362 jjdelcerro
        DisablePluginsConflictingDialog(Map<String, PackageInfo> packages, Set<String> incompatiblePlugins) {
4031
            super((Frame) null, "", true);
4032
            this.setTitle(translate("_Conflicting_plugins"));
4033 41775 fdiaz
4034 42362 jjdelcerro
            this.packages = packages;
4035 40821 jjdelcerro
4036 42362 jjdelcerro
            this.incompatiblePlugins = new ArrayList<Item>();
4037
            Item item = null;
4038
            Iterator<String> it = incompatiblePlugins.iterator();
4039
            while (it.hasNext()) {
4040
                String code = it.next();
4041
                item = new Item(code, packages.get(code));
4042
                this.incompatiblePlugins.add(item);
4043
                logger.info("Found plugin '" + item.getCode() + "' incopatibles with each other.");
4044
            }
4045
            initComponents();
4046
        }
4047 40821 jjdelcerro
4048 42362 jjdelcerro
        private void initComponents() {
4049
            this.contents = new DisablePluginsConflictingLayoutPanel();
4050 41775 fdiaz
4051 42362 jjdelcerro
            doTranslations();
4052 41775 fdiaz
4053 42362 jjdelcerro
            this.contents.buttonClose.addActionListener(new ActionListener() {
4054
                public void actionPerformed(ActionEvent arg0) {
4055
                    doClose();
4056
                }
4057
            });
4058
            this.contents.buttonContinue.addActionListener(new ActionListener() {
4059
                public void actionPerformed(ActionEvent arg0) {
4060
                    doContinue();
4061
                }
4062
            });
4063
            this.contents.pluginList.setModel(new DefaultListModel(this.incompatiblePlugins));
4064
            ListSelectionModel sm = this.contents.pluginList.getSelectionModel();
4065
            sm.setSelectionMode(sm.MULTIPLE_INTERVAL_SELECTION);
4066
            this.setContentPane(this.contents);
4067
            this.pack();
4068 41775 fdiaz
4069 42362 jjdelcerro
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
4070
            setLocation((screenSize.width / 2) - (this.getWidth() / 2),
4071
                    (screenSize.height / 2) - (this.getHeight() / 2));
4072
        }
4073 41775 fdiaz
4074 42362 jjdelcerro
        private void doTranslations() {
4075
            DisablePluginsConflictingLayoutPanel c = this.contents;
4076
            c.lblConflict.setText(translate("_Some_of_plugins_installed_conflict_with_each_other"));
4077
            c.lblSelectPluginToDisable.setText(translate("_Select_the_plugins_that_you_want_to_disable_and_click_the_continue_button"));
4078
            c.lblClickContinue.setText(translate("_You_can_click_on_continue_button_directly_if_you_dont_want_to_disable_any_plugins"));
4079
            c.lblClickClose.setText(translate("_Or_click_the_close_button_to_close_the_application"));
4080
            c.buttonClose.setText(translate("_Close"));
4081
            c.buttonContinue.setText(translate("_Continue"));
4082
        }
4083 41775 fdiaz
4084 42362 jjdelcerro
        private String translate(String msg) {
4085
            return PluginServices.getText(this, msg);
4086
        }
4087 40821 jjdelcerro
4088 42362 jjdelcerro
        private void doClose() {
4089
            this.action = CLOSE;
4090
            this.setVisible(false);
4091
        }
4092 41775 fdiaz
4093 42362 jjdelcerro
        private void doContinue() {
4094
            this.action = CONTINUE;
4095
            this.setVisible(false);
4096
        }
4097 41775 fdiaz
4098 42362 jjdelcerro
        public int getAction() {
4099
            return this.action;
4100
        }
4101
4102
        public List<String> getPluginNamesToDisable() {
4103
            if (this.action == CLOSE) {
4104
                return null;
4105
            }
4106
            Object[] selecteds = null;
4107
            selecteds = (Object[]) this.contents.pluginList.getSelectedValues();
4108
            if (selecteds == null || selecteds.length < 1) {
4109
                return null;
4110
            }
4111
            List<String> values = new ArrayList<String>();
4112
            for (int i = 0; i < selecteds.length; i++) {
4113
                values.add(((Item) selecteds[i]).getCode());
4114
            }
4115
            return values;
4116
        }
4117
    }
4118
4119 41696 jjdelcerro
    private void initializeIdentityManagement(File pluginsFolder) {
4120
        File identityManagementConfigFile = null;
4121
        PluginServices plugin = null;
4122
        Iterator<Entry<String, PluginConfig>> it = pluginsConfig.entrySet().iterator();
4123 42362 jjdelcerro
        while (it.hasNext()) {
4124 41696 jjdelcerro
            Entry<String, PluginConfig> entry = it.next();
4125 42362 jjdelcerro
            File pluginFolder = new File(pluginsFolder, entry.getKey());
4126
            File f = new File(pluginFolder, "identity-management.ini");
4127
            if (f.exists()) {
4128
                if (identityManagementConfigFile != null) {
4129 41696 jjdelcerro
                    logger.warn("Too many identity-managemnt plugins. Disable all.");
4130
                } else {
4131
                    identityManagementConfigFile = f;
4132
                    plugin = PluginServices.getPluginServices(entry.getKey());
4133
                }
4134
            }
4135
        }
4136 42362 jjdelcerro
        if (identityManagementConfigFile == null || plugin == null) {
4137 41696 jjdelcerro
            return;
4138
        }
4139
        if (!identityManagementConfigFile.canRead()) {
4140 42362 jjdelcerro
            return;
4141 41696 jjdelcerro
        }
4142
        PropertiesConfiguration identityManagementConfig = null;
4143
        try {
4144
            identityManagementConfig = new PropertiesConfiguration(identityManagementConfigFile);
4145
        } catch (Exception ex) {
4146
            logger.warn("Can't open identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.", ex);
4147
            return;
4148
        }
4149
        String identityManagerClassName = identityManagementConfig.getString("IdentityManager", null);
4150
        String identityManagementInitializerClassName = identityManagementConfig.getString("IdentityManagementInitializer", null);
4151
        try {
4152 42362 jjdelcerro
            if (identityManagerClassName != null) {
4153 41696 jjdelcerro
                Class identityManagerClass = plugin.getClassLoader().loadClass(identityManagerClassName);
4154
                ToolsLocator.registerIdentityManager(identityManagerClass);
4155
            } else {
4156
                logger.info("Entry IdentityManager not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4157
            }
4158
4159 42362 jjdelcerro
            if (identityManagementInitializerClassName != null) {
4160 41696 jjdelcerro
                Class identityManagerInitializerClass = plugin.getClassLoader().loadClass(identityManagementInitializerClassName);
4161
                Runnable identityManagerInitializer = (Runnable) identityManagerInitializerClass.newInstance();
4162
                identityManagerInitializer.run();
4163
            } else {
4164
                logger.info("Entry IdentityManagementInitializer not found in identity management config file '" + identityManagementConfigFile.getAbsolutePath() + "'.");
4165
            }
4166
4167
        } catch (Exception ex) {
4168 42362 jjdelcerro
            logger.warn("Can't initialize the identity manager from '" + identityManagementConfigFile.getAbsolutePath() + ".", ex);
4169 41696 jjdelcerro
            return;
4170
        }
4171 42362 jjdelcerro
        logger.info("Loaded an identity manager from plugin '" + plugin.getPluginName() + ".");
4172 41696 jjdelcerro
    }
4173 41775 fdiaz
4174 40435 jjdelcerro
}