Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / frameworks / _fwAndami / src / org / gvsig / andami / Launcher.java @ 37830

History | View | Annotate | Download (92.1 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.nio.channels.FileChannel;
70
import java.security.AllPermission;
71
import java.security.CodeSource;
72
import java.security.PermissionCollection;
73
import java.security.Permissions;
74
import java.security.Policy;
75
import java.text.MessageFormat;
76
import java.util.ArrayList;
77
import java.util.Comparator;
78
import java.util.HashMap;
79
import java.util.HashSet;
80
import java.util.Iterator;
81
import java.util.List;
82
import java.util.Locale;
83
import java.util.Map;
84
import java.util.Properties;
85
import java.util.Set;
86
import java.util.TreeSet;
87
import java.util.prefs.Preferences;
88

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

    
98
import org.apache.commons.cli.CommandLine;
99
import org.apache.commons.cli.CommandLineParser;
100
import org.apache.commons.cli.Options;
101
import org.apache.commons.cli.ParseException;
102
import org.apache.commons.cli.PosixParser;
103
import org.apache.log4j.AppenderSkeleton;
104
import org.apache.log4j.PatternLayout;
105
import org.apache.log4j.PropertyConfigurator;
106
import org.apache.log4j.RollingFileAppender;
107
import org.apache.log4j.spi.LoggingEvent;
108
import org.exolab.castor.xml.MarshalException;
109
import org.exolab.castor.xml.ValidationException;
110
import org.gvsig.andami.authentication.IAuthentication;
111
import org.gvsig.andami.authentication.LoginUI;
112
import org.gvsig.andami.config.generate.Andami;
113
import org.gvsig.andami.config.generate.AndamiConfig;
114
import org.gvsig.andami.config.generate.Plugin;
115
import org.gvsig.andami.iconthemes.IIconTheme;
116
import org.gvsig.andami.iconthemes.IconThemeManager;
117
import org.gvsig.andami.messages.Messages;
118
import org.gvsig.andami.messages.NotificationManager;
119
import org.gvsig.andami.plugins.ExclusiveUIExtension;
120
import org.gvsig.andami.plugins.ExtensionDecorator;
121
import org.gvsig.andami.plugins.IExtension;
122
import org.gvsig.andami.plugins.PluginClassLoader;
123
import org.gvsig.andami.plugins.config.generate.ActionTool;
124
import org.gvsig.andami.plugins.config.generate.ComboButton;
125
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
126
import org.gvsig.andami.plugins.config.generate.ComboScale;
127
import org.gvsig.andami.plugins.config.generate.Depends;
128
import org.gvsig.andami.plugins.config.generate.Extension;
129
import org.gvsig.andami.plugins.config.generate.Extensions;
130
import org.gvsig.andami.plugins.config.generate.LabelSet;
131
import org.gvsig.andami.plugins.config.generate.Menu;
132
import org.gvsig.andami.plugins.config.generate.PluginConfig;
133
import org.gvsig.andami.plugins.config.generate.PopupMenu;
134
import org.gvsig.andami.plugins.config.generate.PopupMenus;
135
import org.gvsig.andami.plugins.config.generate.SelectableTool;
136
import org.gvsig.andami.plugins.config.generate.SkinExtension;
137
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
138
import org.gvsig.andami.plugins.config.generate.ToolBar;
139
import org.gvsig.andami.plugins.status.IExtensionStatus;
140
import org.gvsig.andami.plugins.status.IUnsavedData;
141
import org.gvsig.andami.ui.AndamiEventQueue;
142
import org.gvsig.andami.ui.MDIManagerLoadException;
143
import org.gvsig.andami.ui.ToolsWindowManager;
144
import org.gvsig.andami.ui.fonts.FontUtils;
145
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
146
import org.gvsig.andami.ui.mdiFrame.NewStatusBar;
147
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
148
import org.gvsig.andami.ui.splash.MultiSplashWindow;
149
import org.gvsig.andami.ui.theme.Theme;
150
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
151
import org.gvsig.installer.lib.api.InstallerLocator;
152
import org.gvsig.installer.lib.api.InstallerManager;
153
import org.gvsig.installer.lib.api.PackageInfo;
154
import org.gvsig.installer.swing.api.SwingInstallerLocator;
155
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
156
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
157
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
158
import org.gvsig.tools.exception.ListBaseException;
159
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
160
import org.gvsig.tools.swing.api.ToolsSwingLocator;
161
import org.gvsig.utils.DateTime;
162
import org.gvsig.utils.XMLEntity;
163
import org.gvsig.utils.xml.XMLEncodingUtils;
164
import org.gvsig.utils.xmlEntity.generate.XmlTag;
165
import org.slf4j.Logger;
166
import org.slf4j.LoggerFactory;
167

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

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

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

    
210
        protected static ListBaseException launcherrors = null;
211

    
212
        protected static Theme theme = null;
213

    
214
        private static final class ProxyAuth extends Authenticator {
215

    
216
                private PasswordAuthentication auth;
217

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

    
222
                protected PasswordAuthentication getPasswordAuthentication() {
223
                        return auth;
224
                }
225
        }
226

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

    
247
        protected void downloadExtensions(String extDir) {
248
                // do nothing
249
        }
250

    
251
        public static class LaunchException extends ListBaseException {
252

    
253
                private static final long serialVersionUID = 4541192746962684705L;
254

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

    
261
        }
262

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

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

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

    
279
        public void doMain(String[] args) throws Exception {
280

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

    
286
                initializeApp(args);
287

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

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

    
299
                        public void refresh() {
300
                        }
301
                });
302

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
411
                SwingUtilities.invokeAndWait(new Runnable() {
412

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

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

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

    
432
                        public void run() {
433
                                initializeExtensions();
434
                        }
435
                });
436

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

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

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

    
453
                        public void run() {
454
                                installPluginsControls();
455

    
456
                        }
457
                });
458

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

    
464
                        public void run() {
465
                                installPluginsMenus();
466

    
467
                        }
468
                });
469

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

    
475
                        public void run() {
476
                                installPluginsLabels();
477

    
478
                        }
479
                });
480

    
481
                // 18. Se instalan los bookmarks de los plugins
482

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

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

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

    
501
                        public void run() {
502
                                postInitializeExtensions();
503

    
504
                        }
505
                });
506

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

    
514
                SwingUtilities.invokeAndWait(new Runnable() {
515

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

    
525
                org.apache.log4j.Logger.getRootLogger().addAppender(
526
                                new NotificationAppender());
527

    
528
        }
529

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

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

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

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

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

    
568
                // Clean temporal files
569
                Utilities.cleanUpTempFiles();
570

    
571
                appName = args[0];
572

    
573
                getOrCreateConfigFolder();
574

    
575
                configureLogging(appName);
576

    
577
                loadAndamiConfig(args[1]);
578

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

    
584
                configureLocales(args);
585

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

    
592
                logger.info("Configure LookAndFeel");
593
                configureLookAndFeel();
594
        }
595

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

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

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

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

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

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

    
662
        private class NotificationAppender extends AppenderSkeleton {
663

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

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

    
683
                }
684

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

    
691
        }
692

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

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

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

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

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

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

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

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

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

    
822
                System.getProperties().put("http.proxyHost", host);
823
                System.getProperties().put("http.proxyPort", port);
824

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

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

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

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

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

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

    
898
        private void loadPluginsPersistence() throws ConfigurationException {
899
                XMLEntity entity = persistenceFromXML();
900

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

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

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

    
928
                XMLEntity entity = new XMLEntity();
929

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

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

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

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

    
964
                        LabelSet[] ls = pc.getLabelSet();
965

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

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

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

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

    
1001
                Class<? extends IExtension> skinClass;
1002

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

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

    
1032
        }
1033

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

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

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

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

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

    
1095
        }
1096

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

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

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

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

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

    
1127
        private void initializeExtensions() {
1128

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

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

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

    
1159
                        Extension[] exts = pc.getExtensions().getExtension();
1160

    
1161
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1162
                                        new ExtensionComparator());
1163

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

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

    
1174
                                orderedExtensions.add(exts[j]);
1175
                        }
1176

    
1177
                        Iterator<Extension> e = orderedExtensions.iterator();
1178

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

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

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

    
1210
                                        extensionInstance.initialize();
1211
                                        extensions.add(extensionInstance);
1212

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

    
1224
        private void postInitializeExtensions() {
1225
                logger.info("PostInitializing extensions: ");
1226

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

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

    
1246
                Iterator<String> i = pluginsConfig.keySet().iterator();
1247

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

    
1254
                                Extension[] exts = pc.getExtensions().getExtension();
1255

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

    
1261
                                        Menu[] menus = exts[j].getMenu();
1262

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

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

    
1276
                                                orderedMenus.add(sm);
1277
                                        }
1278
                                }
1279

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

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

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

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

    
1299
                                                        orderedMenus.add(sm);
1300
                                                }
1301
                                        }
1302
                                }
1303

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

    
1309
                }
1310

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

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

    
1319
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1320

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

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

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

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

    
1365
                                Extension[] exts = pc.getExtensions().getExtension();
1366

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

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

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

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

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

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

    
1423
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1424

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

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

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

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

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

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

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

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

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

    
1558
                                                        SelectableTool[] sTools = toolbars[k]
1559
                                                                        .getSelectableTool();
1560

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

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

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

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

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

    
1618
                Plugin[] plugins = andamiConfig.getPlugin();
1619

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

    
1624
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1625

    
1626
                while (i.hasNext()) {
1627
                        PluginServices ps = i.next();
1628

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

    
1634
                                andamiConfig.addPlugin(p);
1635
                        }
1636
                }
1637
        }
1638

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

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

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

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

    
1654
                                if (installed.contains(pluginName)) {
1655
                                        continue;
1656
                                }
1657

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

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

    
1673
                                                continue;
1674
                                        }
1675

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

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

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

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

    
1704
                                URL[] urls = new URL[jarFiles.length];
1705

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

    
1716
                                PluginClassLoader loader;
1717

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

    
1724
                                        PluginServices ps = new PluginServices(loader);
1725

    
1726
                                        pluginsServices.put(ps.getPluginName(), ps);
1727

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

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

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

    
1750
                                break;
1751
                        }
1752
                }
1753

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

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

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

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

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

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

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

    
1793
        static String getPluginsDir() {
1794
                return andamiConfig.getPluginsDirectory();
1795
        }
1796

    
1797
        static void setPluginsDir(String s) {
1798
                andamiConfig.setPluginsDirectory(s);
1799
        }
1800

    
1801
        static MDIFrame getMDIFrame() {
1802
                return frame;
1803
        }
1804

    
1805
        private void loadPlugins(String pluginsDirectory) {
1806
                File pDir = new File(pluginsDirectory);
1807

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

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

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

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

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

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

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

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

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

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

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

    
1952
        private static AndamiConfig getDefaultAndamiConfig() {
1953
                AndamiConfig andamiConfig = new AndamiConfig();
1954

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

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

    
1973
                andamiConfig.setPlugin(new Plugin[0]);
1974
                return andamiConfig;
1975
        }
1976

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

    
1980
                if (xml.exists()) {
1981
                        InputStreamReader reader = null;
1982

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

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

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

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

    
2047
        }
2048

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

    
2056
                File xml = getPluginsPersistenceFile(false);
2057
                OutputStreamWriter writer = null;
2058

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

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

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

    
2097
        static MDIFrame getFrame() {
2098
                return frame;
2099
        }
2100

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

    
2111
        static HashMap getClassesExtensions() {
2112
                return classesExtensions;
2113
        }
2114

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

    
2119
                while (iter.hasNext()) {
2120
                        array.add(iter.next().getExtensions());
2121
                }
2122

    
2123
                return array.toArray(new Extensions[array.size()]);
2124
        }
2125

    
2126
        public static Iterator getExtensionIterator() {
2127
                return extensions.iterator();
2128
        }
2129

    
2130
        public static HashMap getPluginConfig() {
2131
                return pluginsConfig;
2132
        }
2133

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

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

    
2145
                return null;
2146
        }
2147

    
2148
        public static AndamiConfig getAndamiConfig() {
2149
                return andamiConfig;
2150
        }
2151

    
2152
        private static class ExtensionComparator implements Comparator {
2153

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

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

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

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

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

    
2178
        private static class MenuComparator implements Comparator<SortableMenu> {
2179

    
2180
                private static ExtensionComparator extComp = new ExtensionComparator();
2181

    
2182
                public int compare(SortableMenu e1, SortableMenu e2) {
2183

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

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

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

    
2211
        private static class SortableMenu {
2212

    
2213
                public PluginClassLoader loader;
2214
                public Menu menu;
2215
                public SkinExtensionType extension;
2216

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

    
2225
        private static class SortableTool {
2226

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

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

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

    
2252
        private static class ToolBarComparator implements Comparator<SortableTool> {
2253

    
2254
                private static ExtensionComparator extComp = new ExtensionComparator();
2255

    
2256
                public int compare(SortableTool e1, SortableTool e2) {
2257

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

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

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

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

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

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

    
2317
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2318

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

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

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

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

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

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

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

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

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

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

    
2408
                return UIManager.getSystemLookAndFeelClassName();
2409
        }
2410

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

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

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

    
2514
        }
2515

    
2516
        /**
2517
         * Gets Home Directory location of the application into users home folder.
2518
         * 
2519
         * May be set from outside the aplication by means of
2520
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2521
         * 
2522
         * @return
2523
         */
2524
        public static String getAppHomeDir() {
2525
                return appHomeDir;
2526
        }
2527

    
2528
        /**
2529
         * Sets Home Directory location of the application. May be set from outside
2530
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
2531
         * the name of the application
2532
         * 
2533
         * @param appHomeDir
2534
         */
2535
        public static void setAppHomeDir(String appHomeDir) {
2536
                Launcher.appHomeDir = appHomeDir;
2537
        }
2538

    
2539
        /**
2540
         * Initialize the extesion that have to take the control of the state of
2541
         * action controls of the UI of all extensions. <br>
2542
         * <br>
2543
         * For use this option you have to add an argument to the command line like
2544
         * this: <br>
2545
         * <br>
2546
         * -exclusiveUI={pathToExtensionClass} <br>
2547
         * 
2548
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
2549
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
2550
         */
2551
        private static void initializeExclusiveUIExtension() {
2552
                String name = PluginServices.getArgumentByName("exclusiveUI");
2553
                if (name == null) {
2554
                        return;
2555
                }
2556

    
2557
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
2558
                                .iterator();
2559
                int charIndex;
2560
                Class<? extends IExtension> key;
2561
                while (iter.hasNext()) {
2562
                        key = iter.next();
2563
                        charIndex = key.getName().indexOf(name);
2564
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2565
                        if (charIndex == 0) {
2566
                                IExtension ext = classesExtensions.get(key);
2567
                                if (ext instanceof ExtensionDecorator) {
2568
                                        ext = ((ExtensionDecorator) ext).getExtension();
2569
                                }
2570
                                if (ext instanceof ExclusiveUIExtension) {
2571
                                        PluginServices
2572
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
2573
                                }
2574
                                break;
2575
                        }
2576
                }
2577

    
2578
                logger
2579
                                .error(Messages
2580
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2581
                                                + " '" + name + "'");
2582
        }
2583

    
2584
        // public static void initIconThemes() {
2585
        // // load the iconTheme
2586
        // IconThemeManager iconManager = new IconThemeManager();
2587
        // PluginServices.setIconThemeManager(iconManager);
2588
        // IconThemeInfo selectedTheme = iconManager.readConfig();
2589
        // if (selectedTheme!=null) {
2590
        // iconManager.setDefault(selectedTheme);
2591
        // logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2592
        // }
2593
        // else {
2594
        // // set the default dir and try to load the default theme
2595
        // try {
2596
        // iconManager.setThemesDir(new File("iconThemes"));
2597
        // IconThemeInfo[] list = iconManager.list();
2598
        //
2599
        // for (int i=0; i<list.length; i++) {
2600
        // if (list[i].getResourceName().equals("iconThemes/icons")) {
2601
        // iconManager.setDefault(list[i]);
2602
        // logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2603
        // return;
2604
        // }
2605
        // }
2606
        // } catch (FileNotFoundException e) {
2607
        // logger.info("IconTheme basedir does not exist");
2608
        // }
2609
        // // create an empty theme
2610
        // IconThemeInfo info = new IconThemeInfo();
2611
        // info.setName("No theme loaded");
2612
        // info.setResource(null); // null resource means that no real theme is
2613
        // loaded
2614
        // info.setDescription("No theme loaded");
2615
        // info.setVersion("0");
2616
        // iconManager.setDefault(new IconTheme(info));
2617
        // logger.info("Setting an empty icon theme");
2618
        //
2619
        // }
2620
        // }
2621

    
2622
        public static void initIconThemes() {
2623
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2624
                IIconTheme icontheme = iconManager.getIconThemeFromConfig();
2625
                if (icontheme != null) {
2626
                        iconManager.setCurrent(icontheme);
2627
                }
2628
        }
2629

    
2630
        /**
2631
         * Manages Andami termination process
2632
         * 
2633
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2634
         */
2635
        public class TerminationProcess {
2636

    
2637
                private boolean proceed = false;
2638
                private UnsavedDataPanel panel = null;
2639

    
2640
                public void run() {
2641
                        try {
2642
                                int exit = manageUnsavedData();
2643
                                if ((exit == JOptionPane.NO_OPTION)
2644
                                                || (exit == JOptionPane.CLOSED_OPTION)) {
2645
                                        // the user doesn't want to exit
2646
                                        return;
2647
                                }
2648
                                closeAndami();
2649
                        } catch (Exception e) {
2650
                                // It is not possible to close the application.
2651
                                // this exception has been registered before
2652
                        }
2653
                }
2654

    
2655
                /**
2656
                 * Finishes the application without asking user if want or not to save
2657
                 * unsaved data.
2658
                 */
2659
                public void closeAndami() {
2660
                        try {
2661
                                saveAndamiConfig();
2662
                        } catch (Exception ex) {
2663
                                logger
2664
                                                .error(
2665
                                                                "There was an error exiting application, can't save andami-config.xml",
2666
                                                                ex);
2667
                        }
2668

    
2669
                        try {
2670
                                // Persistencia de los plugins
2671
                                savePluginPersistence();
2672
                                savePluginsProperties();
2673
                        } catch (Exception ex) {
2674
                                logger
2675
                                                .error(
2676
                                                                "There was an error exiting application, can't save plugins properties",
2677
                                                                ex);
2678
                        }
2679

    
2680
                        // Finalize all the extensions
2681
                        finalizeExtensions();
2682

    
2683
                        try {
2684
                                // Clean any temp data created
2685
                                Utilities.cleanUpTempFiles();
2686
                        } catch (Exception ex) {
2687
                                logger
2688
                                                .error(
2689
                                                                "There was an error exiting application, can't remove temporary files",
2690
                                                                ex);
2691
                        }
2692

    
2693
                        logger.info("Quiting application.");
2694

    
2695
                        // Para la depuraci?n de memory leaks
2696
                        System.gc();
2697

    
2698
                        System.exit(0);
2699
                }
2700

    
2701
                /**
2702
         * 
2703
         */
2704
                public void saveAndamiConfig() {
2705
                        // Configuraci?n de Andami
2706
                        try {
2707
                                andamiConfigToXML(andamiConfigPath);
2708
                        } catch (MarshalException e) {
2709
                                logger
2710
                                                .error(
2711
                                                                Messages
2712
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2713
                                                                e);
2714
                        } catch (ValidationException e) {
2715
                                logger
2716
                                                .error(
2717
                                                                Messages
2718
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2719
                                                                e);
2720
                        } catch (IOException e) {
2721
                                logger
2722
                                                .error(
2723
                                                                Messages
2724
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
2725
                                                                e);
2726
                        }
2727
                }
2728

    
2729
                private void savePluginsProperties() {
2730
                        PluginsManager manager = PluginsLocator.getManager();
2731
                        List<PluginServices> plugins = manager.getPlugins();
2732
                        for (PluginServices plugin : plugins) {
2733
                                if (plugin != null) {
2734
                                        plugin.savePluginProperties();
2735
                                }
2736
                        }
2737
                }
2738

    
2739
                /**
2740
                 * Exectutes the terminate method for all the extensions, in the reverse
2741
                 * order they were initialized
2742
                 * 
2743
                 */
2744
                private void finalizeExtensions() {
2745
                        for (int i = extensions.size() - 1; i >= 0; i--) {
2746
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
2747
                                                .get(i);
2748
                                String extensionName = "(unknow)";
2749
                                try {
2750
                                        extensionName = extensionInstance.getClass().getName();
2751
                                        extensionInstance.terminate();
2752
                                } catch (Exception ex) {
2753
                                        logger.error(MessageFormat.format(
2754
                                                        "There was an error extension ending {0}",
2755
                                                        extensionName), ex);
2756
                                }
2757
                        }
2758
                }
2759

    
2760
                private IUnsavedData[] getUnsavedData() throws Exception {
2761
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
2762
                        IExtension exclusiveExtension = PluginServices
2763
                                        .getExclusiveUIExtension();
2764

    
2765
                        for (int i = extensions.size() - 1; i >= 0; i--) {
2766
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
2767
                                                .get(i);
2768
                                IExtensionStatus status = null;
2769
                                if (exclusiveExtension != null) {
2770
                                        status = exclusiveExtension.getStatus(extensionInstance);
2771
                                } else {
2772
                                        status = extensionInstance.getStatus();
2773
                                }
2774
                                if (status != null) {
2775
                                        try {
2776
                                                if (status.hasUnsavedData()) {
2777
                                                        IUnsavedData[] array = status.getUnsavedData();
2778
                                                        for (int element = 0; element < array.length; element++) {
2779
                                                                unsavedDataList.add(array[element]);
2780
                                                        }
2781
                                                }
2782
                                        } catch (Exception e) {
2783
                                                logger.info("Error calling the hasUnsavedData method",
2784
                                                                new Exception());
2785
                                                int option = JOptionPane
2786
                                                                .showConfirmDialog(
2787
                                                                                frame,
2788
                                                                                Messages
2789
                                                                                                .getString("error_getting_unsaved_data"),
2790
                                                                                Messages.getString("MDIFrame.salir"),
2791
                                                                                JOptionPane.YES_NO_OPTION);
2792
                                                if (option == JOptionPane.NO_OPTION) {
2793
                                                        throw e;
2794
                                                }
2795
                                        }
2796
                                }
2797
                        }
2798
                        return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
2799
                                        .size()]);
2800
                }
2801

    
2802
                public UnsavedDataPanel getUnsavedDataPanel() {
2803
                        if (panel == null) {
2804
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
2805
                        }
2806
                        return panel;
2807
                }
2808

    
2809
                /**
2810
                 * Checks if the extensions have some unsaved data, and shows a dialog
2811
                 * to allow saving it. This dialog also allows to don't exit Andami.
2812
                 * 
2813
                 * @return true if the user confirmed he wishes to exit, false otherwise
2814
                 * @throws Exception
2815
                 */
2816
                public int manageUnsavedData() throws Exception {
2817
                        IUnsavedData[] unsavedData = getUnsavedData();
2818

    
2819
                        // there was no unsaved data
2820
                        if (unsavedData.length == 0) {
2821
                                int option = JOptionPane
2822
                                                .showConfirmDialog(frame, Messages
2823
                                                                .getString("MDIFrame.quiere_salir"), Messages
2824
                                                                .getString("MDIFrame.salir"),
2825
                                                                JOptionPane.YES_NO_OPTION);
2826
                                return option;
2827
                        }
2828

    
2829
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2830
                        panel.setUnsavedDataArray(unsavedData);
2831

    
2832
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2833

    
2834
                                public void cancel(UnsavedDataPanel panel) {
2835
                                        proceed(false);
2836
                                        PluginServices.getMDIManager().closeWindow(panel);
2837

    
2838
                                }
2839

    
2840
                                public void discard(UnsavedDataPanel panel) {
2841
                                        proceed(true);
2842
                                        PluginServices.getMDIManager().closeWindow(panel);
2843

    
2844
                                }
2845

    
2846
                                public void accept(UnsavedDataPanel panel) {
2847
                                        IUnsavedData[] unsavedDataArray = panel
2848
                                                        .getSelectedsUnsavedData();
2849
                                        boolean saved;
2850
                                        for (int i = 0; i < unsavedDataArray.length; i++) {
2851
                                                try {
2852
                                                        saved = unsavedDataArray[i].saveData();
2853
                                                } catch (Exception ex) {
2854
                                                        PluginServices.getLogger().error(
2855
                                                                        "Error saving"
2856
                                                                                        + unsavedDataArray[i]
2857
                                                                                                        .getResourceName(), ex);
2858
                                                        saved = false;
2859
                                                }
2860
                                                if (!saved) {
2861
                                                        JOptionPane
2862
                                                                        .showMessageDialog(
2863
                                                                                        panel,
2864
                                                                                        PluginServices
2865
                                                                                                        .getText(this,
2866
                                                                                                                        "The_following_resource_could_not_be_saved_")
2867
                                                                                                        + "\n"
2868
                                                                                                        + unsavedDataArray[i]
2869
                                                                                                                        .getResourceName()
2870
                                                                                                        + " -- "
2871
                                                                                                        + unsavedDataArray[i]
2872
                                                                                                                        .getDescription(),
2873
                                                                                        PluginServices.getText(this,
2874
                                                                                                        "Resource_was_not_saved"),
2875
                                                                                        JOptionPane.ERROR_MESSAGE);
2876

    
2877
                                                        try {
2878
                                                                unsavedDataArray = getUnsavedData();
2879
                                                        } catch (Exception e) {
2880
                                                                // This exception has been registered before
2881
                                                        }
2882
                                                        panel.setUnsavedDataArray(unsavedDataArray);
2883
                                                        return;
2884
                                                }
2885
                                        }
2886
                                        proceed(true);
2887
                                        PluginServices.getMDIManager().closeWindow(panel);
2888
                                }
2889
                        });
2890

    
2891
                        PluginServices.getMDIManager().addWindow(panel);
2892
                        if (proceed) {
2893
                                return JOptionPane.YES_OPTION;
2894
                        } else {
2895
                                return JOptionPane.NO_OPTION;
2896
                        }
2897
                }
2898

    
2899
                private void proceed(boolean proceed) {
2900
                        this.proceed = proceed;
2901
                }
2902

    
2903
        }
2904

    
2905
        public static TerminationProcess getTerminationProcess() {
2906
                return (new Launcher()).new TerminationProcess();
2907
        }
2908

    
2909
        /**
2910
         * Launch the gvSIG package installer.
2911
         * 
2912
         * @throws Exception
2913
         *             if there is any error
2914
         */
2915
        private void doInstall(String[] args) throws Exception {
2916
                String installURL = null;
2917
                String installURLFile = null;
2918
                String gvSIGVersion = null;
2919
                String[] myArgs = new String[2];
2920

    
2921
                Options options = new Options();
2922
                options.addOption("i", "install", false, "install");
2923
                options.addOption("u", "installURL", true, "installURL");
2924
                options.addOption("f", "installURLFile", true, "installURLFile");
2925
                options.addOption("v", "installVersion", true, "installVersion");
2926
                options.addOption("A", "applicationName", true, "applicationName");
2927
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
2928

    
2929
                CommandLineParser parser = new PosixParser();
2930
                CommandLine line = null;
2931
                try {
2932
                        line = parser.parse(options, args);
2933
                        boolean hasAllMandatoryOptions = true;
2934
                        if (!line.hasOption("install")) {
2935
                                hasAllMandatoryOptions = false;
2936
                        }
2937
                        if (line.hasOption("installURL")) {
2938
                                installURL = line.getOptionValue("installURL");
2939
                        }
2940
                        if (line.hasOption("installURLFile")) {
2941
                                installURLFile = line.getOptionValue("installURLFile");
2942
                        }
2943
                        if (line.hasOption("installVersion")) {
2944
                                gvSIGVersion = line.getOptionValue("installVersion");
2945
                        }
2946
                        if (line.hasOption("applicationName")) {
2947
                                myArgs[0] = line.getOptionValue("applicationName");
2948
                        } else {
2949
                                hasAllMandatoryOptions = false;
2950
                        }
2951
                        if (line.hasOption("pluginsFolder")) {
2952
                                myArgs[1] = line.getOptionValue("pluginsFolder");
2953
                        } else {
2954
                                hasAllMandatoryOptions = false;
2955
                        }
2956
                        if (!hasAllMandatoryOptions) {
2957
                                System.err
2958
                                                .println(Messages.get("usage")
2959
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
2960
                                                                + "[--installURLFile=File] "
2961
                                                                + "--install [--installURL=URL] [language=locale]");
2962
                                return;
2963
                        }
2964
                } catch (ParseException exp) {
2965
                        System.out.println("Unexpected exception:" + exp.getMessage());
2966
                }
2967

    
2968
                initializeApp(myArgs);
2969
                initializeLibraries();
2970
                AndamiConfig config = getAndamiConfig();
2971
                config.setLocaleLanguage(locale.getLanguage());
2972
                config.setLocaleCountry(locale.getCountry());
2973
                config.setLocaleVariant(locale.getVariant());
2974

    
2975
                // Configure default index download URL
2976
                if (installURL != null) {
2977
                        SwingInstallerLocator.getSwingInstallerManager()
2978
                                        .setDefaultDownloadURL(installURL);
2979
                }
2980

    
2981
                if (installURLFile != null) {
2982
                        // TODO: Convertir a File y pasarlo
2983
                        SwingInstallerLocator.getSwingInstallerManager()
2984
                                        .setDefaultDownloadURL(new File(installURLFile));
2985
                }
2986

    
2987
                // Launch installer
2988
                PluginsManager manager = PluginsLocator.getManager();
2989

    
2990
                File defaultAddonsRepository = PluginsLocator.getManager()
2991
                                .getPluginsFolder();
2992
                InstallerManager installerManager = InstallerLocator
2993
                                .getInstallerManager();
2994
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
2995
                installerManager
2996
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
2997

    
2998
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
2999
                                .getSwingInstallerManager().createInstallPackageWizard(
3000
                                                manager.getApplicationFolder(),
3001
                                                manager.getInstallFolder());
3002
                installPackageWizard
3003
                                .setWizardActionListener(new InstallerWizardActionListener() {
3004

    
3005
                                        public void finish(InstallerWizardPanel installerWizard) {
3006
                                                System.exit(0);
3007
                                        }
3008

    
3009
                                        public void cancel(InstallerWizardPanel installerWizard) {
3010
                                                System.exit(0);
3011
                                        }
3012
                                });
3013

    
3014
                // the wizard will show the Typical or Advanced mode option.
3015
                installPackageWizard.setAskTypicalOrCustom(true);
3016
                // default packages will be selected.
3017
                installPackageWizard.setSelectDefaultPackages(true);
3018

    
3019
                // set the gvSIG version to the install manager, to compose the download
3020
                // URL:
3021
                InstallerLocator.getInstallerManager().setVersion(gvSIGVersion);
3022

    
3023
                // 1. Create the frame.
3024
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3025

    
3026
                // 2. What happens when the frame closes?
3027
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3028
                Runtime.getRuntime().addShutdownHook(new Thread() {
3029

    
3030
                        @Override
3031
                        public void run() {
3032
                                getTerminationProcess().saveAndamiConfig();
3033
                        }
3034
                });
3035

    
3036
                // 3. Add the installer panel to the frame
3037
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3038

    
3039
                // 4. Size the frame and center on the screen
3040
                frame.pack();
3041
                frame.setLocationRelativeTo(null);
3042

    
3043
                // 5. Show it.
3044
                frame.setVisible(true);
3045
        }
3046

    
3047
        public static String getInformation() {
3048
                PluginsManager pluginmgr = PluginsLocator.getManager();
3049
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3050

    
3051
                StringWriter writer = new StringWriter();
3052

    
3053
                Properties props = System.getProperties();
3054

    
3055
                // OS information
3056
                String osName = props.getProperty("os.name");
3057
                writer.write("OS\n");
3058
                writer.write("    name   : " + osName + "\n");
3059
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3060
                writer.write("    version: " + props.get("os.version") + "\n");
3061
                if (osName.startsWith("Linux")) {
3062
                        try {
3063
                                String[] command = { "lsb_release", "-a" };
3064
                                Process p = Runtime.getRuntime().exec(command);
3065
                                InputStream is = p.getInputStream();
3066
                                BufferedReader reader = new BufferedReader(
3067
                                                new InputStreamReader(is));
3068
                                String line;
3069
                                while ((line = reader.readLine()) != null) {
3070
                                        writer.write("    " + line + "\n");
3071
                                }
3072
                        } catch (Exception ex) {
3073
                                writer
3074
                                                .write("Can't get detailled os information (lsb_release -a).");
3075
                        }
3076
                }
3077

    
3078
                // JRE information
3079
                writer.write("JRE\n");
3080
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3081
                writer.write("    version: " + props.get("java.version") + "\n");
3082
                writer.write("    home   : " + props.get("java.home") + "\n");
3083

    
3084
                writer.write("HTTP Proxy\n");
3085
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3086
                                + "\n");
3087
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3088
                                + "\n");
3089
                writer.write("    http.proxyUserName : "
3090
                                + props.get("http.proxyUserName") + "\n");
3091
                writer.write("    http.proxyPassword : "
3092
                                + props.get("http.proxyPassword") + "\n");
3093

    
3094
                String skinName = "(unknow)";
3095
                try {
3096
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3097
                } catch (Throwable e) {
3098
                        // Ignore
3099
                }
3100
                writer.write("Application\n");
3101
                writer.write("    locale language         : "
3102
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3103
                writer.write("    application forlder     : "
3104
                                + pluginmgr.getApplicationFolder() + "\n");
3105
                writer.write("    install forlder         : "
3106
                                + pluginmgr.getInstallFolder() + "\n");
3107
                writer.write("    application home forlder: "
3108
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3109
                writer.write("    plugins forlder         : "
3110
                                + pluginmgr.getPluginsFolder() + "\n");
3111
                writer.write("    theme                   : "
3112
                                + Launcher.theme.getSource() + "\n");
3113
                // writer.write("    Skin                    : " + skinName + "\n");
3114

    
3115
                try {
3116
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3117
                                        .getPluginsFolder());
3118
                        writer.write("Installed packages\n");
3119
                        for (int i = 0; i < pkgs.length; i++) {
3120
                                writer.write("    ");
3121
                                writer.write(pkgs[i].toStringCompact());
3122
                                writer.write("\n");
3123
                        }
3124
                } catch (Throwable e) {
3125
                        writer.write("Can't get installed package information.");
3126
                }
3127
                return writer.toString();
3128
        }
3129

    
3130
        private void logger_info(String msg) {
3131
                String info[] = msg.split("\n");
3132
                for (int i = 0; i < info.length; i++) {
3133
                        logger.info(info[i]);
3134
                }
3135
        }
3136

    
3137
}