Statistics
| Revision:

root / branches / v2_0_0_prep / frameworks / _fwAndami / src / org / gvsig / andami / Launcher.java @ 38094

History | View | Annotate | Download (93.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004-2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.andami;
42

    
43
import java.awt.BorderLayout;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.EventQueue;
47
import java.awt.Frame;
48
import java.awt.KeyboardFocusManager;
49
import java.awt.Point;
50
import java.awt.Toolkit;
51
import java.io.BufferedOutputStream;
52
import java.io.BufferedReader;
53
import java.io.File;
54
import java.io.FileFilter;
55
import java.io.FileInputStream;
56
import java.io.FileNotFoundException;
57
import java.io.FileOutputStream;
58
import java.io.FileReader;
59
import java.io.IOException;
60
import java.io.InputStream;
61
import java.io.InputStreamReader;
62
import java.io.OutputStreamWriter;
63
import java.io.Reader;
64
import java.io.StringWriter;
65
import java.net.Authenticator;
66
import java.net.MalformedURLException;
67
import java.net.PasswordAuthentication;
68
import java.net.URL;
69
import java.net.URLClassLoader;
70
import java.nio.channels.FileChannel;
71
import java.security.AllPermission;
72
import java.security.CodeSource;
73
import java.security.PermissionCollection;
74
import java.security.Permissions;
75
import java.security.Policy;
76
import java.text.MessageFormat;
77
import java.util.ArrayList;
78
import java.util.Comparator;
79
import java.util.HashMap;
80
import java.util.HashSet;
81
import java.util.Iterator;
82
import java.util.List;
83
import java.util.Locale;
84
import java.util.Map;
85
import java.util.Properties;
86
import java.util.Set;
87
import java.util.TreeSet;
88
import java.util.prefs.Preferences;
89

    
90
import javax.swing.ImageIcon;
91
import javax.swing.JButton;
92
import javax.swing.JComponent;
93
import javax.swing.JFrame;
94
import javax.swing.JOptionPane;
95
import javax.swing.JPopupMenu;
96
import javax.swing.SwingUtilities;
97
import javax.swing.UIManager;
98

    
99
import org.apache.commons.cli.CommandLine;
100
import org.apache.commons.cli.CommandLineParser;
101
import org.apache.commons.cli.Options;
102
import org.apache.commons.cli.ParseException;
103
import org.apache.commons.cli.PosixParser;
104
import org.apache.log4j.AppenderSkeleton;
105
import org.apache.log4j.PatternLayout;
106
import org.apache.log4j.PropertyConfigurator;
107
import org.apache.log4j.RollingFileAppender;
108
import org.apache.log4j.spi.LoggingEvent;
109
import org.exolab.castor.xml.MarshalException;
110
import org.exolab.castor.xml.ValidationException;
111
import org.slf4j.Logger;
112
import org.slf4j.LoggerFactory;
113

    
114
import org.gvsig.andami.authentication.IAuthentication;
115
import org.gvsig.andami.authentication.LoginUI;
116
import org.gvsig.andami.config.generate.Andami;
117
import org.gvsig.andami.config.generate.AndamiConfig;
118
import org.gvsig.andami.config.generate.Plugin;
119
import org.gvsig.andami.iconthemes.IIconTheme;
120
import org.gvsig.andami.iconthemes.IconThemeManager;
121
import org.gvsig.andami.messages.Messages;
122
import org.gvsig.andami.messages.NotificationManager;
123
import org.gvsig.andami.plugins.ExclusiveUIExtension;
124
import org.gvsig.andami.plugins.ExtensionDecorator;
125
import org.gvsig.andami.plugins.IExtension;
126
import org.gvsig.andami.plugins.PluginClassLoader;
127
import org.gvsig.andami.plugins.config.generate.ActionTool;
128
import org.gvsig.andami.plugins.config.generate.ComboButton;
129
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
130
import org.gvsig.andami.plugins.config.generate.ComboScale;
131
import org.gvsig.andami.plugins.config.generate.Depends;
132
import org.gvsig.andami.plugins.config.generate.Extension;
133
import org.gvsig.andami.plugins.config.generate.Extensions;
134
import org.gvsig.andami.plugins.config.generate.LabelSet;
135
import org.gvsig.andami.plugins.config.generate.Menu;
136
import org.gvsig.andami.plugins.config.generate.PluginConfig;
137
import org.gvsig.andami.plugins.config.generate.PopupMenu;
138
import org.gvsig.andami.plugins.config.generate.PopupMenus;
139
import org.gvsig.andami.plugins.config.generate.SelectableTool;
140
import org.gvsig.andami.plugins.config.generate.SkinExtension;
141
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
142
import org.gvsig.andami.plugins.config.generate.ToolBar;
143
import org.gvsig.andami.plugins.status.IExtensionStatus;
144
import org.gvsig.andami.plugins.status.IUnsavedData;
145
import org.gvsig.andami.ui.AndamiEventQueue;
146
import org.gvsig.andami.ui.MDIManagerLoadException;
147
import org.gvsig.andami.ui.ToolsWindowManager;
148
import org.gvsig.andami.ui.fonts.FontUtils;
149
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
150
import org.gvsig.andami.ui.mdiFrame.NewStatusBar;
151
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
152
import org.gvsig.andami.ui.splash.MultiSplashWindow;
153
import org.gvsig.andami.ui.theme.Theme;
154
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
155
import org.gvsig.installer.lib.api.InstallerLocator;
156
import org.gvsig.installer.lib.api.InstallerManager;
157
import org.gvsig.installer.lib.api.PackageInfo;
158
import org.gvsig.installer.swing.api.SwingInstallerLocator;
159
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
160
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
161
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
162
import org.gvsig.tools.exception.ListBaseException;
163
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
164
import org.gvsig.tools.swing.api.ToolsSwingLocator;
165
import org.gvsig.utils.DateTime;
166
import org.gvsig.utils.XMLEntity;
167
import org.gvsig.utils.xml.XMLEncodingUtils;
168
import org.gvsig.utils.xmlEntity.generate.XmlTag;
169

    
170
/**
171
 * <p>
172
 * Andami's launching class. This is the class used to create the Andami's
173
 * plugin environment.<br>
174
 * </p>
175
 * 
176
 * <p>
177
 * <b>Syntax:</b> <br>
178
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or
179
 * semicolon-separated(windows) list of files containg base library of classes}]
180
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
181
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
182
 * [{list of additional custom application arguments separated by spaces}]
183
 * </p>
184
 * 
185
 * 
186
 * @author $author$
187
 * @version $Revision: 38094 $
188
 */
189
public class Launcher {
190

    
191
        protected static Logger logger = LoggerFactory.getLogger(Launcher.class
192
                        .getName());
193
        protected static Preferences prefs = Preferences.userRoot().node(
194
                        "gvsig.connection");
195
        protected static AndamiConfig andamiConfig;
196
        protected static MultiSplashWindow splashWindow;
197
        protected static String appName;
198
        protected static Locale locale;
199
        protected static HashMap<String, PluginConfig> pluginsConfig = new HashMap<String, PluginConfig>();
200
        protected static HashMap<String, PluginServices> pluginsServices = new HashMap<String, PluginServices>();
201
        protected static MDIFrame frame;
202
        protected static HashMap<Class<? extends IExtension>, ExtensionDecorator> classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
203
        protected static String andamiConfigPath;
204
        protected static final String nonWinDefaultLookAndFeel = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
205

    
206
        protected static ArrayList<String> pluginsOrdered = new ArrayList<String>();
207
        protected static ArrayList<IExtension> extensions = new ArrayList<IExtension>();
208
        protected static String appHomeDir = null;
209
        // it seems castor uses this encoding
210
        protected static final String CASTORENCODING = "UTF8";
211

    
212
        protected static ListBaseException launcherrors = null;
213

    
214
        protected static Theme theme = null;
215

    
216
        private static final class ProxyAuth extends Authenticator {
217

    
218
                private PasswordAuthentication auth;
219

    
220
                private ProxyAuth(String user, String pass) {
221
                        auth = new PasswordAuthentication(user, pass.toCharArray());
222
                }
223

    
224
                protected PasswordAuthentication getPasswordAuthentication() {
225
                        return auth;
226
                }
227
        }
228

    
229
        public static void main(String[] args) throws Exception {
230
                Launcher launcher = new Launcher();
231
                boolean install = false;
232
                for (int i = 0; i < args.length; i++) {
233
                        if (args[i].equalsIgnoreCase("--install")) {
234
                                install = true;
235
                        }
236
                }
237
                try {
238
                        if (install) {
239
                                launcher.doInstall(args);
240
                        } else {
241
                                launcher.doMain(args);
242
                        }
243
                } catch (Exception e) {
244
                        logger.error("excepci?n al arrancar", e);
245
                        System.exit(-1);
246
                }
247
        }
248

    
249
        protected void downloadExtensions(String extDir) {
250
                // do nothing
251
        }
252

    
253
        public static class LaunchException extends ListBaseException {
254

    
255
                private static final long serialVersionUID = 4541192746962684705L;
256

    
257
                public LaunchException() {
258
                        super("Errors in initialization of application.",
259
                                        "_errors_in_initialization_of_application",
260
                                        serialVersionUID);
261
                }
262

    
263
        }
264

    
265
        protected void addError(Throwable ex) {
266
                if (launcherrors == null) {
267
                        launcherrors = new LaunchException();
268
                }
269
                launcherrors.add(ex);
270
        }
271

    
272
        protected void addError(String msg, Throwable cause) {
273
                logger.error(msg, cause);
274
                this.addError(new RuntimeException(msg, cause));
275
        }
276

    
277
        protected void addError(String msg) {
278
                this.addError(msg, null);
279
        }
280

    
281
        public void doMain(String[] args) throws Exception {
282

    
283
                if (args.length < 1) {
284
                        System.err
285
                                        .println("Uso: Launcher appName plugins-directory [language=locale]");
286
                }
287

    
288
                initializeApp(args);
289

    
290
                // Solucionamos el problema de permisos que se produc?a con Java
291
                // Web Start con este c?digo.
292
                // System.setSecurityManager(null);
293
                Policy.setPolicy(new Policy() {
294

    
295
                        public PermissionCollection getPermissions(CodeSource codesource) {
296
                                Permissions perms = new Permissions();
297
                                perms.add(new AllPermission());
298
                                return (perms);
299
                        }
300

    
301
                        public void refresh() {
302
                        }
303
                });
304

    
305
                try {
306
                        initIconThemes();
307
                } catch (Exception ex) {
308
                        this.addError("Can't initialize icon theme", ex);
309
                }
310
                // Registramos los iconos base
311
                try {
312
                        registerIcons();
313
                } catch (Exception ex) {
314
                        this.addError("Can't register icons", ex);
315
                }
316
                validate();
317

    
318
                // Obtener la personalizaci?n de la aplicaci?n.
319
                try {
320
                        logger.info("Initialize andami theme");
321
                        theme = getTheme(andamiConfig.getPluginsDirectory());
322
                } catch (Exception ex) {
323
                        this.addError("Can't get personalized theme for the application",
324
                                        ex);
325
                }
326

    
327
                // Mostrar la ventana de inicio
328
                Frame f = new Frame();
329
                splashWindow = new MultiSplashWindow(f, theme, 190);
330

    
331
                // 1. Ponemos los datos del proxy
332
                splashWindow.process(10, PluginServices.getText(Launcher.class,
333
                                "SplashWindow.configuring_proxy"));
334
                logger.info("Configute http proxy");
335
                configureProxy();
336

    
337
                // 2. TODO Buscar actualizaciones de los plugins
338
                splashWindow.process(20, PluginServices.getText(Launcher.class,
339
                                "SplashWindow.looking_for_updates"));
340
                try {
341
                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
342
                } catch (Exception ex) {
343
                        this.addError("Can't downloads plugins", ex);
344
                }
345

    
346
                // 2.5. Initialize andami libraries
347
                splashWindow.process(25, PluginServices.getText(Launcher.class,
348
                                "SplashWindow.initialize_andami_libraries"));
349
                new DefaultLibrariesInitializer().fullInitialize(true);
350
                logger.info("Dump system information");
351
                logger_info(getInformation());
352

    
353
                // 3. Se leen los config.xml de los plugins -----++++
354
                splashWindow.process(30, PluginServices.getText(Launcher.class,
355
                                "SplashWindow.reading_plugins_config.xml"));
356
                try {
357
                        logger.info("Load plugins information");
358
                        this.loadPlugins(andamiConfig.getPluginsDirectory());
359
                } catch (Exception ex) {
360
                        this.addError("Can't load plugins", ex);
361
                }
362

    
363
                // 4. Se configura el classloader del plugin
364
                splashWindow.process(40, PluginServices.getText(Launcher.class,
365
                                "SplashWindow.setting_up_class_loaders"));
366
                try {
367
                        logger.info("Configure plugins class loader");
368
                        this.pluginsClassLoaders();
369
                } catch (Exception ex) {
370
                        this.addError("Can't initialize plugin's classloaders  ", ex);
371
                }
372

    
373
                // 5. Initialize libraries
374
                splashWindow.process(50, PluginServices.getText(Launcher.class,
375
                                "SplashWindow.initialize_libraries"));
376
                initializeLibraries();
377

    
378
                // 6. Se carga un Skin si alguno ide los plugins trae informaci?n
379
                // para ello
380
                splashWindow.process(60, PluginServices.getText(Launcher.class,
381
                                "SplashWindow.looking_for_a_skin"));
382
                // skinPlugin( "com.iver.core.mdiManager.NewSkin");
383
                logger.info("Initialize skin");
384
                skinPlugin(null);
385

    
386
                // 7. Se configura la cola de eventos
387
                splashWindow.process(70, PluginServices.getText(Launcher.class,
388
                                "setting_up_event_queue"));
389
                EventQueue waitQueue = new AndamiEventQueue();
390
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
391

    
392
                // 8. Se configura la mensajer?a del plugin
393
                splashWindow.process(80, PluginServices.getText(Launcher.class,
394
                                "SplashWindow.starting_plugin_internationalization_system"));
395
                pluginsMessages();
396

    
397
                // 9. Se modifica el andami-config con los plugins nuevos
398
                splashWindow.process(90, PluginServices.getText(Launcher.class,
399
                                "SplashWindow.looking_for_a_skin"));
400
                updateAndamiConfig();
401

    
402
                frame = new MDIFrame();
403
                // 10. Se configura el nombre e icono de la aplicaci?n
404
                splashWindow.process(100, PluginServices.getText(Launcher.class,
405
                                "SplashWindow.setting_up_applications_name_and_icons"));
406
                frameIcon(theme);
407

    
408
                // 11. Se prepara el MainFrame para albergar las extensiones
409
                splashWindow.process(110, PluginServices.getText(Launcher.class,
410
                                "SplashWindow.preparing_workbench"));
411
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
412

    
413
                SwingUtilities.invokeAndWait(new Runnable() {
414

    
415
                        public void run() {
416
                                frame.init();
417
                        }
418
                });
419
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
420

    
421
                // 12. Leer el fichero de persistencia
422
                // info de los plugins
423
                // bookmarks de los plugins
424
                splashWindow.process(120, PluginServices.getText(Launcher.class,
425
                                "SplashWindow.loading_plugin_settings"));
426
                loadPluginsPersistence();
427

    
428
                // Se instalan los controles del skin
429
                // 13. Se inicializan todas las extensiones de todos los plugins
430
                splashWindow.process(130, PluginServices.getText(Launcher.class,
431
                                "SplashWindow.initializing_extensions"));
432
                SwingUtilities.invokeAndWait(new Runnable() {
433

    
434
                        public void run() {
435
                                initializeExtensions();
436
                        }
437
                });
438

    
439
                // 14. Se inicializan la extensi?n exclusiva
440
                splashWindow.process(140, PluginServices.getText(Launcher.class,
441
                                "SplashWindow.setting_up_master_extension"));
442
                SwingUtilities.invokeAndWait(new Runnable() {
443

    
444
                        public void run() {
445
                                initializeExclusiveUIExtension();
446
                        }
447
                });
448
                frame.setClassesExtensions(classesExtensions);
449

    
450
                // 15. Se instalan los controles de las extensiones de los plugins
451
                splashWindow.process(150, PluginServices.getText(Launcher.class,
452
                                "SplashWindow.installing_extensions_controls"));
453
                SwingUtilities.invokeAndWait(new Runnable() {
454

    
455
                        public void run() {
456
                                installPluginsControls();
457

    
458
                        }
459
                });
460

    
461
                // 16. Se instalan los menus de las extensiones de los plugins
462
                splashWindow.process(160, PluginServices.getText(Launcher.class,
463
                                "SplashWindow.installing_extensions_menus"));
464
                SwingUtilities.invokeAndWait(new Runnable() {
465

    
466
                        public void run() {
467
                                installPluginsMenus();
468

    
469
                        }
470
                });
471

    
472
                // 17. Se instalan las etiquetas de las extensiones de los plugins
473
                splashWindow.process(170, PluginServices.getText(Launcher.class,
474
                                "SplashWindow.installing_extensions_labels"));
475
                SwingUtilities.invokeAndWait(new Runnable() {
476

    
477
                        public void run() {
478
                                installPluginsLabels();
479

    
480
                        }
481
                });
482

    
483
                // 18. Se instalan los bookmarks de los plugins
484

    
485
                // 19. Se muestra el frame principal
486
                splashWindow.process(180, PluginServices.getText(Launcher.class,
487
                                "creating_main_window"));
488
                frame.setVisible(true);
489

    
490
                File defaultAddonsRepository = PluginsLocator.getManager()
491
                                .getPluginsFolder();
492
                InstallerManager installerManager = InstallerLocator
493
                                .getInstallerManager();
494
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
495
                installerManager
496
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
497

    
498
                // 19. Se ejecuta el postInitialize
499
                splashWindow.process(190, PluginServices.getText(Launcher.class,
500
                                "SplashWindow.post_initializing_extensions"));
501
                SwingUtilities.invokeAndWait(new Runnable() {
502

    
503
                        public void run() {
504
                                postInitializeExtensions();
505

    
506
                        }
507
                });
508

    
509
                // Definimos un KeyEventDispatcher global para que las extensiones
510
                // puedan registrar sus "teclas r?pidas".
511
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher
512
                                .getInstance();
513
                KeyboardFocusManager.getCurrentKeyboardFocusManager()
514
                                .addKeyEventDispatcher(keyDispatcher);
515

    
516
                SwingUtilities.invokeAndWait(new Runnable() {
517

    
518
                        public void run() {
519
                                frame.enableControls();
520
                        }
521
                });
522
                splashWindow.close();
523
                if (launcherrors != null) {
524
                        NotificationManager.addError(launcherrors);
525
                }
526

    
527
                org.apache.log4j.Logger.getRootLogger().addAppender(
528
                                new NotificationAppender());
529

    
530
        }
531

    
532
        /**
533
     * 
534
     */
535
        private void initializeLibraries() {
536
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
537
                                pluginsOrdered.size() + 1);
538
                classLoaders.add(getClass().getClassLoader());
539
                Iterator<String> iter = pluginsOrdered.iterator();
540

    
541
                logger.debug("Initializing plugins libraries: ");
542
                while (iter.hasNext()) {
543
                        String pName = (String) iter.next();
544
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
545
                        classLoaders.add(ps.getClassLoader());
546
                }
547

    
548
                // Create the libraries initializer and
549
                // initialize the plugin libraries
550
                new DefaultLibrariesInitializer(classLoaders
551
                                .toArray(new ClassLoader[classLoaders.size()]))
552
                                .fullInitialize(true);
553

    
554
                // Remove them all, we don't need them anymore
555
                classLoaders.clear();
556
                classLoaders = null;
557
        }
558

    
559
        /**
560
         * @param args
561
         * @throws IOException
562
         * @throws ConfigurationException
563
         */
564
        private void initializeApp(String[] args) throws IOException,
565
                        ConfigurationException {
566
                if (!validJVM()) {
567
                        System.exit(-1);
568
                }
569

    
570
                // Clean temporal files
571
                Utilities.cleanUpTempFiles();
572

    
573
                appName = args[0];
574

    
575
                getOrCreateConfigFolder();
576

    
577
                configureLogging(appName);
578

    
579
                loadAndamiConfig(args[1]);
580

    
581
                // Hacemos visibles los argumentos como una propiedad est?tica
582
                // de plugin services para quien lo quiera usar (por ejemplo, para
583
                // cargar un proyecto por l?nea de comandos)
584
                PluginServices.setArguments(args);
585

    
586
                configureLocales(args);
587

    
588
                logger.info("Load and initialize andami and plugins libraries");
589
                // LibrariesInitializer libsInitializer =
590
                // new DefaultLibrariesInitializer();
591
                // libsInitializer.initialize(true);
592
                // libsInitializer.postInitialize(true);
593

    
594
                logger.info("Configure LookAndFeel");
595
                configureLookAndFeel();
596
        }
597

    
598
        /**
599
     * 
600
     */
601
        private void configureLookAndFeel() {
602
                // Se pone el lookAndFeel
603
                try {
604
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
605
                        if (lookAndFeel == null) {
606
                                lookAndFeel = getDefaultLookAndFeel();
607
                        }
608
                        UIManager.setLookAndFeel(lookAndFeel);
609
                } catch (Exception e) {
610
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
611
                }
612
                FontUtils.initFonts();
613
        }
614

    
615
        /**
616
         * @param args
617
         * @throws ConfigurationException
618
         */
619
        private void loadAndamiConfig(String pluginFolder)
620
                        throws ConfigurationException {
621
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
622
                // locale
623
                // Buscar actualizaci?nes al comenzar
624
                // Andami
625
                // Plugins
626
                // Directorio de las extensiones
627
                andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
628
                andamiConfigFromXML(andamiConfigPath);
629
                andamiConfig.setPluginsDirectory(pluginFolder);
630
        }
631

    
632
        /**
633
     * 
634
     */
635
        private void getOrCreateConfigFolder() {
636
                // Create application configuration folder
637
                appHomeDir = System.getProperty(appName + ".home");
638
                if (appHomeDir == null) {
639
                        appHomeDir = System.getProperty("user.home");
640
                }
641

    
642
                appHomeDir += File.separator + appName;
643
                File parent = new File(appHomeDir);
644
                parent.mkdirs();
645
        }
646

    
647
        /**
648
         * @param args
649
         * @throws IOException
650
         */
651
        private void configureLogging(String appName) throws IOException {
652
                // Configurar el log4j
653
                Launcher.class.getClassLoader().getResource(".");
654
                PropertyConfigurator.configure("log4j.properties");
655

    
656
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
657
                RollingFileAppender fa = new RollingFileAppender(l, appHomeDir
658
                                + File.separator + appName + ".log", false);
659
                fa.setMaxFileSize("512KB");
660
                fa.setMaxBackupIndex(3);
661
                org.apache.log4j.Logger.getRootLogger().addAppender(fa);
662
        }
663

    
664
        private class NotificationAppender extends AppenderSkeleton {
665

    
666
                @Override
667
                protected void append(LoggingEvent event) {
668
                        if (event.getLevel() == org.apache.log4j.Level.ERROR
669
                                        || event.getLevel() == org.apache.log4j.Level.FATAL) {
670
                                NotificationManager.dispatchError(event.getRenderedMessage(),
671
                                                null);
672
                                return;
673
                        }
674
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
675
                        // NotificationManager.dispatchWarning(event.getRenderedMessage(),
676
                        // null);
677
                        // return;
678
                        // }
679
                }
680

    
681
                @Override
682
                public void close() {
683
                        // TODO Auto-generated method stub
684

    
685
                }
686

    
687
                @Override
688
                public boolean requiresLayout() {
689
                        // TODO Auto-generated method stub
690
                        return false;
691
                }
692

    
693
        }
694

    
695
        /**
696
         * Return the directory applicaction is installed.
697
         */
698
        public static String getApplicationDirectory() {
699
                return new File("").getAbsolutePath();
700
        }
701

    
702
        private void registerIcons() {
703
                PluginServices.getIconTheme().registerDefault(
704
                                "login-gvsig",
705
                                LoginUI.class.getClassLoader().getResource(
706
                                                "images/login_gvsig.png"));
707
                PluginServices.getIconTheme().registerDefault(
708
                                "splash-gvsig",
709
                                MultiSplashWindow.class.getClassLoader().getResource(
710
                                                "images/splash.png"));
711
                PluginServices.getIconTheme().registerDefault(
712
                                "info-icon",
713
                                NewStatusBar.class.getClassLoader().getResource(
714
                                                "images/info.gif"));
715
                PluginServices.getIconTheme().registerDefault(
716
                                "error-icon",
717
                                NewStatusBar.class.getClassLoader().getResource(
718
                                                "images/error.gif"));
719
                PluginServices.getIconTheme().registerDefault(
720
                                "warning-icon",
721
                                NewStatusBar.class.getClassLoader().getResource(
722
                                                "images/warning.gif"));
723
                PluginServices.getIconTheme().registerDefault(
724
                                "no-icon",
725
                                NewStatusBar.class.getClassLoader().getResource(
726
                                                "images/no_icon.png"));
727
        }
728

    
729
        /**
730
         * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de la
731
         * aplicaci?n.
732
         * 
733
         * @return Theme
734
         */
735
        private Theme getTheme(String pluginsDirectory) {
736
                File themeFile = null;
737
                Theme theme = new Theme();
738

    
739
                // Try to get theme from args
740
                String name = PluginServices.getArgumentByName("andamiTheme");
741
                if (name != null) {
742
                        themeFile = new File(name);
743
                        logger.info("search andami-theme in {}", themeFile
744
                                        .getAbsolutePath());
745
                        if (themeFile.exists()) {
746
                                theme.readTheme(themeFile);
747
                                logger.info("andami-theme found in {}", themeFile
748
                                                .getAbsolutePath());
749
                                return theme;
750
                        }
751
                }
752

    
753
                // Try to get theme from a plugin
754
                File pluginsDir = new File(pluginsDirectory);
755
                if (!pluginsDir.isAbsolute()) {
756
                        pluginsDir = new File(System.getProperty("user.dir"),
757
                                        pluginsDirectory);
758
                }
759
                if (pluginsDir.exists()) {
760
                        logger.info("search andami-theme in plugins folder.");
761
                        File[] pluginDirs = pluginsDir.listFiles();
762
                        if (pluginDirs.length > 0) {
763
                                for (int i = 0; i < pluginDirs.length; i++) {
764
                                        File pluginThemeFile = new File(pluginDirs[i], "theme"
765
                                                        + File.separator + "andami-theme.xml");
766
                                        if (pluginThemeFile.exists()) {
767
                                                themeFile = pluginThemeFile;
768
                                                // This if is a hack to allow more themes than the
769
                                                // one available in org.gvsig.app. Remove this
770
                                                // when a the theme format is changed to allow for
771
                                                // priorities
772
                                                if (!"org.gvsig.app".equals(pluginDirs[i].getName())) {
773
                                                        break;
774
                                                }
775
                                        }
776
                                }
777
                        }
778
                }
779

    
780
                // The theme file will be the one into a plugin or by default the one
781
                // in the org.gvsig.app plugin
782
                if (themeFile != null && themeFile.exists()) {
783
                        theme.readTheme(themeFile);
784
                        logger.info("andami-theme found in plugin {}", themeFile
785
                                        .getAbsolutePath());
786
                        return theme;
787
                }
788

    
789
                // Try to get theme from dir gvSIG in user home
790
                themeFile = new File(getAppHomeDir(), "theme" + File.separator
791
                                + "andami-theme.xml");
792
                logger.info("search andami-theme in user's home {}", themeFile
793
                                .getAbsolutePath());
794
                if (themeFile.exists()) {
795
                        theme.readTheme(themeFile);
796
                        logger.info("andami-theme found in user's home {}", themeFile
797
                                        .getAbsolutePath());
798
                        return theme;
799
                }
800

    
801
                // Try to get theme from the instalation dir of gvSIG.
802
                themeFile = new File(getApplicationDirectory(), "theme"
803
                                + File.separator + "andami-theme.xml");
804
                logger.info("search andami-theme in installation folder {}", themeFile
805
                                .getAbsolutePath());
806
                if (themeFile.exists()) {
807
                        theme.readTheme(themeFile);
808
                        logger.info("andami-theme found in instalation folder {}",
809
                                        themeFile.getAbsolutePath());
810
                        return theme;
811
                }
812
                logger.info("Apply default andami-theme.");
813
                return theme;
814
        }
815

    
816
        /**
817
         * Establece los datos que ten?amos guardados respecto de la configuraci?n
818
         * del proxy.
819
         */
820
        private void configureProxy() {
821
                String host = prefs.get("firewall.http.host", "");
822
                String port = prefs.get("firewall.http.port", "");
823

    
824
                System.getProperties().put("http.proxyHost", host);
825
                System.getProperties().put("http.proxyPort", port);
826

    
827
                // Ponemos el usuario y clave del proxy, si existe
828
                String proxyUser = prefs.get("firewall.http.user", null);
829
                String proxyPassword = prefs.get("firewall.http.password", null);
830
                if (proxyUser != null) {
831
                        System.getProperties().put("http.proxyUserName", proxyUser);
832
                        System.getProperties().put("http.proxyPassword", proxyPassword);
833

    
834
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
835
                } else {
836
                        Authenticator.setDefault(new ProxyAuth("", ""));
837
                }
838
        }
839

    
840
        /**
841
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal
842
         * de Andami. TODO Pendiente de ver como se asigna un pluginServices para el
843
         * launcher.
844
         * 
845
         * @author LWS
846
         */
847
        private void restoreMDIStatus(XMLEntity xml) {
848
                if (xml == null) {
849
                        xml = new XMLEntity();
850
                }
851
                // restore frame size
852
                Dimension sz = new Dimension(700, 580);
853
                if (xml.contains("MDIFrameSize")) {
854
                        int[] wh = xml.getIntArrayProperty("MDIFrameSize");
855
                        sz = new Dimension(wh[0], wh[1]);
856
                }
857
                frame.setSize(sz);
858
                // restore frame location
859
                Point pos = new Point(10, 10);
860
                if (xml.contains("MDIFramePos")) {
861
                        int[] xy = xml.getIntArrayProperty("MDIFramePos");
862
                        pos = new Point(xy[0], xy[1]);
863
                }
864
                frame.setLocation(pos);
865

    
866
                // restore frame status (Maximized, minimized, etc);
867
                int state = java.awt.Frame.MAXIMIZED_BOTH;
868
                if (xml.contains("MDIFrameState")) {
869
                        state = xml.getIntProperty("MDIFrameState");
870
                }
871
                frame.setExtendedState(state);
872
        }
873

    
874
        private XMLEntity saveMDIStatus() {
875
                XMLEntity xml = new XMLEntity();
876
                // save frame size
877
                int[] wh = new int[2];
878
                wh[0] = frame.getWidth();
879
                wh[1] = frame.getHeight();
880
                xml.putProperty("MDIFrameSize", wh);
881
                // save frame location
882
                int[] xy = new int[2];
883
                xy[0] = frame.getX();
884
                xy[1] = frame.getY();
885
                xml.putProperty("MDIFramePos", xy);
886
                // save frame status
887
                xml.putProperty("MDIFrameState", frame.getExtendedState());
888
                return xml;
889
        }
890

    
891
        private boolean validJVM() {
892
                char thirdCharacter = System.getProperty("java.version").charAt(2);
893
                if (thirdCharacter < '4') {
894
                        return false;
895
                } else {
896
                        return true;
897
                }
898
        }
899

    
900
        private void loadPluginsPersistence() throws ConfigurationException {
901
                XMLEntity entity = persistenceFromXML();
902

    
903
                for (int i = 0; i < entity.getChildrenCount(); i++) {
904
                        XMLEntity plugin = entity.getChild(i);
905
                        String pName = plugin
906
                                        .getStringProperty("com.iver.andami.pluginName");
907

    
908
                        if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
909
                                pName = "org.gvsig.app";
910
                        }
911
                        if (pluginsServices.get(pName) != null) {
912
                                ((PluginServices) pluginsServices.get(pName))
913
                                                .setPersistentXML(plugin);
914
                        } else {
915
                                if (pName.startsWith("Andami.Launcher")) {
916
                                        restoreMDIStatus(plugin);
917
                                }
918
                        }
919
                }
920
        }
921

    
922
        /**
923
         * Salva la persistencia de los plugins.
924
         * 
925
         * @author LWS
926
         */
927
        private void savePluginPersistence() {
928
                Iterator<String> i = pluginsConfig.keySet().iterator();
929

    
930
                XMLEntity entity = new XMLEntity();
931

    
932
                while (i.hasNext()) {
933
                        String pName = i.next();
934
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
935
                        XMLEntity ent = ps.getPersistentXML();
936

    
937
                        if (ent != null) {
938
                                ent.putProperty("com.iver.andami.pluginName", pName);
939
                                entity.addChild(ent);
940
                        }
941
                }
942
                XMLEntity ent = saveMDIStatus();
943
                if (ent != null) {
944
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
945
                        entity.addChild(ent);
946
                }
947
                try {
948
                        persistenceToXML(entity);
949
                } catch (ConfigurationException e1) {
950
                        this
951
                                        .addError(
952
                                                        Messages
953
                                                                        .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
954
                                                        e1);
955
                }
956
        }
957

    
958
        private void installPluginsLabels() {
959
                Iterator<String> i = pluginsConfig.keySet().iterator();
960

    
961
                while (i.hasNext()) {
962
                        String name = i.next();
963
                        PluginConfig pc = pluginsConfig.get(name);
964
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
965

    
966
                        LabelSet[] ls = pc.getLabelSet();
967

    
968
                        for (int j = 0; j < ls.length; j++) {
969
                                PluginClassLoader loader = ps.getClassLoader();
970

    
971
                                try {
972
                                        Class clase = loader.loadClass(ls[j].getClassName());
973
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
974
                                } catch (ClassNotFoundException e) {
975
                                        this.addError(
976
                                                        Messages.getString("Launcher.labelset_class"), e);
977
                                }
978
                        }
979
                }
980
        }
981

    
982
        private String configureSkin(XMLEntity xml, String defaultSkin) {
983
                if (defaultSkin == null) {
984
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
985
                                if (xml.getChild(i).contains("Skin-Selected")) {
986
                                        String className = xml.getChild(i).getStringProperty(
987
                                                        "Skin-Selected");
988
                                        return className;
989
                                }
990
                        }
991
                }
992
                // return "com.iver.core.mdiManager.NewSkin";
993
                return defaultSkin;
994
        }
995

    
996
        private void fixSkin(SkinExtension skinExtension,
997
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
998
                // now insert the skin selected.
999
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1000
                // MDIManagerFactory.setSkinExtension(se,
1001
                // ps.getClassLoader());
1002

    
1003
                Class<? extends IExtension> skinClass;
1004

    
1005
                try {
1006
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1007
                                        .loadClass(skinExtension.getClassName());
1008

    
1009
                        IExtension skinInstance = skinClass.newInstance();
1010
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1011
                                        skinInstance, ExtensionDecorator.INACTIVE);
1012
                        classesExtensions.put(skinClass, newExtensionDecorator);
1013
                } catch (ClassNotFoundException e) {
1014
                        logger.error(Messages
1015
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1016
                                        e);
1017
                        throw new MDIManagerLoadException(e);
1018
                } catch (InstantiationException e) {
1019
                        logger
1020
                                        .error(
1021
                                                        Messages
1022
                                                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1023
                                                        e);
1024
                        throw new MDIManagerLoadException(e);
1025
                } catch (IllegalAccessException e) {
1026
                        logger
1027
                                        .error(
1028
                                                        Messages
1029
                                                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1030
                                                        e);
1031
                        throw new MDIManagerLoadException(e);
1032
                }
1033

    
1034
        }
1035

    
1036
        /**
1037
         * DOCUMENT ME!
1038
         * 
1039
         * @throws MDIManagerLoadException
1040
         */
1041
        private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1042
                XMLEntity entity = null;
1043
                try {
1044
                        entity = persistenceFromXML();
1045
                } catch (ConfigurationException e1) {
1046
                        // TODO Auto-generated catch block
1047
                        e1.printStackTrace();
1048
                }
1049
                Iterator<String> i = pluginsConfig.keySet().iterator();
1050

    
1051
                SkinExtension skinExtension = null;
1052
                PluginClassLoader pluginClassLoader = null;
1053
                List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1054
                while (i.hasNext()) {
1055
                        String name = i.next();
1056
                        PluginConfig pc = pluginsConfig.get(name);
1057
                        PluginServices ps = pluginsServices.get(name);
1058

    
1059
                        if (pc.getExtensions().getSkinExtension() != null) {
1060
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1061
                                // logger.warn(Messages.getString(
1062
                                // "Launcher.Dos_skin_extension"));
1063
                                // }
1064

    
1065
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1066
                                for (int numExten = 0; numExten < se.length; numExten++) {
1067
                                        skinExtensions.add(se[numExten]);
1068
                                }
1069
                                for (int j = 0; j < se.length; j++) {
1070
                                        String configuredSkin = this.configureSkin(entity,
1071
                                                        defaultSkin);
1072
                                        if ((configuredSkin != null)
1073
                                                        && configuredSkin.equals(se[j].getClassName())) {
1074
                                                skinExtension = se[j];
1075
                                                pluginClassLoader = ps.getClassLoader();
1076
                                        }
1077
                                }
1078
                        }
1079
                }
1080

    
1081
                if ((skinExtension != null) && (pluginClassLoader != null)) {
1082
                        // configured skin was found
1083
                        fixSkin(skinExtension, pluginClassLoader);
1084
                } else {
1085
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1086
                                // try first NewSkin (from CorePlugin)
1087
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
1088
                        } else if (skinExtensions.size() > 0) {
1089
                                // try to load the first skin found
1090
                                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1091
                                skinPlugin((String) se.getClassName());
1092
                        } else {
1093
                                throw new MDIManagerLoadException("No Skin-Extension installed");
1094
                        }
1095
                }
1096

    
1097
        }
1098

    
1099
        private static void frameIcon(Theme theme) {
1100
                Iterator<String> i = pluginsConfig.keySet().iterator();
1101

    
1102
                while (i.hasNext()) {
1103
                        String pName = i.next();
1104
                        PluginConfig pc = pluginsConfig.get(pName);
1105
                        if (pc.getIcon() != null) {
1106
                                if (theme.getIcon() != null) {
1107
                                        frame.setIconImage(theme.getIcon().getImage());
1108
                                } else {
1109

    
1110
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1111
                                                        pc.getIcon().getSrc());
1112
                                        frame.setIconImage(icon.getImage());
1113

    
1114
                                }
1115
                                if (theme.getName() != null) {
1116
                                        frame.setTitlePrefix(theme.getName());
1117
                                } else {
1118
                                        frame.setTitlePrefix(pc.getIcon().getText());
1119
                                }
1120
                                if (theme.getBackgroundImage() != null) {
1121

    
1122
                                        PluginServices.getMDIManager().setBackgroundImage(
1123
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1124
                                }
1125
                        }
1126
                }
1127
        }
1128

    
1129
        private void initializeExtensions() {
1130

    
1131
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1132
                                pluginsOrdered.size());
1133
                classLoaders.add(getClass().getClassLoader());
1134
                Iterator<String> iter = pluginsOrdered.iterator();
1135

    
1136
                // logger.debug("Initializing plugins libraries: ");
1137
                // while (iter.hasNext()) {
1138
                // String pName = (String) iter.next();
1139
                // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1140
                // classLoaders.add(ps.getClassLoader());
1141
                // }
1142
                //
1143
                // // Create the libraries initializer and
1144
                // // initialize the plugin libraries
1145
                // new DefaultLibrariesInitializer(
1146
                // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1147
                // .fullInitialize();
1148
                //
1149
                // // Remove them all, we don't need them anymore
1150
                // classLoaders.clear();
1151
                // classLoaders = null;
1152

    
1153
                logger.info("Initializing plugins: ");
1154
                // iter = pluginsOrdered.iterator();
1155
                while (iter.hasNext()) {
1156
                        String pName = (String) iter.next();
1157
                        logger.info("Initializing plugin " + pName);
1158
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1159
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1160

    
1161
                        Extension[] exts = pc.getExtensions().getExtension();
1162

    
1163
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1164
                                        new ExtensionComparator());
1165

    
1166
                        for (int j = 0; j < exts.length; j++) {
1167
                                if (!exts[j].getActive()) {
1168
                                        continue;
1169
                                }
1170

    
1171
                                if (orderedExtensions.contains(exts[j])) {
1172
                                        logger.warn("Two extensions with the same priority ("
1173
                                                        + exts[j].getClassName() + ")");
1174
                                }
1175

    
1176
                                orderedExtensions.add(exts[j]);
1177
                        }
1178

    
1179
                        Iterator<Extension> e = orderedExtensions.iterator();
1180

    
1181
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1182
                        while (e.hasNext()) {
1183
                                Extension extension = e.next();
1184
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1185

    
1186
                                try {
1187
                                        logger.info("Initializing " + extension.getClassName()
1188
                                                        + "...");
1189
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1190
                                                        .getClassLoader().loadClass(
1191
                                                                        extension.getClassName());
1192
                                        extensionInstance = extensionClass.newInstance();
1193

    
1194
                                        // CON DECORATOR
1195
                                        // ANTES: classesExtensions.put(extensionClass,
1196
                                        // extensionInstance);
1197
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1198
                                        // instancia para
1199
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por
1200
                                        // ejemplo)
1201
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos
1202
                                        // como par?metro
1203
                                        // la extensi?n original que acabamos de crear
1204
                                        // 0-> Inactivo, controla la extension
1205
                                        // 1-> Siempre visible
1206
                                        // 2-> Invisible
1207
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1208
                                                        extensionInstance, ExtensionDecorator.INACTIVE);
1209
                                        classesExtensions
1210
                                                        .put(extensionClass, newExtensionDecorator);
1211

    
1212
                                        extensionInstance.initialize();
1213
                                        extensions.add(extensionInstance);
1214

    
1215
                                } catch (NoClassDefFoundError e1) {
1216
                                        this.addError("Can't find class extension ("
1217
                                                        + extension.getClassName() + ")", e1);
1218
                                } catch (Throwable e1) {
1219
                                        this.addError("Can't initialize extension '"
1220
                                                        + extension.getClassName() + "'.", e1);
1221
                                }
1222
                        }
1223
                }
1224
        }
1225

    
1226
        private void postInitializeExtensions() {
1227
                logger.info("PostInitializing extensions: ");
1228

    
1229
                for (int i = 0; i < extensions.size(); i++) {
1230
                        org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1231
                                        .get(i);
1232
                        logger.info("PostInitializing "
1233
                                        + extensionInstance.getClass().getName() + "...");
1234
                        try {
1235
                                extensionInstance.postInitialize();
1236
                        } catch (Throwable ex) {
1237
                                this.addError("postInitialize of extension '"
1238
                                                + extensionInstance.getClass().getName() + "' failed",
1239
                                                ex);
1240
                        }
1241
                }
1242
        }
1243

    
1244
        private void installPluginsMenus() {
1245
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1246
                                new MenuComparator());
1247

    
1248
                Iterator<String> i = pluginsConfig.keySet().iterator();
1249

    
1250
                while (i.hasNext()) {
1251
                        String pName = i.next();
1252
                        try {
1253
                                PluginServices ps = pluginsServices.get(pName);
1254
                                PluginConfig pc = pluginsConfig.get(pName);
1255

    
1256
                                Extension[] exts = pc.getExtensions().getExtension();
1257

    
1258
                                for (int j = 0; j < exts.length; j++) {
1259
                                        if (!exts[j].getActive()) {
1260
                                                continue;
1261
                                        }
1262

    
1263
                                        Menu[] menus = exts[j].getMenu();
1264

    
1265
                                        for (int k = 0; k < menus.length; k++) {
1266
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1267
                                                                exts[j], menus[k]);
1268

    
1269
                                                if (orderedMenus.contains(sm)) {
1270
                                                        this
1271
                                                                        .addError(Messages
1272
                                                                                        .getString("Launcher.Two_menus_with_the_same_position")
1273
                                                                                        + " - "
1274
                                                                                        + menus[k].getText()
1275
                                                                                        + " - " + exts[j].getClassName());
1276
                                                }
1277

    
1278
                                                orderedMenus.add(sm);
1279
                                        }
1280
                                }
1281

    
1282
                                // Se instalan las extensiones de MDI
1283
                                SkinExtension[] skinExts = pc.getExtensions()
1284
                                                .getSkinExtension();
1285
                                for (int j = 0; j < skinExts.length; j++) {
1286

    
1287
                                        if (skinExts[j] != null) {
1288
                                                Menu[] menu = skinExts[j].getMenu();
1289

    
1290
                                                for (int k = 0; k < menu.length; k++) {
1291
                                                        SortableMenu sm = new SortableMenu(ps
1292
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1293

    
1294
                                                        if (orderedMenus.contains(sm)) {
1295
                                                                this
1296
                                                                                .addError(Messages
1297
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1298
                                                                                                + skinExts[j].getClassName());
1299
                                                        }
1300

    
1301
                                                        orderedMenus.add(sm);
1302
                                                }
1303
                                        }
1304
                                }
1305

    
1306
                        } catch (Throwable e) {
1307
                                addError("Error initializing menus of plugin '" + pName + "'",
1308
                                                e);
1309
                        }
1310

    
1311
                }
1312

    
1313
                // Se itera por los menus ordenados
1314
                Iterator<SortableMenu> e = orderedMenus.iterator();
1315

    
1316
                // Se ordenan los menues
1317
                while (e.hasNext()) {
1318
                        try {
1319
                                SortableMenu sm = e.next();
1320

    
1321
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1322

    
1323
                        } catch (ClassNotFoundException ex) {
1324
                                this
1325
                                                .addError(
1326
                                                                Messages
1327
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1328
                                                                ex);
1329
                        } catch (NoClassDefFoundError ex) {
1330
                                this
1331
                                                .addError(
1332
                                                                Messages
1333
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1334
                                                                ex);
1335
                        } catch (Throwable ex) {
1336
                                this
1337
                                                .addError(
1338
                                                                Messages
1339
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1340
                                                                ex);
1341
                        }
1342
                }
1343
        }
1344

    
1345
        /**
1346
         * Installs the menus, toolbars, actiontools, selectable toolbars and
1347
         * combos. The order in which they are shown is determined here.
1348
         */
1349
        private void installPluginsControls() {
1350
                Iterator<String> i = pluginsConfig.keySet().iterator();
1351

    
1352
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1353
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1354
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1355
                                new ExtensionComparator());
1356

    
1357
                // First of all, sort the extensions.
1358
                // We need to iterate on the plugins, and iterate on each plugin's
1359
                // extensions
1360
                // (each plugin may contain one or more extensions)
1361
                while (i.hasNext()) { // iterate on the plugins
1362
                        String pName = i.next();
1363
                        try {
1364
                                PluginConfig pc = pluginsConfig.get(pName);
1365
                                PluginServices ps = pluginsServices.get(pName);
1366

    
1367
                                Extension[] exts = pc.getExtensions().getExtension();
1368

    
1369
                                for (int j = 0; j < exts.length; j++) { // iterate on the
1370
                                        // extensions
1371
                                        String cname = "unknow";
1372
                                        try {
1373
                                                cname = exts[j].getClassName();
1374
                                                if (exts[j].getActive()
1375
                                                                && !cname.equals(LibraryExtension.class
1376
                                                                                .getName())) {
1377
                                                        if (orderedExtensions.contains(exts[j])) {
1378
                                                                this
1379
                                                                                .addError(Messages
1380
                                                                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1381
                                                                                                + cname);
1382
                                                        }
1383

    
1384
                                                        orderedExtensions.add(exts[j]);
1385
                                                        extensionPluginServices.put(exts[j], ps);
1386
                                                        extensionPluginConfig.put(exts[j], pc);
1387
                                                }
1388
                                        } catch (Exception e) {
1389
                                                addError("Error initializing controls of plugin '"
1390
                                                                + pName + "' extension '" + cname + "'", e);
1391
                                        }
1392
                                }
1393
                        } catch (Throwable e) {
1394
                                addError("Error initializing controls of plugin '" + pName
1395
                                                + "'", e);
1396
                        }
1397
                }
1398

    
1399
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1400
                                new ToolComparator());
1401
                Iterator<Extension> e = orderedExtensions.iterator();
1402

    
1403
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1404
                // selectabletools)
1405
                // and load the combo-scales and combo-buttons for the status bar
1406
                while (e.hasNext()) {
1407
                        Extension ext = e.next();
1408
                        String extName = "unknow";
1409
                        try {
1410
                                extName = ext.getClassName();
1411
                                ToolBar[] toolbars = ext.getToolBar();
1412

    
1413
                                // get tools from toolbars
1414
                                for (int k = 0; k < toolbars.length; k++) {
1415
                                        ActionTool[] tools = toolbars[k].getActionTool();
1416

    
1417
                                        for (int t = 0; t < tools.length; t++) {
1418
                                                SortableTool sm = new SortableTool(
1419
                                                                (extensionPluginServices.get(ext))
1420
                                                                                .getClassLoader(), ext, toolbars[k],
1421
                                                                tools[t]);
1422
                                                orderedTools.add(sm);
1423
                                        }
1424

    
1425
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1426

    
1427
                                        for (int t = 0; t < sTools.length; t++) {
1428
                                                SortableTool sm = new SortableTool(
1429
                                                                (extensionPluginServices.get(ext))
1430
                                                                                .getClassLoader(), ext, toolbars[k],
1431
                                                                sTools[t]);
1432
                                                orderedTools.add(sm);
1433
                                        }
1434
                                }
1435

    
1436
                                // get controls for statusBar
1437
                                PluginServices ps = extensionPluginServices.get(ext);
1438
                                PluginClassLoader loader = ps.getClassLoader();
1439

    
1440
                                // ArrayList componentList = new ArrayList();
1441
                                ComboScale[] comboScaleArray = ext.getComboScale();
1442
                                for (int k = 0; k < comboScaleArray.length; k++) {
1443
                                        org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1444
                                        String label = comboScaleArray[k].getLabel();
1445
                                        if (label != null) {
1446
                                                combo.setLabel(label);
1447
                                        }
1448
                                        String name = comboScaleArray[k].getName();
1449
                                        if (name != null) {
1450
                                                combo.setName(name);
1451
                                        }
1452
                                        String[] elementsString = ((String) comboScaleArray[k]
1453
                                                        .getElements()).split(";");
1454
                                        long[] elements = new long[elementsString.length];
1455
                                        for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
1456
                                                try {
1457
                                                        elements[currentElem] = Long
1458
                                                                        .parseLong(elementsString[currentElem]);
1459
                                                } catch (NumberFormatException nfex1) {
1460
                                                        this
1461
                                                                        .addError(ext.getClassName()
1462
                                                                                        + " -- "
1463
                                                                                        + Messages
1464
                                                                                                        .getString("error_parsing_comboscale_elements"));
1465
                                                        elements[currentElem] = 0;
1466
                                                }
1467
                                        }
1468
                                        combo.setItems(elements);
1469
                                        try {
1470
                                                long value = Long.parseLong((String) comboScaleArray[k]
1471
                                                                .getValue());
1472
                                                combo.setScale(value);
1473
                                        } catch (NumberFormatException nfex2) {
1474
                                                this
1475
                                                                .addError(ext.getClassName()
1476
                                                                                + " -- "
1477
                                                                                + Messages
1478
                                                                                                .getString("error_parsing_comboscale_value"));
1479
                                        }
1480
                                        try {
1481
                                                frame.addStatusBarControl(loader.loadClass(ext
1482
                                                                .getClassName()), combo);
1483
                                        } catch (ClassNotFoundException e1) {
1484
                                                this
1485
                                                                .addError(
1486
                                                                                Messages
1487
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1488
                                                                                e1);
1489
                                        }
1490
                                }
1491

    
1492
                                ComboButton[] comboButtonArray = ext.getComboButton();
1493
                                for (int k = 0; k < comboButtonArray.length; k++) {
1494
                                        ComboButtonElement[] elementList = comboButtonArray[k]
1495
                                                        .getComboButtonElement();
1496
                                        org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1497
                                        String name = comboButtonArray[k].getName();
1498
                                        if (name != null) {
1499
                                                combo.setName(name);
1500
                                        }
1501
                                        for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
1502
                                                ComboButtonElement element = elementList[currentElement];
1503
                                                ImageIcon icon;
1504
                                                URL iconLocation = loader
1505
                                                                .getResource(element.getIcon());
1506
                                                if (iconLocation == null) {
1507
                                                        this.addError(Messages.getString("Icon_not_found_")
1508
                                                                        + element.getIcon());
1509
                                                } else {
1510
                                                        icon = new ImageIcon(iconLocation);
1511
                                                        JButton button = new JButton(icon);
1512
                                                        combo.addButton(button);
1513
                                                        button.setActionCommand(element.getActionCommand());
1514
                                                }
1515
                                        }
1516
                                        try {
1517
                                                frame.addStatusBarControl(loader.loadClass(ext
1518
                                                                .getClassName()), combo);
1519
                                        } catch (ClassNotFoundException e1) {
1520
                                                this
1521
                                                                .addError(
1522
                                                                                Messages
1523
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1524
                                                                                e1);
1525
                                        }
1526
                                }
1527
                        } catch (Throwable e2) {
1528
                                addError(
1529
                                                "Error initializing tools and status bars of extension '"
1530
                                                                + extName + "'", e2);
1531
                        }
1532
                }
1533

    
1534
                // Add the tools from MDI extensions to the ordered tool-list, so that
1535
                // we get a sorted list containing all the tools
1536
                i = pluginsConfig.keySet().iterator();
1537
                while (i.hasNext()) {
1538
                        String pName = (String) i.next();
1539
                        try {
1540
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1541
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
1542

    
1543
                                SkinExtension[] skinExts = pc.getExtensions()
1544
                                                .getSkinExtension();
1545
                                for (int j = 0; j < skinExts.length; j++) {
1546

    
1547
                                        if (skinExts[j] != null) {
1548
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1549

    
1550
                                                for (int k = 0; k < toolbars.length; k++) {
1551
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1552

    
1553
                                                        for (int t = 0; t < tools.length; t++) {
1554
                                                                SortableTool stb = new SortableTool(ps
1555
                                                                                .getClassLoader(), skinExts[j],
1556
                                                                                toolbars[k], tools[t]);
1557
                                                                orderedTools.add(stb);
1558
                                                        }
1559

    
1560
                                                        SelectableTool[] sTools = toolbars[k]
1561
                                                                        .getSelectableTool();
1562

    
1563
                                                        for (int t = 0; t < sTools.length; t++) {
1564
                                                                SortableTool stb = new SortableTool(ps
1565
                                                                                .getClassLoader(), skinExts[j],
1566
                                                                                toolbars[k], sTools[t]);
1567
                                                                orderedTools.add(stb);
1568
                                                        }
1569
                                                }
1570
                                        }
1571
                                }
1572
                                // Install popup menus
1573
                                PopupMenus pus = pc.getPopupMenus();
1574

    
1575
                                if (pus != null) {
1576
                                        PopupMenu[] menus = pus.getPopupMenu();
1577

    
1578
                                        for (int j = 0; j < menus.length; j++) {
1579
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1580
                                        }
1581
                                }
1582
                        } catch (Throwable e3) {
1583
                                addError("Error initializing skins of the plugin '" + pName
1584
                                                + "'", e3);
1585
                        }
1586
                }
1587

    
1588
                // loop on the ordered extension list, to add them to the interface in
1589
                // an ordered way
1590
                Iterator<SortableTool> t = orderedTools.iterator();
1591
                while (t.hasNext()) {
1592
                        SortableTool stb = t.next();
1593
                        try {
1594
                                if (stb.actiontool != null) {
1595
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1596
                                                        stb.actiontool);
1597
                                } else {
1598
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1599
                                                        stb.selectabletool);
1600
                                }
1601
                        } catch (ClassNotFoundException ex) {
1602
                                this
1603
                                                .addError(
1604
                                                                Messages
1605
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1606
                                                                ex);
1607
                        } catch (Throwable e2) {
1608
                                addError("Error adding tools to the interface of extension '"
1609
                                                + stb.extension.getClassName() + "'", e2);
1610
                        }
1611
                }
1612
        }
1613

    
1614
        /**
1615
         * Adds new plugins to the the andami-config file.
1616
         */
1617
        private void updateAndamiConfig() {
1618
                Set<String> olds = new HashSet<String>();
1619

    
1620
                Plugin[] plugins = andamiConfig.getPlugin();
1621

    
1622
                for (int i = 0; i < plugins.length; i++) {
1623
                        olds.add(plugins[i].getName());
1624
                }
1625

    
1626
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1627

    
1628
                while (i.hasNext()) {
1629
                        PluginServices ps = i.next();
1630

    
1631
                        if (!olds.contains(ps.getPluginName())) {
1632
                                Plugin p = new Plugin();
1633
                                p.setName(ps.getPluginName());
1634
                                p.setUpdate(false);
1635

    
1636
                                andamiConfig.addPlugin(p);
1637
                        }
1638
                }
1639
        }
1640

    
1641
        private void pluginsClassLoaders() {
1642
                Set<String> installed = new HashSet<String>();
1643

    
1644
                // Se itera hasta que est?n todos instalados
1645
                while (installed.size() != pluginsConfig.size()) {
1646
                        boolean circle = true;
1647

    
1648
                        // Hacemos una pasada por todos los plugins
1649
                        Iterator<String> i = pluginsConfig.keySet().iterator();
1650

    
1651
                        while (i.hasNext()) {
1652
                                String pluginName = i.next();
1653
                                PluginConfig config = (PluginConfig) pluginsConfig
1654
                                                .get(pluginName);
1655

    
1656
                                if (installed.contains(pluginName)) {
1657
                                        continue;
1658
                                }
1659

    
1660
                                // Se obtienen las dependencias y sus class loaders
1661
                                boolean ready = true;
1662
                                Depends[] dependencies = config.getDepends();
1663
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1664

    
1665
                                for (int j = 0; j < dependencies.length; j++) {
1666
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1667
                                                this
1668
                                                                .addError(Messages
1669
                                                                                .getString("Launcher.Dependencia_no_resuelta_en_plugin")
1670
                                                                                + " "
1671
                                                                                + pluginName
1672
                                                                                + ": "
1673
                                                                                + dependencies[j].getPluginName());
1674

    
1675
                                                continue;
1676
                                        }
1677

    
1678
                                        if (!installed.contains(dependencies[j].getPluginName())) {
1679
                                                ready = false;
1680
                                        } else {
1681
                                                loaders[j] = (pluginsServices.get(dependencies[j]
1682
                                                                .getPluginName())).getClassLoader();
1683
                                        }
1684
                                }
1685

    
1686
                                // Si no est?n sus dependencias satisfechas se aborta la
1687
                                // instalaci?n
1688
                                if (!ready) {
1689
                                        continue;
1690
                                }
1691

    
1692
                                // Se genera el class loader
1693
                                String jardir = config.getLibraries().getLibraryDir();
1694
                                File jarDir = new File(andamiConfig.getPluginsDirectory(),
1695
                                                pluginName + File.separator + jardir);
1696
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1697

    
1698
                                        public boolean accept(File pathname) {
1699
                                                return (pathname.getName().toUpperCase()
1700
                                                                .endsWith(".JAR"))
1701
                                                                || (pathname.getName().toUpperCase()
1702
                                                                                .endsWith(".ZIP"));
1703
                                        }
1704
                                });
1705

    
1706
                                URL[] urls = new URL[jarFiles.length];
1707

    
1708
                                for (int j = 0; j < jarFiles.length; j++) {
1709
                                        try {
1710
                                                urls[j] = new URL("file:" + jarFiles[j]);
1711
                                        } catch (MalformedURLException e) {
1712
                                                this.addError(Messages
1713
                                                                .getString("Launcher.No_se_puede_acceder_a")
1714
                                                                + " " + jarFiles[j]);
1715
                                        }
1716
                                }
1717

    
1718
                                PluginClassLoader loader;
1719

    
1720
                                try {
1721
                                        loader = new PluginClassLoader(urls, andamiConfig
1722
                                                        .getPluginsDirectory()
1723
                                                        + File.separator + pluginName, Launcher.class
1724
                                                        .getClassLoader(), loaders);
1725

    
1726
                                        PluginServices ps = new PluginServices(loader);
1727

    
1728
                                        pluginsServices.put(ps.getPluginName(), ps);
1729

    
1730
                                        installed.add(pluginName);
1731
                                        // FJP: Los metemos ordenados para luego no cargar uno que
1732
                                        // necesita de otro antes de tiempo. Esto lo usaremos al
1733
                                        // inicializar los plugins
1734
                                        pluginsOrdered.add(pluginName);
1735

    
1736
                                        circle = false;
1737
                                } catch (IOException e) {
1738
                                        this
1739
                                                        .addError(
1740
                                                                        Messages
1741
                                                                                        .getString("Launcher.Error_con_las_librerias_del_plugin"),
1742
                                                                        e);
1743
                                        pluginsConfig.remove(pluginName);
1744
                                        i = pluginsConfig.keySet().iterator();
1745
                                }
1746
                        }
1747

    
1748
                        if (circle) {
1749
                                this.addError(Messages
1750
                                                .getString("Launcher.Hay_dependencias_circulares"));
1751

    
1752
                                break;
1753
                        }
1754
                }
1755

    
1756
                // Se eliminan los plugins que no fueron instalados
1757
                Iterator<String> i = pluginsConfig.keySet().iterator();
1758

    
1759
                while (i.hasNext()) {
1760
                        String pluginName = i.next();
1761
                        PluginServices ps = (PluginServices) pluginsServices
1762
                                        .get(pluginName);
1763

    
1764
                        if (ps == null) {
1765
                                pluginsConfig.remove(pluginName);
1766
                                i = pluginsConfig.keySet().iterator();
1767
                        }
1768
                }
1769
        }
1770

    
1771
        private void pluginsMessages() {
1772
                Iterator<String> iterator = pluginsOrdered.iterator();
1773
                PluginConfig config;
1774
                PluginServices ps;
1775

    
1776
                while (iterator.hasNext()) {
1777
                        String pluginName = iterator.next();
1778
                        config = pluginsConfig.get(pluginName);
1779
                        ps = pluginsServices.get(pluginName);
1780

    
1781
                        if ((config.getResourceBundle() != null)
1782
                                        && !config.getResourceBundle().getName().equals("")) {
1783
                                // add the locale files associated with the plugin
1784
                                org.gvsig.i18n.Messages.addResourceFamily(config
1785
                                                .getResourceBundle().getName(), ps.getClassLoader(),
1786
                                                pluginName);
1787
                        }
1788
                }
1789
        }
1790

    
1791
        static public PluginServices getPluginServices(String name) {
1792
                return (PluginServices) pluginsServices.get(name);
1793
        }
1794

    
1795
        static String getPluginsDir() {
1796
                return andamiConfig.getPluginsDirectory();
1797
        }
1798

    
1799
        static void setPluginsDir(String s) {
1800
                andamiConfig.setPluginsDirectory(s);
1801
        }
1802

    
1803
        static MDIFrame getMDIFrame() {
1804
                return frame;
1805
        }
1806

    
1807
        private void loadPlugins(String pluginsDirectory) {
1808
                File pDir = new File(pluginsDirectory);
1809

    
1810
                if (!pDir.exists()) {
1811
                        logger
1812
                                        .error("\n\tPlugins directory not found: "
1813
                                                        + pDir.getAbsolutePath()
1814
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1815
                        System.exit(-1);
1816
                        return;
1817
                }
1818

    
1819
                File[] pluginDirs = pDir.listFiles();
1820
                if (pluginDirs.length == 0) {
1821
                        logger
1822
                                        .error("\n\tPlugins directory is empty: "
1823
                                                        + pDir.getAbsolutePath()
1824
                                                        + "Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1825
                        System.exit(-1);
1826
                        return;
1827
                }
1828

    
1829
                for (int i = 0; i < pluginDirs.length; i++) {
1830
                        if (pluginDirs[i].isDirectory()) {
1831
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
1832
                                                "config.xml");
1833

    
1834
                                try {
1835
                                        FileInputStream is = new FileInputStream(configXml);
1836
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils
1837
                                                        .getReader(is);
1838
                                        if (xml == null) {
1839
                                                // the encoding was not correctly detected, use system
1840
                                                // default
1841
                                                xml = new FileReader(configXml);
1842
                                        } else {
1843
                                                // use a buffered reader to improve performance
1844
                                                xml = new BufferedReader(xml);
1845
                                        }
1846
                                        PluginConfig pConfig = (PluginConfig) PluginConfig
1847
                                                        .unmarshal(xml);
1848
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1849
                                } catch (FileNotFoundException e) {
1850
                                        logger
1851
                                                        .info("Plugin folder without config.xml. Skip plugin '"
1852
                                                                        + pluginDirs[i].getAbsolutePath() + "'.");
1853
                                } catch (MarshalException e) {
1854
                                        this.addError("Can't load plugin '"
1855
                                                        + pluginDirs[i].getAbsolutePath() + "'.", e);
1856
                                } catch (ValidationException e) {
1857
                                        this.addError("Can't load plugin '"
1858
                                                        + pluginDirs[i].getAbsolutePath() + "'.", e);
1859
                                }
1860
                        }
1861
                }
1862

    
1863
                if (pluginsConfig.size() == 0) {
1864
                        logger
1865
                                        .error("No valid plugin was found. The plugins directory currently is: "
1866
                                                        + pDir.getAbsolutePath()
1867
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1868
                        System.exit(-1);
1869
                        return;
1870
                }
1871
        }
1872

    
1873
        private static Locale getLocale(String language, String country,
1874
                        String variant) {
1875
                if (variant != null) {
1876
                        return new Locale(language, country, variant);
1877
                } else if (country != null) {
1878
                        return new Locale(language, country);
1879
                } else if (language != null) {
1880
                        return new Locale(language);
1881
                } else {
1882
                        return new Locale("es");
1883
                }
1884
        }
1885

    
1886
        private static void andamiConfigToXML(String file) throws IOException,
1887
                        MarshalException, ValidationException {
1888
                // write on a temporary file in order to not destroy current file if
1889
                // there is some problem while marshaling
1890
                File tmpFile = new File(file + "-"
1891
                                + DateTime.getCurrentDate().getTime());
1892
                File xml = new File(file);
1893
                File parent = xml.getParentFile();
1894
                parent.mkdirs();
1895

    
1896
                BufferedOutputStream os = new BufferedOutputStream(
1897
                                new FileOutputStream(tmpFile));
1898
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
1899
                andamiConfig.marshal(writer);
1900
                writer.close();
1901

    
1902
                // if marshaling process finished correctly, move the file to the
1903
                // correct one
1904
                xml.delete();
1905
                if (!tmpFile.renameTo(xml)) {
1906
                        // if rename was not succesful, try copying it
1907
                        FileChannel sourceChannel = new FileInputStream(tmpFile)
1908
                                        .getChannel();
1909
                        FileChannel destinationChannel = new FileOutputStream(xml)
1910
                                        .getChannel();
1911
                        sourceChannel.transferTo(0, sourceChannel.size(),
1912
                                        destinationChannel);
1913
                        sourceChannel.close();
1914
                        destinationChannel.close();
1915
                }
1916
        }
1917

    
1918
        private static void andamiConfigFromXML(String file)
1919
                        throws ConfigurationException {
1920
                File xml = new File(file);
1921

    
1922
                InputStreamReader reader = null;
1923
                try {
1924
                        // Se lee la configuraci?n
1925
                        reader = XMLEncodingUtils.getReader(xml);
1926
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1927
                } catch (FileNotFoundException e) {
1928
                        // Si no existe se ponen los valores por defecto
1929
                        andamiConfig = getDefaultAndamiConfig();
1930
                } catch (MarshalException e) {
1931
                        // try to close the stream, maybe it remains open
1932
                        if (reader != null) {
1933
                                try {
1934
                                        reader.close();
1935
                                } catch (IOException e1) {
1936
                                }
1937
                        }
1938
                        // if there was a problem reading the file, backup it and create a
1939
                        // new one with default values
1940
                        String backupFile = file + "-"
1941
                                        + DateTime.getCurrentDate().getTime();
1942
                        NotificationManager
1943
                                        .addError(
1944
                                                        Messages
1945
                                                                        .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
1946
                                                                        + backupFile, new ConfigurationException(e));
1947
                        xml.renameTo(new File(backupFile));
1948
                        andamiConfig = getDefaultAndamiConfig();
1949
                } catch (ValidationException e) {
1950
                        throw new ConfigurationException(e);
1951
                }
1952
        }
1953

    
1954
        private static AndamiConfig getDefaultAndamiConfig() {
1955
                AndamiConfig andamiConfig = new AndamiConfig();
1956

    
1957
                Andami andami = new Andami();
1958
                andami.setUpdate(true);
1959
                andamiConfig.setAndami(andami);
1960
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1961
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1962
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1963

    
1964
                if (System.getProperty("javawebstart.version") != null) // Es java web
1965
                // start)
1966
                {
1967
                        andamiConfig
1968
                                        .setPluginsDirectory(new File(appHomeDir, "extensiones")
1969
                                                        .getAbsolutePath());
1970
                } else {
1971
                        andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
1972
                                        .getAbsolutePath());
1973
                }
1974

    
1975
                andamiConfig.setPlugin(new Plugin[0]);
1976
                return andamiConfig;
1977
        }
1978

    
1979
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1980
                File xml = getPluginsPersistenceFile(true);
1981

    
1982
                if (xml.exists()) {
1983
                        InputStreamReader reader = null;
1984

    
1985
                        try {
1986
                                reader = XMLEncodingUtils.getReader(xml);
1987
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1988
                                return new XMLEntity(tag);
1989
                        } catch (FileNotFoundException e) {
1990
                                throw new ConfigurationException(e);
1991
                        } catch (MarshalException e) {
1992

    
1993
                                // try to reopen with default encoding (for backward
1994
                                // compatibility)
1995
                                try {
1996
                                        reader = new FileReader(xml);
1997
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1998
                                        return new XMLEntity(tag);
1999

    
2000
                                } catch (MarshalException ex) {
2001
                                        // try to close the stream, maybe it remains open
2002
                                        if (reader != null) {
2003
                                                try {
2004
                                                        reader.close();
2005
                                                } catch (IOException e1) {
2006
                                                }
2007
                                        }
2008
                                        // backup the old file
2009
                                        String backupFile = getPluginsPersistenceFile(true)
2010
                                                        .getPath()
2011
                                                        + "-" + DateTime.getCurrentDate().getTime();
2012
                                        NotificationManager
2013
                                                        .addError(
2014
                                                                        Messages
2015
                                                                                        .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2016
                                                                                        + backupFile,
2017
                                                                        new ConfigurationException(e));
2018
                                        xml.renameTo(new File(backupFile));
2019
                                        // create a new, empty configuration
2020
                                        return new XMLEntity();
2021
                                } catch (FileNotFoundException ex) {
2022
                                        return new XMLEntity();
2023
                                } catch (ValidationException ex) {
2024
                                        throw new ConfigurationException(e);
2025
                                }
2026
                        } catch (ValidationException e) {
2027
                                throw new ConfigurationException(e);
2028
                        }
2029
                } else {
2030
                        return new XMLEntity();
2031
                }
2032
        }
2033

    
2034
        private static File getPluginsPersistenceFile(boolean read) {
2035
                if (read) {
2036
                        File pluginsPersistenceFile = new File(getAppHomeDir(),
2037
                                        "plugins-persistence-2_0.xml");
2038
                        if (pluginsPersistenceFile.exists()) {
2039
                                return pluginsPersistenceFile;
2040
                        }
2041
                        pluginsPersistenceFile = new File(getAppHomeDir(),
2042
                                        "plugins-persistence.xml");
2043
                        if (pluginsPersistenceFile.exists()) {
2044
                                return pluginsPersistenceFile;
2045
                        }
2046
                }
2047
                return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2048

    
2049
        }
2050

    
2051
        private static void persistenceToXML(XMLEntity entity)
2052
                        throws ConfigurationException {
2053
                // write on a temporary file in order to not destroy current file if
2054
                // there is some problem while marshaling
2055
                File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2056
                                + "-" + DateTime.getCurrentDate().getTime());
2057

    
2058
                File xml = getPluginsPersistenceFile(false);
2059
                OutputStreamWriter writer = null;
2060

    
2061
                try {
2062
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2063
                                        CASTORENCODING);
2064
                        entity.getXmlTag().marshal(writer);
2065
                        writer.close();
2066

    
2067
                        // if marshaling process finished correctly, move the file to the
2068
                        // correct one
2069
                        xml.delete();
2070
                        if (!tmpFile.renameTo(xml)) {
2071
                                // if rename was not succesful, try copying it
2072
                                FileChannel sourceChannel = new FileInputStream(tmpFile)
2073
                                                .getChannel();
2074
                                FileChannel destinationChannel = new FileOutputStream(xml)
2075
                                                .getChannel();
2076
                                sourceChannel.transferTo(0, sourceChannel.size(),
2077
                                                destinationChannel);
2078
                                sourceChannel.close();
2079
                                destinationChannel.close();
2080

    
2081
                        }
2082
                } catch (FileNotFoundException e) {
2083
                        throw new ConfigurationException(e);
2084
                } catch (MarshalException e) {
2085
                        // try to close the stream, maybe it remains open
2086
                        if (writer != null) {
2087
                                try {
2088
                                        writer.close();
2089
                                } catch (IOException e1) {
2090
                                }
2091
                        }
2092
                } catch (ValidationException e) {
2093
                        throw new ConfigurationException(e);
2094
                } catch (IOException e) {
2095
                        throw new ConfigurationException(e);
2096
                }
2097
        }
2098

    
2099
        static MDIFrame getFrame() {
2100
                return frame;
2101
        }
2102

    
2103
        /**
2104
         * Gracefully closes the application. It shows dialogs to save data, finish
2105
         * processes, etc, then it terminates the extensions, removes temporal files
2106
         * and finally exits.
2107
         */
2108
        public synchronized static void closeApplication() {
2109
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2110
                terminationProcess.run();
2111
        }
2112

    
2113
        static HashMap getClassesExtensions() {
2114
                return classesExtensions;
2115
        }
2116

    
2117
        private static Extensions[] getExtensions() {
2118
                List<Extensions> array = new ArrayList<Extensions>();
2119
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2120

    
2121
                while (iter.hasNext()) {
2122
                        array.add(iter.next().getExtensions());
2123
                }
2124

    
2125
                return array.toArray(new Extensions[array.size()]);
2126
        }
2127

    
2128
        public static Iterator getExtensionIterator() {
2129
                return extensions.iterator();
2130
        }
2131

    
2132
        public static HashMap getPluginConfig() {
2133
                return pluginsConfig;
2134
        }
2135

    
2136
        public static Extension getExtension(String s) {
2137
                Extensions[] exts = getExtensions();
2138

    
2139
                for (int i = 0; i < exts.length; i++) {
2140
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2141
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2142
                                        return exts[i].getExtension(j);
2143
                                }
2144
                        }
2145
                }
2146

    
2147
                return null;
2148
        }
2149

    
2150
        public static AndamiConfig getAndamiConfig() {
2151
                return andamiConfig;
2152
        }
2153

    
2154
        private static class ExtensionComparator implements Comparator {
2155

    
2156
                public int compare(Object o1, Object o2) {
2157
                        Extension e1 = (Extension) o1;
2158
                        Extension e2 = (Extension) o2;
2159

    
2160
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2161
                                return -1;
2162
                        }
2163

    
2164
                        if (e1.hasPriority() && !e2.hasPriority()) {
2165
                                return Integer.MIN_VALUE;
2166
                        }
2167

    
2168
                        if (e2.hasPriority() && !e1.hasPriority()) {
2169
                                return Integer.MAX_VALUE;
2170
                        }
2171

    
2172
                        if (e1.getPriority() != e2.getPriority()) {
2173
                                return e2.getPriority() - e1.getPriority();
2174
                        } else {
2175
                                return (e2.toString().compareTo(e1.toString()));
2176
                        }
2177
                }
2178
        }
2179

    
2180
        private static class MenuComparator implements Comparator<SortableMenu> {
2181

    
2182
                private static ExtensionComparator extComp = new ExtensionComparator();
2183

    
2184
                public int compare(SortableMenu e1, SortableMenu e2) {
2185

    
2186
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2187
                                if (e1.extension instanceof SkinExtensionType) {
2188
                                        return 1;
2189
                                } else if (e2.extension instanceof SkinExtensionType) {
2190
                                        return -1;
2191
                                } else {
2192
                                        return extComp.compare(e1.extension, e2.extension);
2193
                                }
2194
                        }
2195

    
2196
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2197
                                return Integer.MIN_VALUE;
2198
                        }
2199

    
2200
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2201
                                return Integer.MAX_VALUE;
2202
                        }
2203
                        if (e1.menu.getPosition() != e2.menu.getPosition()) {
2204
                                // we don't return 0 unless both objects are the same, otherwise
2205
                                // the objects get overwritten in the treemap
2206
                                return e1.menu.getPosition() - e2.menu.getPosition();
2207
                        } else {
2208
                                return (e1.toString().compareTo(e2.toString()));
2209
                        }
2210
                }
2211
        }
2212

    
2213
        private static class SortableMenu {
2214

    
2215
                public PluginClassLoader loader;
2216
                public Menu menu;
2217
                public SkinExtensionType extension;
2218

    
2219
                public SortableMenu(PluginClassLoader loader,
2220
                                SkinExtensionType skinExt, Menu menu2) {
2221
                        extension = skinExt;
2222
                        menu = menu2;
2223
                        this.loader = loader;
2224
                }
2225
        }
2226

    
2227
        private static class SortableTool {
2228

    
2229
                public PluginClassLoader loader;
2230
                public ToolBar toolbar;
2231
                public ActionTool actiontool;
2232
                public SelectableTool selectabletool;
2233
                public SkinExtensionType extension;
2234

    
2235
                public SortableTool(PluginClassLoader loader,
2236
                                SkinExtensionType skinExt, ToolBar toolbar2,
2237
                                ActionTool actiontool2) {
2238
                        extension = skinExt;
2239
                        toolbar = toolbar2;
2240
                        actiontool = actiontool2;
2241
                        this.loader = loader;
2242
                }
2243

    
2244
                public SortableTool(PluginClassLoader loader,
2245
                                SkinExtensionType skinExt, ToolBar toolbar2,
2246
                                SelectableTool selectabletool2) {
2247
                        extension = skinExt;
2248
                        toolbar = toolbar2;
2249
                        selectabletool = selectabletool2;
2250
                        this.loader = loader;
2251
                }
2252
        }
2253

    
2254
        private static class ToolBarComparator implements Comparator<SortableTool> {
2255

    
2256
                private static ExtensionComparator extComp = new ExtensionComparator();
2257

    
2258
                public int compare(SortableTool e1, SortableTool e2) {
2259

    
2260
                        // if the toolbars have the same name, they are considered to be
2261
                        // the same toolbar, so we don't need to do further comparing
2262
                        if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2263
                                return 0;
2264
                        }
2265

    
2266
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2267
                                if (e1.extension instanceof SkinExtensionType) {
2268
                                        return 1;
2269
                                } else if (e2.extension instanceof SkinExtensionType) {
2270
                                        return -1;
2271
                                } else {
2272
                                        return extComp.compare(e1.extension, e2.extension);
2273
                                }
2274
                        }
2275

    
2276
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2277
                                return Integer.MIN_VALUE;
2278
                        }
2279

    
2280
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2281
                                return Integer.MAX_VALUE;
2282
                        }
2283
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2284
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2285
                        }
2286

    
2287
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2288
                                        && e1.toolbar.getSelectableTool().equals(
2289
                                                        e2.toolbar.getSelectableTool())) {
2290
                                return 0;
2291
                        }
2292
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2293
                }
2294
        }
2295

    
2296
        /**
2297
         * <p>
2298
         * This class is used to compare tools (selectabletool and actiontool),
2299
         * using the "position" attribute.
2300
         * </p>
2301
         * <p>
2302
         * The ordering criteria are:
2303
         * </p>
2304
         * <ul>
2305
         * <li>If the tools are placed in different toolbars, they use the toolbars'
2306
         * order. (using the ToolBarComparator).</li>
2307
         * <li></li>
2308
         * <li>If any of the tools has not 'position' attribute, the tool which
2309
         * <strong>has</strong> the attribute will be placed first.</li>
2310
         * <li>If both tools have the same position (or they don't have a 'position'
2311
         * attribute), the priority of the extensions where the tool is defined.</li>
2312
         * </ul>
2313
         * 
2314
         * @author cesar
2315
         * @version $Revision: 38094 $
2316
         */
2317
        private static class ToolComparator implements Comparator<SortableTool> {
2318

    
2319
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2320

    
2321
                public int compare(SortableTool e1, SortableTool e2) {
2322
                        // compare the toolbars which contain the tools
2323
                        int result = toolBarComp.compare(e1, e2);
2324
                        if (result != 0) { // if the toolbars are different, use their order
2325
                                return result;
2326
                        }
2327
                        // otherwise, compare the tools
2328
                        int e1Position = -1, e2Position = -1;
2329

    
2330
                        if (e1.actiontool != null) {
2331
                                if (e1.actiontool.hasPosition()) {
2332
                                        e1Position = e1.actiontool.getPosition();
2333
                                }
2334
                        } else if (e1.selectabletool != null) {
2335
                                if (e1.selectabletool.hasPosition()) {
2336
                                        e1Position = e1.selectabletool.getPosition();
2337
                                }
2338
                        }
2339

    
2340
                        if (e2.actiontool != null) {
2341
                                if (e2.actiontool.hasPosition()) {
2342
                                        e2Position = e2.actiontool.getPosition();
2343
                                }
2344
                        } else if (e2.selectabletool != null) {
2345
                                if (e2.selectabletool.hasPosition()) {
2346
                                        e2Position = e2.selectabletool.getPosition();
2347
                                }
2348
                        }
2349

    
2350
                        if ((e1Position == -1) && (e2Position != -1)) {
2351
                                return 1;
2352
                        }
2353
                        if ((e1Position != -1) && (e2Position == -1)) {
2354
                                return -1;
2355
                        }
2356
                        if ((e1Position != -1) && (e2Position != -1)) {
2357
                                result = e1Position - e2Position;
2358
                                // we don't return 0 unless both objects are the same, otherwise
2359
                                // the objects get overwritten in the treemap
2360
                                if (result != 0) {
2361
                                        return result;
2362
                                }
2363
                        }
2364
                        return e1.toString().compareTo(e2.toString());
2365
                }
2366
        }
2367

    
2368
        /**
2369
         * validates the user before starting gvsig
2370
         * 
2371
         */
2372
        private static void validate() {
2373

    
2374
                IAuthentication session = null;
2375
                try {
2376
                        session = (IAuthentication) Class.forName(
2377
                                        "com.iver.andami.authentication.Session").newInstance();
2378

    
2379
                } catch (ClassNotFoundException e) {
2380
                        return;
2381
                } catch (InstantiationException e) {
2382
                        return;
2383
                } catch (IllegalAccessException e) {
2384
                        return;
2385
                }
2386

    
2387
                session.setPluginDirectory(andamiConfig.getPluginsDirectory());
2388
                if (session.validationRequired()) {
2389
                        if (session.Login()) {
2390
                                logger.info("You are logged in");
2391
                        } else {
2392
                                JOptionPane.showMessageDialog((Component) PluginServices
2393
                                                .getMainFrame(), "You are not logged in");
2394
                        }
2395
                        PluginServices.setAuthentication(session);
2396
                }
2397
        }
2398

    
2399
        public static String getDefaultLookAndFeel() {
2400
                String osName = (String) System.getProperty("os.name");
2401

    
2402
                if ((osName.length() > 4)
2403
                                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2404
                        return nonWinDefaultLookAndFeel;
2405
                }
2406
                if (osName.toLowerCase().startsWith("mac os x")) {
2407
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2408
                }
2409

    
2410
                return UIManager.getSystemLookAndFeelClassName();
2411
        }
2412

    
2413
        /**
2414
         * Gets the ISO 839 two-characters-long language code matching the provided
2415
         * language code (which may be an ISO 839-2/T three-characters-long code or
2416
         * an ISO 839-1 two-characters-long code).
2417
         * 
2418
         * If the provided parameter is already two characters long, it returns the
2419
         * parameter without any modification.
2420
         * 
2421
         * @param langCode
2422
         *            A language code representing either an ISO 839-2/T language
2423
         *            code or an ISO 839-1 code.
2424
         * @return A two-characters-long code specifying an ISO 839 language code.
2425
         */
2426
        private static String normalizeLanguageCode(String langCode) {
2427
                final String fileName = "iso_639.tab";
2428
                if (langCode.length() == 2) {
2429
                        return langCode;
2430
                } else if (langCode.length() == 3) {
2431
                        if (langCode.equals("va") || langCode.equals("val")) { // special
2432
                                // case
2433
                                // for
2434
                                // Valencian
2435
                                return "ca";
2436
                        }
2437
                        URL isoCodes = Launcher.class.getClassLoader()
2438
                                        .getResource(fileName);
2439
                        if (isoCodes != null) {
2440
                                try {
2441
                                        BufferedReader reader = new BufferedReader(
2442
                                                        new InputStreamReader(isoCodes.openStream(),
2443
                                                                        "ISO-8859-1"));
2444
                                        String line;
2445

    
2446
                                        while ((line = reader.readLine()) != null) {
2447
                                                String[] language = line.split("\t");
2448
                                                if (language[0].equals(langCode)) {
2449
                                                        // the three
2450
                                                        // characters code
2451
                                                        return language[2]; // third column i the two
2452
                                                        // characters code
2453
                                                }
2454
                                        }
2455
                                } catch (IOException ex) {
2456
                                        logger.error(Messages
2457
                                                        .getString("Error_reading_isocodes_file"), ex);
2458
                                        return "es";
2459
                                }
2460
                        } else {
2461
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2462
                                return "es";
2463
                        }
2464
                }
2465
                return "es";
2466
        }
2467

    
2468
        /**
2469
         * Configures the locales (languages and local resources) to be used by the
2470
         * application.
2471
         * 
2472
         * First it tries to get the locale from the command line parameters, then
2473
         * the andami-config file is checked.
2474
         * 
2475
         * The locale name is normalized to get a two characters language code as
2476
         * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
2477
         * also accepted from the command line or the configuration file).
2478
         * 
2479
         * Finally, the gvsig-i18n library and the default locales for Java and
2480
         * Swing are configured.
2481
         * 
2482
         */
2483
        private static void configureLocales(String[] args) {
2484
                // Configurar el locale
2485
                String localeStr = null;
2486
                /*
2487
                 * for (int i=2; i < args.length; i++) { int index =
2488
                 * args[i].indexOf("language="); if (index != -1) localeStr =
2489
                 * args[i].substring(index+9); }
2490
                 */
2491
                localeStr = PluginServices.getArgumentByName("language");
2492
                if (localeStr == null) {
2493
                        localeStr = andamiConfig.getLocaleLanguage();
2494
                }
2495
                localeStr = normalizeLanguageCode(localeStr);
2496
                locale = getLocale(localeStr, andamiConfig.getLocaleCountry(),
2497
                                andamiConfig.getLocaleVariant());
2498
                Locale.setDefault(locale);
2499
                JComponent.setDefaultLocale(locale);
2500
                org.gvsig.i18n.Messages.addLocale(locale);
2501
                // add english and spanish as fallback languages
2502
                if (localeStr.equals("es") || localeStr.equals("ca")
2503
                                || localeStr.equals("gl") || localeStr.equals("eu")
2504
                                || localeStr.equals("va")) {
2505
                        // prefer Spanish for languages spoken in Spain
2506
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2507
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2508
                } else {
2509
                        // prefer English for the rest
2510
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2511
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2512
                }
2513

    
2514
        // Create classloader for the i18n resources in the
2515
        // andami and user i18n folder. Those values will have
2516
        // precedence over any other values added afterwards
2517
        File andamiI18nFolder =
2518
            new File(System.getProperty("user.dir"), "i18n");
2519
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2520

    
2521
        logger.info("Loading i18n resources from the application and user "
2522
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2523

    
2524
        URL[] i18nURLs;
2525
        try {
2526
            i18nURLs =
2527
                new URL[] { userI18nFolder.toURI().toURL(),
2528
                    andamiI18nFolder.toURI().toURL() };
2529
            ClassLoader i18nClassLoader = new URLClassLoader(i18nURLs);
2530
            org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
2531
                "Andami Launcher");
2532
        } catch (MalformedURLException e) {
2533
            logger.error("Error loading i18n resources from the application "
2534
                + "and user folders: " + andamiI18nFolder + ", "
2535
                + userI18nFolder, e);
2536
        }
2537

    
2538
        // Finally load the andami own i18n resources
2539
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2540
            "Andami Launcher");
2541
        }
2542

    
2543
        /**
2544
         * Gets Home Directory location of the application into users home folder.
2545
         * 
2546
         * May be set from outside the aplication by means of
2547
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2548
         * 
2549
         * @return
2550
         */
2551
        public static String getAppHomeDir() {
2552
                return appHomeDir;
2553
        }
2554

    
2555
        /**
2556
         * Sets Home Directory location of the application. May be set from outside
2557
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
2558
         * the name of the application
2559
         * 
2560
         * @param appHomeDir
2561
         */
2562
        public static void setAppHomeDir(String appHomeDir) {
2563
                Launcher.appHomeDir = appHomeDir;
2564
        }
2565

    
2566
        /**
2567
         * Initialize the extesion that have to take the control of the state of
2568
         * action controls of the UI of all extensions. <br>
2569
         * <br>
2570
         * For use this option you have to add an argument to the command line like
2571
         * this: <br>
2572
         * <br>
2573
         * -exclusiveUI={pathToExtensionClass} <br>
2574
         * 
2575
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
2576
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
2577
         */
2578
        private static void initializeExclusiveUIExtension() {
2579
                String name = PluginServices.getArgumentByName("exclusiveUI");
2580
                if (name == null) {
2581
                        return;
2582
                }
2583

    
2584
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
2585
                                .iterator();
2586
                int charIndex;
2587
                Class<? extends IExtension> key;
2588
                while (iter.hasNext()) {
2589
                        key = iter.next();
2590
                        charIndex = key.getName().indexOf(name);
2591
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2592
                        if (charIndex == 0) {
2593
                                IExtension ext = classesExtensions.get(key);
2594
                                if (ext instanceof ExtensionDecorator) {
2595
                                        ext = ((ExtensionDecorator) ext).getExtension();
2596
                                }
2597
                                if (ext instanceof ExclusiveUIExtension) {
2598
                                        PluginServices
2599
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
2600
                                }
2601
                                break;
2602
                        }
2603
                }
2604

    
2605
                logger
2606
                                .error(Messages
2607
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2608
                                                + " '" + name + "'");
2609
        }
2610

    
2611
        // public static void initIconThemes() {
2612
        // // load the iconTheme
2613
        // IconThemeManager iconManager = new IconThemeManager();
2614
        // PluginServices.setIconThemeManager(iconManager);
2615
        // IconThemeInfo selectedTheme = iconManager.readConfig();
2616
        // if (selectedTheme!=null) {
2617
        // iconManager.setDefault(selectedTheme);
2618
        // logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2619
        // }
2620
        // else {
2621
        // // set the default dir and try to load the default theme
2622
        // try {
2623
        // iconManager.setThemesDir(new File("iconThemes"));
2624
        // IconThemeInfo[] list = iconManager.list();
2625
        //
2626
        // for (int i=0; i<list.length; i++) {
2627
        // if (list[i].getResourceName().equals("iconThemes/icons")) {
2628
        // iconManager.setDefault(list[i]);
2629
        // logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2630
        // return;
2631
        // }
2632
        // }
2633
        // } catch (FileNotFoundException e) {
2634
        // logger.info("IconTheme basedir does not exist");
2635
        // }
2636
        // // create an empty theme
2637
        // IconThemeInfo info = new IconThemeInfo();
2638
        // info.setName("No theme loaded");
2639
        // info.setResource(null); // null resource means that no real theme is
2640
        // loaded
2641
        // info.setDescription("No theme loaded");
2642
        // info.setVersion("0");
2643
        // iconManager.setDefault(new IconTheme(info));
2644
        // logger.info("Setting an empty icon theme");
2645
        //
2646
        // }
2647
        // }
2648

    
2649
        public static void initIconThemes() {
2650
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2651
                IIconTheme icontheme = iconManager.getIconThemeFromConfig();
2652
                if (icontheme != null) {
2653
                        iconManager.setCurrent(icontheme);
2654
                }
2655
        }
2656

    
2657
        /**
2658
         * Manages Andami termination process
2659
         * 
2660
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2661
         */
2662
        public class TerminationProcess {
2663

    
2664
                private boolean proceed = false;
2665
                private UnsavedDataPanel panel = null;
2666

    
2667
                public void run() {
2668
                        try {
2669
                                int exit = manageUnsavedData();
2670
                                if ((exit == JOptionPane.NO_OPTION)
2671
                                                || (exit == JOptionPane.CLOSED_OPTION)) {
2672
                                        // the user doesn't want to exit
2673
                                        return;
2674
                                }
2675
                                closeAndami();
2676
                        } catch (Exception e) {
2677
                                // It is not possible to close the application.
2678
                                // this exception has been registered before
2679
                        }
2680
                }
2681

    
2682
                /**
2683
                 * Finishes the application without asking user if want or not to save
2684
                 * unsaved data.
2685
                 */
2686
                public void closeAndami() {
2687
                        try {
2688
                                saveAndamiConfig();
2689
                        } catch (Exception ex) {
2690
                                logger
2691
                                                .error(
2692
                                                                "There was an error exiting application, can't save andami-config.xml",
2693
                                                                ex);
2694
                        }
2695

    
2696
                        try {
2697
                                // Persistencia de los plugins
2698
                                savePluginPersistence();
2699
                                savePluginsProperties();
2700
                        } catch (Exception ex) {
2701
                                logger
2702
                                                .error(
2703
                                                                "There was an error exiting application, can't save plugins properties",
2704
                                                                ex);
2705
                        }
2706

    
2707
                        // Finalize all the extensions
2708
                        finalizeExtensions();
2709

    
2710
                        try {
2711
                                // Clean any temp data created
2712
                                Utilities.cleanUpTempFiles();
2713
                        } catch (Exception ex) {
2714
                                logger
2715
                                                .error(
2716
                                                                "There was an error exiting application, can't remove temporary files",
2717
                                                                ex);
2718
                        }
2719

    
2720
                        logger.info("Quiting application.");
2721

    
2722
                        // Para la depuraci?n de memory leaks
2723
                        System.gc();
2724

    
2725
                        System.exit(0);
2726
                }
2727

    
2728
                /**
2729
         * 
2730
         */
2731
                public void saveAndamiConfig() {
2732
                        // Configuraci?n de Andami
2733
                        try {
2734
                                andamiConfigToXML(andamiConfigPath);
2735
                        } catch (MarshalException e) {
2736
                                logger
2737
                                                .error(
2738
                                                                Messages
2739
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2740
                                                                e);
2741
                        } catch (ValidationException e) {
2742
                                logger
2743
                                                .error(
2744
                                                                Messages
2745
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2746
                                                                e);
2747
                        } catch (IOException e) {
2748
                                logger
2749
                                                .error(
2750
                                                                Messages
2751
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2752
                                                                e);
2753
                        }
2754
                }
2755

    
2756
                private void savePluginsProperties() {
2757
                        PluginsManager manager = PluginsLocator.getManager();
2758
                        List<PluginServices> plugins = manager.getPlugins();
2759
                        for (PluginServices plugin : plugins) {
2760
                                if (plugin != null) {
2761
                                        plugin.savePluginProperties();
2762
                                }
2763
                        }
2764
                }
2765

    
2766
                /**
2767
                 * Exectutes the terminate method for all the extensions, in the reverse
2768
                 * order they were initialized
2769
                 * 
2770
                 */
2771
                private void finalizeExtensions() {
2772
                        for (int i = extensions.size() - 1; i >= 0; i--) {
2773
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
2774
                                                .get(i);
2775
                                String extensionName = "(unknow)";
2776
                                try {
2777
                                        extensionName = extensionInstance.getClass().getName();
2778
                                        extensionInstance.terminate();
2779
                                } catch (Exception ex) {
2780
                                        logger.error(MessageFormat.format(
2781
                                                        "There was an error extension ending {0}",
2782
                                                        extensionName), ex);
2783
                                }
2784
                        }
2785
                }
2786

    
2787
                private IUnsavedData[] getUnsavedData() throws Exception {
2788
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
2789
                        IExtension exclusiveExtension = PluginServices
2790
                                        .getExclusiveUIExtension();
2791

    
2792
                        for (int i = extensions.size() - 1; i >= 0; i--) {
2793
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
2794
                                                .get(i);
2795
                                IExtensionStatus status = null;
2796
                                if (exclusiveExtension != null) {
2797
                                        status = exclusiveExtension.getStatus(extensionInstance);
2798
                                } else {
2799
                                        status = extensionInstance.getStatus();
2800
                                }
2801
                                if (status != null) {
2802
                                        try {
2803
                                                if (status.hasUnsavedData()) {
2804
                                                        IUnsavedData[] array = status.getUnsavedData();
2805
                                                        for (int element = 0; element < array.length; element++) {
2806
                                                                unsavedDataList.add(array[element]);
2807
                                                        }
2808
                                                }
2809
                                        } catch (Exception e) {
2810
                                                logger.info("Error calling the hasUnsavedData method",
2811
                                                                new Exception());
2812
                                                int option = JOptionPane
2813
                                                                .showConfirmDialog(
2814
                                                                                frame,
2815
                                                                                Messages
2816
                                                                                                .getString("error_getting_unsaved_data"),
2817
                                                                                Messages.getString("MDIFrame.salir"),
2818
                                                                                JOptionPane.YES_NO_OPTION);
2819
                                                if (option == JOptionPane.NO_OPTION) {
2820
                                                        throw e;
2821
                                                }
2822
                                        }
2823
                                }
2824
                        }
2825
                        return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
2826
                                        .size()]);
2827
                }
2828

    
2829
                public UnsavedDataPanel getUnsavedDataPanel() {
2830
                        if (panel == null) {
2831
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
2832
                        }
2833
                        return panel;
2834
                }
2835

    
2836
                /**
2837
                 * Checks if the extensions have some unsaved data, and shows a dialog
2838
                 * to allow saving it. This dialog also allows to don't exit Andami.
2839
                 * 
2840
                 * @return true if the user confirmed he wishes to exit, false otherwise
2841
                 * @throws Exception
2842
                 */
2843
                public int manageUnsavedData() throws Exception {
2844
                        IUnsavedData[] unsavedData = getUnsavedData();
2845

    
2846
                        // there was no unsaved data
2847
                        if (unsavedData.length == 0) {
2848
                                int option = JOptionPane
2849
                                                .showConfirmDialog(frame, Messages
2850
                                                                .getString("MDIFrame.quiere_salir"), Messages
2851
                                                                .getString("MDIFrame.salir"),
2852
                                                                JOptionPane.YES_NO_OPTION);
2853
                                return option;
2854
                        }
2855

    
2856
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2857
                        panel.setUnsavedDataArray(unsavedData);
2858

    
2859
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2860

    
2861
                                public void cancel(UnsavedDataPanel panel) {
2862
                                        proceed(false);
2863
                                        PluginServices.getMDIManager().closeWindow(panel);
2864

    
2865
                                }
2866

    
2867
                                public void discard(UnsavedDataPanel panel) {
2868
                                        proceed(true);
2869
                                        PluginServices.getMDIManager().closeWindow(panel);
2870

    
2871
                                }
2872

    
2873
                                public void accept(UnsavedDataPanel panel) {
2874
                                        IUnsavedData[] unsavedDataArray = panel
2875
                                                        .getSelectedsUnsavedData();
2876
                                        boolean saved;
2877
                                        for (int i = 0; i < unsavedDataArray.length; i++) {
2878
                                                try {
2879
                                                        saved = unsavedDataArray[i].saveData();
2880
                                                } catch (Exception ex) {
2881
                                                        PluginServices.getLogger().error(
2882
                                                                        "Error saving"
2883
                                                                                        + unsavedDataArray[i]
2884
                                                                                                        .getResourceName(), ex);
2885
                                                        saved = false;
2886
                                                }
2887
                                                if (!saved) {
2888
                                                        JOptionPane
2889
                                                                        .showMessageDialog(
2890
                                                                                        panel,
2891
                                                                                        PluginServices
2892
                                                                                                        .getText(this,
2893
                                                                                                                        "The_following_resource_could_not_be_saved_")
2894
                                                                                                        + "\n"
2895
                                                                                                        + unsavedDataArray[i]
2896
                                                                                                                        .getResourceName()
2897
                                                                                                        + " -- "
2898
                                                                                                        + unsavedDataArray[i]
2899
                                                                                                                        .getDescription(),
2900
                                                                                        PluginServices.getText(this,
2901
                                                                                                        "Resource_was_not_saved"),
2902
                                                                                        JOptionPane.ERROR_MESSAGE);
2903

    
2904
                                                        try {
2905
                                                                unsavedDataArray = getUnsavedData();
2906
                                                        } catch (Exception e) {
2907
                                                                // This exception has been registered before
2908
                                                        }
2909
                                                        panel.setUnsavedDataArray(unsavedDataArray);
2910
                                                        return;
2911
                                                }
2912
                                        }
2913
                                        proceed(true);
2914
                                        PluginServices.getMDIManager().closeWindow(panel);
2915
                                }
2916
                        });
2917

    
2918
                        PluginServices.getMDIManager().addWindow(panel);
2919
                        if (proceed) {
2920
                                return JOptionPane.YES_OPTION;
2921
                        } else {
2922
                                return JOptionPane.NO_OPTION;
2923
                        }
2924
                }
2925

    
2926
                private void proceed(boolean proceed) {
2927
                        this.proceed = proceed;
2928
                }
2929

    
2930
        }
2931

    
2932
        public static TerminationProcess getTerminationProcess() {
2933
                return (new Launcher()).new TerminationProcess();
2934
        }
2935

    
2936
        /**
2937
         * Launch the gvSIG package installer.
2938
         * 
2939
         * @throws Exception
2940
         *             if there is any error
2941
         */
2942
        private void doInstall(String[] args) throws Exception {
2943
                String installURL = null;
2944
                String installURLFile = null;
2945
                String gvSIGVersion = null;
2946
                String[] myArgs = new String[2];
2947

    
2948
                Options options = new Options();
2949
                options.addOption("i", "install", false, "install");
2950
                options.addOption("u", "installURL", true, "installURL");
2951
                options.addOption("f", "installURLFile", true, "installURLFile");
2952
                options.addOption("v", "installVersion", true, "installVersion");
2953
                options.addOption("A", "applicationName", true, "applicationName");
2954
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
2955

    
2956
                CommandLineParser parser = new PosixParser();
2957
                CommandLine line = null;
2958
                try {
2959
                        line = parser.parse(options, args);
2960
                        boolean hasAllMandatoryOptions = true;
2961
                        if (!line.hasOption("install")) {
2962
                                hasAllMandatoryOptions = false;
2963
                        }
2964
                        if (line.hasOption("installURL")) {
2965
                                installURL = line.getOptionValue("installURL");
2966
                        }
2967
                        if (line.hasOption("installURLFile")) {
2968
                                installURLFile = line.getOptionValue("installURLFile");
2969
                        }
2970
                        if (line.hasOption("installVersion")) {
2971
                                gvSIGVersion = line.getOptionValue("installVersion");
2972
                        }
2973
                        if (line.hasOption("applicationName")) {
2974
                                myArgs[0] = line.getOptionValue("applicationName");
2975
                        } else {
2976
                                hasAllMandatoryOptions = false;
2977
                        }
2978
                        if (line.hasOption("pluginsFolder")) {
2979
                                myArgs[1] = line.getOptionValue("pluginsFolder");
2980
                        } else {
2981
                                hasAllMandatoryOptions = false;
2982
                        }
2983
                        if (!hasAllMandatoryOptions) {
2984
                                System.err
2985
                                                .println(Messages.get("usage")
2986
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
2987
                                                                + "[--installURLFile=File] "
2988
                                                                + "--install [--installURL=URL] [language=locale]");
2989
                                return;
2990
                        }
2991
                } catch (ParseException exp) {
2992
                        System.out.println("Unexpected exception:" + exp.getMessage());
2993
                }
2994

    
2995
                initializeApp(myArgs);
2996
                initializeLibraries();
2997
                AndamiConfig config = getAndamiConfig();
2998
                config.setLocaleLanguage(locale.getLanguage());
2999
                config.setLocaleCountry(locale.getCountry());
3000
                config.setLocaleVariant(locale.getVariant());
3001

    
3002
                // Configure default index download URL
3003
                if (installURL != null) {
3004
                        SwingInstallerLocator.getSwingInstallerManager()
3005
                                        .setDefaultDownloadURL(installURL);
3006
                }
3007

    
3008
                if (installURLFile != null) {
3009
                        // TODO: Convertir a File y pasarlo
3010
                        SwingInstallerLocator.getSwingInstallerManager()
3011
                                        .setDefaultDownloadURL(new File(installURLFile));
3012
                }
3013

    
3014
                // Launch installer
3015
                PluginsManager manager = PluginsLocator.getManager();
3016

    
3017
                File defaultAddonsRepository = PluginsLocator.getManager()
3018
                                .getPluginsFolder();
3019
                InstallerManager installerManager = InstallerLocator
3020
                                .getInstallerManager();
3021
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3022
                installerManager
3023
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3024

    
3025
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3026
                                .getSwingInstallerManager().createInstallPackageWizard(
3027
                                                manager.getApplicationFolder(),
3028
                                                manager.getInstallFolder());
3029
                installPackageWizard
3030
                                .setWizardActionListener(new InstallerWizardActionListener() {
3031

    
3032
                                        public void finish(InstallerWizardPanel installerWizard) {
3033
                                                System.exit(0);
3034
                                        }
3035

    
3036
                                        public void cancel(InstallerWizardPanel installerWizard) {
3037
                                                System.exit(0);
3038
                                        }
3039
                                });
3040

    
3041
                // the wizard will show the Typical or Advanced mode option.
3042
                installPackageWizard.setAskTypicalOrCustom(true);
3043
                // default packages will be selected.
3044
                installPackageWizard.setSelectDefaultPackages(true);
3045

    
3046
                // set the gvSIG version to the install manager, to compose the download
3047
                // URL:
3048
                InstallerLocator.getInstallerManager().setVersion(gvSIGVersion);
3049

    
3050
                // 1. Create the frame.
3051
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3052

    
3053
                // 2. What happens when the frame closes?
3054
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3055
                Runtime.getRuntime().addShutdownHook(new Thread() {
3056

    
3057
                        @Override
3058
                        public void run() {
3059
                                getTerminationProcess().saveAndamiConfig();
3060
                        }
3061
                });
3062

    
3063
                // 3. Add the installer panel to the frame
3064
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3065

    
3066
                // 4. Size the frame and center on the screen
3067
                frame.pack();
3068
                frame.setLocationRelativeTo(null);
3069

    
3070
                // 5. Show it.
3071
                frame.setVisible(true);
3072
        }
3073

    
3074
        public static String getInformation() {
3075
                PluginsManager pluginmgr = PluginsLocator.getManager();
3076
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3077

    
3078
                StringWriter writer = new StringWriter();
3079

    
3080
                Properties props = System.getProperties();
3081

    
3082
                // OS information
3083
                String osName = props.getProperty("os.name");
3084
                writer.write("OS\n");
3085
                writer.write("    name   : " + osName + "\n");
3086
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3087
                writer.write("    version: " + props.get("os.version") + "\n");
3088
                if (osName.startsWith("Linux")) {
3089
                        try {
3090
                                String[] command = { "lsb_release", "-a" };
3091
                                Process p = Runtime.getRuntime().exec(command);
3092
                                InputStream is = p.getInputStream();
3093
                                BufferedReader reader = new BufferedReader(
3094
                                                new InputStreamReader(is));
3095
                                String line;
3096
                                while ((line = reader.readLine()) != null) {
3097
                                        writer.write("    " + line + "\n");
3098
                                }
3099
                        } catch (Exception ex) {
3100
                                writer
3101
                                                .write("Can't get detailled os information (lsb_release -a).");
3102
                        }
3103
                }
3104

    
3105
                // JRE information
3106
                writer.write("JRE\n");
3107
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3108
                writer.write("    version: " + props.get("java.version") + "\n");
3109
                writer.write("    home   : " + props.get("java.home") + "\n");
3110

    
3111
                writer.write("HTTP Proxy\n");
3112
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3113
                                + "\n");
3114
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3115
                                + "\n");
3116
                writer.write("    http.proxyUserName : "
3117
                                + props.get("http.proxyUserName") + "\n");
3118
                writer.write("    http.proxyPassword : "
3119
                                + props.get("http.proxyPassword") + "\n");
3120

    
3121
                String skinName = "(unknow)";
3122
                try {
3123
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3124
                } catch (Throwable e) {
3125
                        // Ignore
3126
                }
3127
                writer.write("Application\n");
3128
                writer.write("    locale language         : "
3129
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3130
                writer.write("    application forlder     : "
3131
                                + pluginmgr.getApplicationFolder() + "\n");
3132
                writer.write("    install forlder         : "
3133
                                + pluginmgr.getInstallFolder() + "\n");
3134
                writer.write("    application home forlder: "
3135
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3136
                writer.write("    plugins forlder         : "
3137
                                + pluginmgr.getPluginsFolder() + "\n");
3138
                writer.write("    theme                   : "
3139
                                + Launcher.theme.getSource() + "\n");
3140
                // writer.write("    Skin                    : " + skinName + "\n");
3141

    
3142
                try {
3143
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3144
                                        .getPluginsFolder());
3145
                        writer.write("Installed packages\n");
3146
                        for (int i = 0; i < pkgs.length; i++) {
3147
                                writer.write("    ");
3148
                                writer.write(pkgs[i].toStringCompact());
3149
                                writer.write("\n");
3150
                        }
3151
                } catch (Throwable e) {
3152
                        writer.write("Can't get installed package information.");
3153
                }
3154
                return writer.toString();
3155
        }
3156

    
3157
        private void logger_info(String msg) {
3158
                String info[] = msg.split("\n");
3159
                for (int i = 0; i < info.length; i++) {
3160
                        logger.info(info[i]);
3161
                }
3162
        }
3163

    
3164
}