Statistics
| Revision:

svn-gvsig-desktop / tags / v2_0_0_Build_2050 / frameworks / _fwAndami / src / org / gvsig / andami / Launcher.java @ 38651

History | View | Annotate | Download (104 KB)

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

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

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

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

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

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

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

    
210
        protected static ArrayList<String> pluginsOrdered = new ArrayList<String>();
211
        protected static ArrayList<IExtension> extensions = new ArrayList<IExtension>();
212
        protected static String appHomeDir = null;
213
        // it seems castor uses this encoding
214
        protected static final String CASTORENCODING = "UTF8";
215

    
216
        protected static ListBaseException launcherrors = null;
217

    
218
        protected static Theme theme = null;
219

    
220
        private static final class ProxyAuth extends Authenticator {
221

    
222
                private PasswordAuthentication auth;
223

    
224
                private ProxyAuth(String user, String pass) {
225
                        auth = new PasswordAuthentication(user, pass.toCharArray());
226
                }
227

    
228
                protected PasswordAuthentication getPasswordAuthentication() {
229
                        return auth;
230
                }
231
        }
232

    
233
        private static Launcher launcherInstance;
234

    
235
        public static Launcher getInstance() {
236
                if( launcherInstance == null ) {
237
                        launcherInstance = new Launcher();
238
                }
239
                return launcherInstance;
240
        }
241
        
242
        public static void main(String[] args) throws Exception {
243
                Launcher launcher = getInstance();
244
                boolean install = false;
245
                for (int i = 0; i < args.length; i++) {
246
                        if (args[i].equalsIgnoreCase("--install")) {
247
                                install = true;
248
                        }
249
                }
250
                try {
251
                        if (install) {
252
                                launcher.doInstall(args);
253
                        } else {
254
                                launcher.doMain(args);
255
                        }
256
                } catch (Exception e) {
257
                        logger.error("excepci?n al arrancar", e);
258
                        System.exit(-1);
259
                }
260
        }
261

    
262
        protected void downloadExtensions(String extDir) {
263
                // do nothing
264
        }
265

    
266
        public static class LaunchException extends ListBaseException {
267

    
268
                private static final long serialVersionUID = 4541192746962684705L;
269

    
270
                public LaunchException() {
271
                        super("Errors in initialization of application.",
272
                                        "_errors_in_initialization_of_application",
273
                                        serialVersionUID);
274
                }
275

    
276
        }
277

    
278
        protected void addError(Throwable ex) {
279
                if (launcherrors == null) {
280
                        launcherrors = new LaunchException();
281
                }
282
                launcherrors.add(ex);
283
        }
284

    
285
        protected void addError(String msg, Throwable cause) {
286
                logger.error(msg, cause);
287
                this.addError(new RuntimeException(msg, cause));
288
        }
289

    
290
        protected void addError(String msg) {
291
                this.addError(msg, null);
292
        }
293

    
294
        public void doMain(String[] args) throws Exception {
295

    
296
                if (args.length < 1) {
297
                        System.err
298
                                        .println("Uso: Launcher appName plugins-directory [language=locale]");
299
                }
300

    
301
                initializeApp(args);
302

    
303
                // Solucionamos el problema de permisos que se produc?a con Java
304
                // Web Start con este c?digo.
305
                // System.setSecurityManager(null);
306
                Policy.setPolicy(new Policy() {
307

    
308
                        public PermissionCollection getPermissions(CodeSource codesource) {
309
                                Permissions perms = new Permissions();
310
                                perms.add(new AllPermission());
311
                                return (perms);
312
                        }
313

    
314
                        public void refresh() {
315
                        }
316
                });
317

    
318
                /*
319
        new ToolsLibrary().initialize();
320
        new ToolsSwingLibrary().initialize();
321
        new ToolsSwingDefaultImplLibrary().initialize();
322
        */
323
        
324
        new DefaultLibrariesInitializer().fullInitialize(true);
325

    
326
                try {
327
                        initIconThemes();
328
                } catch (Exception ex) {
329
                        this.addError("Can't initialize icon theme", ex);
330
                }
331
                // Registramos los iconos base
332
                try {
333
                        registerIcons();
334
                } catch (Exception ex) {
335
                        this.addError("Can't register icons", ex);
336
                }
337
                validate();
338

    
339
                // Obtener la personalizaci?n de la aplicaci?n.
340
                try {
341
                        logger.info("Initialize andami theme");
342
                        theme = getTheme(andamiConfig.getPluginsDirectory());
343
                } catch (Exception ex) {
344
                        this.addError("Can't get personalized theme for the application",
345
                                        ex);
346
                }
347

    
348
                // Mostrar la ventana de inicio
349
                Frame f = new Frame();
350
                splashWindow = new MultiSplashWindow(f, theme, 190);
351

    
352
                // 1. Ponemos los datos del proxy
353
                splashWindow.process(10, PluginServices.getText(Launcher.class,
354
                                "SplashWindow.configuring_proxy"));
355
                logger.info("Configute http proxy");
356
                configureProxy();
357

    
358
                // 2. TODO Buscar actualizaciones de los plugins
359
//                splashWindow.process(20, PluginServices.getText(Launcher.class,
360
//                                "SplashWindow.looking_for_updates"));
361
//                try {
362
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
363
//                } catch (Exception ex) {
364
//                        this.addError("Can't downloads plugins", ex);
365
//                }
366

    
367
                // 2.5. Initialize andami libraries
368
                splashWindow.process(25, PluginServices.getText(Launcher.class,
369
                                "SplashWindow.initialize_andami_libraries"));
370
                
371
                File defaultAddonsRepository = PluginsLocator.getManager()
372
                                .getPluginsFolder();
373
                InstallerManager installerManager = InstallerLocator
374
                                .getInstallerManager();
375
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
376
                installerManager
377
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
378
        
379
                logger.info("Dump system information");
380
                logger_info(getInformation());
381

    
382
                // 3. Se leen los config.xml de los plugins -----++++
383
                splashWindow.process(30, PluginServices.getText(Launcher.class,
384
                                "SplashWindow.reading_plugins_config.xml"));
385
                try {
386
                        logger.info("Load plugins information");
387
                        this.loadPlugins(andamiConfig.getPluginsDirectory());
388
                } catch (Exception ex) {
389
                        this.addError("Can't load plugins", ex);
390
                }
391

    
392
                // 4. Se configura el classloader del plugin
393
                splashWindow.process(40, PluginServices.getText(Launcher.class,
394
                                "SplashWindow.setting_up_class_loaders"));
395
                try {
396
                        logger.info("Configure plugins class loader");
397
                        this.pluginsClassLoaders();
398
                } catch (Exception ex) {
399
                        this.addError("Can't initialize plugin's classloaders  ", ex);
400
                }
401

    
402
                // 5. Initialize libraries
403
                splashWindow.process(50, PluginServices.getText(Launcher.class,
404
                                "SplashWindow.initialize_libraries"));
405
                initializeLibraries();
406

    
407
                // 6. Se carga un Skin si alguno ide los plugins trae informaci?n
408
                // para ello
409
                splashWindow.process(60, PluginServices.getText(Launcher.class,
410
                                "SplashWindow.looking_for_a_skin"));
411
                // skinPlugin( "com.iver.core.mdiManager.NewSkin");
412
                logger.info("Initialize skin");
413
                skinPlugin(null);
414

    
415
                // 7. Se configura la cola de eventos
416
                splashWindow.process(70, PluginServices.getText(Launcher.class,
417
                                "setting_up_event_queue"));
418
                EventQueue waitQueue = new AndamiEventQueue();
419
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
420

    
421
                // 8. Se configura la mensajer?a del plugin
422
                splashWindow.process(80, PluginServices.getText(Launcher.class,
423
                                "SplashWindow.starting_plugin_internationalization_system"));
424
                pluginsMessages();
425

    
426
                // 9. Se modifica el andami-config con los plugins nuevos
427
                splashWindow.process(90, PluginServices.getText(Launcher.class,
428
                                "SplashWindow.looking_for_a_skin"));
429
                updateAndamiConfig();
430

    
431
                frame = new MDIFrame();
432
                // 10. Se configura el nombre e icono de la aplicaci?n
433
                splashWindow.process(100, PluginServices.getText(Launcher.class,
434
                                "SplashWindow.setting_up_applications_name_and_icons"));
435
                frameIcon(theme);
436

    
437
                // 11. Se prepara el MainFrame para albergar las extensiones
438
                splashWindow.process(110, PluginServices.getText(Launcher.class,
439
                                "SplashWindow.preparing_workbench"));
440
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
441

    
442
                SwingUtilities.invokeAndWait(new Runnable() {
443

    
444
                        public void run() {
445
                                frame.init();
446
                        }
447
                });
448
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
449

    
450
                // 12. Leer el fichero de persistencia
451
                // info de los plugins
452
                // bookmarks de los plugins
453
                splashWindow.process(120, PluginServices.getText(Launcher.class,
454
                                "SplashWindow.loading_plugin_settings"));
455
                loadPluginsPersistence();
456

    
457
                // Se instalan los controles del skin
458
                // 13. Se inicializan todas las extensiones de todos los plugins
459
                splashWindow.process(130, PluginServices.getText(Launcher.class,
460
                                "SplashWindow.initializing_extensions"));
461
                SwingUtilities.invokeAndWait(new Runnable() {
462

    
463
                        public void run() {
464
                                initializeExtensions();
465
                        }
466
                });
467

    
468
                // 14. Se inicializan la extensi?n exclusiva
469
                splashWindow.process(140, PluginServices.getText(Launcher.class,
470
                                "SplashWindow.setting_up_master_extension"));
471
                SwingUtilities.invokeAndWait(new Runnable() {
472

    
473
                        public void run() {
474
                                initializeExclusiveUIExtension();
475
                        }
476
                });
477
                frame.setClassesExtensions(classesExtensions);
478

    
479
                // 15. Se instalan los controles de las extensiones de los plugins
480
                splashWindow.process(150, PluginServices.getText(Launcher.class,
481
                                "SplashWindow.installing_extensions_controls"));
482
                SwingUtilities.invokeAndWait(new Runnable() {
483

    
484
                        public void run() {
485
                                installPluginsControls();
486

    
487
                        }
488
                });
489

    
490
                // 16. Se instalan los menus de las extensiones de los plugins
491
                splashWindow.process(160, PluginServices.getText(Launcher.class,
492
                                "SplashWindow.installing_extensions_menus"));
493
                SwingUtilities.invokeAndWait(new Runnable() {
494

    
495
                        public void run() {
496
                                installPluginsMenus();
497

    
498
                        }
499
                });
500

    
501
                // 17. Se instalan las etiquetas de las extensiones de los plugins
502
                splashWindow.process(170, PluginServices.getText(Launcher.class,
503
                                "SplashWindow.installing_extensions_labels"));
504
                SwingUtilities.invokeAndWait(new Runnable() {
505

    
506
                        public void run() {
507
                                installPluginsLabels();
508

    
509
                        }
510
                });
511

    
512
                // 18. Se instalan los bookmarks de los plugins
513

    
514
                // 19. Se muestra el frame principal
515
                splashWindow.process(180, PluginServices.getText(Launcher.class,
516
                                "creating_main_window"));
517
                frame.setVisible(true);
518

    
519
                /* 
520
                 * Initialize installer local repository folders 
521
                 */
522
                initializeLocalAddOnRepositoryFolders();
523

    
524
                // 19. Se ejecuta el postInitialize
525
                splashWindow.process(190, PluginServices.getText(Launcher.class,
526
                                "SplashWindow.post_initializing_extensions"));
527
                SwingUtilities.invokeAndWait(new Runnable() {
528

    
529
                        public void run() {
530
                                postInitializeExtensions();
531

    
532
                        }
533
                });
534

    
535
                // Definimos un KeyEventDispatcher global para que las extensiones
536
                // puedan registrar sus "teclas r?pidas".
537
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
538
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
539

    
540
                SwingUtilities.invokeAndWait(new Runnable() {
541

    
542
                        public void run() {
543
                                frame.enableControls();
544
                        }
545
                });
546

    
547
                createDefaultIconTheme();
548

    
549
                frame.message(Messages.getString("StatusBar.Aplicacion_iniciada"), JOptionPane.INFORMATION_MESSAGE);
550

    
551
                splashWindow.close();
552
                if (launcherrors != null) {
553
                        NotificationManager.addError(launcherrors);
554
                }
555

    
556
                
557
                org.apache.log4j.Logger.getRootLogger().addAppender(
558
                                new NotificationAppender());
559

    
560
        }
561

    
562
        private void initializeLocalAddOnRepositoryFolders() {
563
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
564

    
565
                File defaultAddonsRepository = PluginsLocator.getManager().getPluginsFolder();
566

    
567
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
568
                installerManager.setDefaultLocalAddonRepository(defaultAddonsRepository);
569
                
570
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
571
                FolderSet fset = iconManager.getRepository();
572
                Iterator<FolderSet.FolderEntry> it = fset.iterator();
573
                while( it.hasNext() ) {
574
                        FolderEntry entry = it.next();
575
                        installerManager.addLocalAddonRepository(entry.getFolder());
576
                }
577
        }
578
        
579
        private void createDefaultIconTheme() {
580
                PluginsManager pluginsManager = PluginsLocator.getManager();
581
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
582
                
583
                File f = new File(pluginsManager.getApplicationHomeFolder(),"icon-theme");
584
                if( !f.exists() ) {
585
                        f.mkdir();
586
                }
587
                IconTheme theme = iconManager.getDefault();
588
                File f2 = new File(f,theme.getID()) ;
589
                if( !f2.exists() ) {
590
                        logger.info("Creating default icon theme in "+f.getAbsolutePath());
591
                        theme.export(f);
592
                }
593
        }
594
        
595
        /**
596
     * 
597
     */
598
        private void initializeLibraries() {
599
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
600
                                pluginsOrdered.size() + 1);
601
                classLoaders.add(getClass().getClassLoader());
602
                Iterator<String> iter = pluginsOrdered.iterator();
603

    
604
                logger.debug("Initializing plugins libraries: ");
605
                while (iter.hasNext()) {
606
                        String pName = (String) iter.next();
607
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
608
                        classLoaders.add(ps.getClassLoader());
609
                }
610

    
611
                // Create the libraries initializer and
612
                // initialize the plugin libraries
613
                new DefaultLibrariesInitializer(classLoaders
614
                                .toArray(new ClassLoader[classLoaders.size()]))
615
                                .fullInitialize(true);
616

    
617
                // Remove them all, we don't need them anymore
618
                classLoaders.clear();
619
                classLoaders = null;
620
        }
621

    
622
        /**
623
         * @param args
624
         * @throws IOException
625
         * @throws ConfigurationException
626
         */
627
        private void initializeApp(String[] args) throws IOException,
628
                        ConfigurationException {
629
                if (!validJVM()) {
630
                        System.exit(-1);
631
                }
632

    
633
                // Clean temporal files
634
                Utilities.cleanUpTempFiles();
635

    
636
                appName = args[0];
637

    
638
                getOrCreateConfigFolder();
639

    
640
                configureLogging(appName);
641

    
642
                loadAndamiConfig(args[1]);
643

    
644
                // Hacemos visibles los argumentos como una propiedad est?tica
645
                // de plugin services para quien lo quiera usar (por ejemplo, para
646
                // cargar un proyecto por l?nea de comandos)
647
                PluginServices.setArguments(args);
648

    
649
                configureLocales(args);
650

    
651
                logger.info("Load and initialize andami and plugins libraries");
652
                // LibrariesInitializer libsInitializer =
653
                // new DefaultLibrariesInitializer();
654
                // libsInitializer.initialize(true);
655
                // libsInitializer.postInitialize(true);
656

    
657
                logger.info("Configure LookAndFeel");
658
                configureLookAndFeel();
659
        }
660

    
661
        /**
662
     * 
663
     */
664
        private void configureLookAndFeel() {
665
                // Se pone el lookAndFeel
666
                try {
667
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
668
                        if (lookAndFeel == null) {
669
                                lookAndFeel = getDefaultLookAndFeel();
670
                        }
671
                        UIManager.setLookAndFeel(lookAndFeel);
672
                } catch (Exception e) {
673
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
674
                }
675
                FontUtils.initFonts();
676
        }
677

    
678
        /**
679
         * @param args
680
         * @throws ConfigurationException
681
         */
682
        private void loadAndamiConfig(String pluginFolder)
683
                        throws ConfigurationException {
684
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
685
                // locale
686
                // Buscar actualizaci?nes al comenzar
687
                // Andami
688
                // Plugins
689
                // Directorio de las extensiones
690
                andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
691
                andamiConfigFromXML(andamiConfigPath);
692
                andamiConfig.setPluginsDirectory(pluginFolder);
693
        }
694

    
695
        /**
696
     * 
697
     */
698
        private void getOrCreateConfigFolder() {
699
                // Create application configuration folder
700
                appHomeDir = System.getProperty(appName + ".home");
701
                if (appHomeDir == null) {
702
                        appHomeDir = System.getProperty("user.home");
703
                }
704

    
705
                appHomeDir += File.separator + appName;
706
                File parent = new File(appHomeDir);
707
                parent.mkdirs();
708
        }
709

    
710
        /**
711
         * @param args
712
         * @throws IOException
713
         */
714
        private void configureLogging(String appName) throws IOException {
715
                // Configurar el log4j
716
                Launcher.class.getClassLoader().getResource(".");
717
                PropertyConfigurator.configure("log4j.properties");
718

    
719
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
720
                RollingFileAppender fa = new RollingFileAppender(l, appHomeDir
721
                                + File.separator + appName + ".log", false);
722
                fa.setMaxFileSize("512KB");
723
                fa.setMaxBackupIndex(3);
724
                org.apache.log4j.Logger.getRootLogger().addAppender(fa);
725
        }
726

    
727
        private class NotificationAppender extends AppenderSkeleton {
728

    
729
                @Override
730
                protected void append(LoggingEvent event) {
731
                        if (event.getLevel() == org.apache.log4j.Level.ERROR
732
                                        || event.getLevel() == org.apache.log4j.Level.FATAL) {
733
                                NotificationManager.dispatchError(event.getRenderedMessage(),
734
                                                null);
735
                                return;
736
                        }
737
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
738
                        // NotificationManager.dispatchWarning(event.getRenderedMessage(),
739
                        // null);
740
                        // return;
741
                        // }
742
                }
743

    
744
                @Override
745
                public void close() {
746
                        // TODO Auto-generated method stub
747

    
748
                }
749

    
750
                @Override
751
                public boolean requiresLayout() {
752
                        // TODO Auto-generated method stub
753
                        return false;
754
                }
755

    
756
        }
757

    
758
        /**
759
         * Return the directory applicaction is installed.
760
         */
761
        public static String getApplicationDirectory() {
762
                return getApplicationFolder().getAbsolutePath();
763
        }
764
        
765
    public static File getApplicationFolder() {
766
        // TODO: check if there is a better way to handle this
767
        return new File(System.getProperty("user.dir"));
768
    }
769

    
770
        private void registerIcons() {
771
                IconTheme theme = PluginServices.getIconTheme();
772
                ClassLoader loader = Launcher.class.getClassLoader();        
773
                
774
                String[][] icons = {
775
                                // MultiSplashWindow
776
                                { "main", "splash-default" },
777
                                // NewStatusBar
778
                                { "main", "statusbar-info" },
779
                                { "main", "statusbar-warning" },
780
                                { "main", "statusbar-error" }
781
                };
782
                for( int i=0; i<icons.length; i++) {
783
                        try {
784
                                IconThemeHelper.registerIcon(icons[i][0], icons[i][1], Launcher.class);
785
                        } catch(Exception e) {
786
                                logger.info("Can't register icon '"+icons[i][0]+"' ("+icons[i][1]+").");
787
                        }
788
                }                
789
                theme.setDefaultIcon(loader.getResource("images/main/default-icon.png" ));
790
        }
791

    
792
        /**
793
         * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de la
794
         * aplicaci?n.
795
         * 
796
         * @return Theme
797
         */
798
        private Theme getTheme(String pluginsDirectory) {
799
                File themeFile = null;
800
                Theme theme = new Theme();
801

    
802
                // Try to get theme from args
803
                String name = PluginServices.getArgumentByName("andamiTheme");
804
                if (name != null) {
805
                        themeFile = new File(name);
806
                        logger.info("search andami-theme in {}", themeFile
807
                                        .getAbsolutePath());
808
                        if (themeFile.exists()) {
809
                                theme.readTheme(themeFile);
810
                                logger.info("andami-theme found in {}", themeFile
811
                                                .getAbsolutePath());
812
                                return theme;
813
                        }
814
                }
815

    
816
                // Try to get theme from a plugin
817
                File pluginsDir = new File(pluginsDirectory);
818
                if (!pluginsDir.isAbsolute()) {
819
                        pluginsDir = new File(System.getProperty("user.dir"),
820
                                        pluginsDirectory);
821
                }
822
                if (pluginsDir.exists()) {
823
                        logger.info("search andami-theme in plugins folder.");
824
                        File[] pluginDirs = pluginsDir.listFiles();
825
                        if (pluginDirs.length > 0) {
826
                                for (int i = 0; i < pluginDirs.length; i++) {
827
                                        File pluginThemeFile = new File(pluginDirs[i], "theme"
828
                                                        + File.separator + "andami-theme.xml");
829
                                        if (pluginThemeFile.exists()) {
830
                                                themeFile = pluginThemeFile;
831
                                                // This if is a hack to allow more themes than the
832
                                                // one available in org.gvsig.app. Remove this
833
                                                // when a the theme format is changed to allow for
834
                                                // priorities
835
                                                if (!"org.gvsig.app".equals(pluginDirs[i].getName())) {
836
                                                        break;
837
                                                }
838
                                        }
839
                                }
840
                        }
841
                }
842

    
843
                // The theme file will be the one into a plugin or by default the one
844
                // in the org.gvsig.app plugin
845
                if (themeFile != null && themeFile.exists()) {
846
                        theme.readTheme(themeFile);
847
                        logger.info("andami-theme found in plugin {}", themeFile
848
                                        .getAbsolutePath());
849
                        return theme;
850
                }
851

    
852
                // Try to get theme from dir gvSIG in user home
853
                themeFile = new File(getAppHomeDir(), "theme" + File.separator
854
                                + "andami-theme.xml");
855
                logger.info("search andami-theme in user's home {}", themeFile
856
                                .getAbsolutePath());
857
                if (themeFile.exists()) {
858
                        theme.readTheme(themeFile);
859
                        logger.info("andami-theme found in user's home {}", themeFile
860
                                        .getAbsolutePath());
861
                        return theme;
862
                }
863

    
864
                // Try to get theme from the instalation dir of gvSIG.
865
                themeFile = new File(getApplicationDirectory(), "theme"
866
                                + File.separator + "andami-theme.xml");
867
                logger.info("search andami-theme in installation folder {}", themeFile
868
                                .getAbsolutePath());
869
                if (themeFile.exists()) {
870
                        theme.readTheme(themeFile);
871
                        logger.info("andami-theme found in instalation folder {}",
872
                                        themeFile.getAbsolutePath());
873
                        return theme;
874
                }
875
                logger.info("Apply default andami-theme.");
876
                return theme;
877
        }
878

    
879
        /**
880
         * Establece los datos que ten?amos guardados respecto de la configuraci?n
881
         * del proxy.
882
         */
883
        private void configureProxy() {
884
                String host = prefs.get("firewall.http.host", "");
885
                String port = prefs.get("firewall.http.port", "");
886

    
887
                System.getProperties().put("http.proxyHost", host);
888
                System.getProperties().put("http.proxyPort", port);
889

    
890
                // Ponemos el usuario y clave del proxy, si existe
891
                String proxyUser = prefs.get("firewall.http.user", null);
892
                String proxyPassword = prefs.get("firewall.http.password", null);
893
                if (proxyUser != null) {
894
                        System.getProperties().put("http.proxyUserName", proxyUser);
895
                        System.getProperties().put("http.proxyPassword", proxyPassword);
896

    
897
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
898
                } else {
899
                        Authenticator.setDefault(new ProxyAuth("", ""));
900
                }
901
        }
902

    
903
        /**
904
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal
905
         * de Andami. TODO Pendiente de ver como se asigna un pluginServices para el
906
         * launcher.
907
         * 
908
         * @author LWS
909
         */
910
        private void restoreMDIStatus(XMLEntity xml) {
911
                if (xml == null) {
912
                        xml = new XMLEntity();
913
                }
914
                // restore frame size
915
                Dimension sz = new Dimension(700, 580);
916
                if (xml.contains("MDIFrameSize")) {
917
                        int[] wh = xml.getIntArrayProperty("MDIFrameSize");
918
                        sz = new Dimension(wh[0], wh[1]);
919
                }
920
                frame.setSize(sz);
921
                // restore frame location
922
                Point pos = new Point(10, 10);
923
                if (xml.contains("MDIFramePos")) {
924
                        int[] xy = xml.getIntArrayProperty("MDIFramePos");
925
                        pos = new Point(xy[0], xy[1]);
926
                }
927
                frame.setLocation(pos);
928

    
929
                // restore frame status (Maximized, minimized, etc);
930
                int state = java.awt.Frame.MAXIMIZED_BOTH;
931
                if (xml.contains("MDIFrameState")) {
932
                        state = xml.getIntProperty("MDIFrameState");
933
                }
934
                frame.setExtendedState(state);
935
        }
936

    
937
        private XMLEntity saveMDIStatus() {
938
                XMLEntity xml = new XMLEntity();
939
                // save frame size
940
                int[] wh = new int[2];
941
                wh[0] = frame.getWidth();
942
                wh[1] = frame.getHeight();
943
                xml.putProperty("MDIFrameSize", wh);
944
                // save frame location
945
                int[] xy = new int[2];
946
                xy[0] = frame.getX();
947
                xy[1] = frame.getY();
948
                xml.putProperty("MDIFramePos", xy);
949
                // save frame status
950
                xml.putProperty("MDIFrameState", frame.getExtendedState());
951
                return xml;
952
        }
953

    
954
        private boolean validJVM() {
955
                char thirdCharacter = System.getProperty("java.version").charAt(2);
956
                if (thirdCharacter < '4') {
957
                        return false;
958
                } else {
959
                        return true;
960
                }
961
        }
962

    
963
        private void loadPluginsPersistence() throws ConfigurationException {
964
                XMLEntity entity = persistenceFromXML();
965

    
966
                for (int i = 0; i < entity.getChildrenCount(); i++) {
967
                        XMLEntity plugin = entity.getChild(i);
968
                        String pName = plugin
969
                                        .getStringProperty("com.iver.andami.pluginName");
970

    
971
                        if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
972
                                pName = "org.gvsig.app";
973
                        }
974
                        if (pluginsServices.get(pName) != null) {
975
                                ((PluginServices) pluginsServices.get(pName))
976
                                                .setPersistentXML(plugin);
977
                        } else {
978
                                if (pName.startsWith("Andami.Launcher")) {
979
                                        restoreMDIStatus(plugin);
980
                                }
981
                        }
982
                }
983
        }
984

    
985
        /**
986
         * Salva la persistencia de los plugins.
987
         * 
988
         * @author LWS
989
         */
990
        private void savePluginPersistence() {
991
                Iterator<String> i = pluginsConfig.keySet().iterator();
992

    
993
                XMLEntity entity = new XMLEntity();
994

    
995
                while (i.hasNext()) {
996
                        String pName = i.next();
997
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
998
                        XMLEntity ent = ps.getPersistentXML();
999

    
1000
                        if (ent != null) {
1001
                                ent.putProperty("com.iver.andami.pluginName", pName);
1002
                                entity.addChild(ent);
1003
                        }
1004
                }
1005
                XMLEntity ent = saveMDIStatus();
1006
                if (ent != null) {
1007
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
1008
                        entity.addChild(ent);
1009
                }
1010
                try {
1011
                        persistenceToXML(entity);
1012
                } catch (ConfigurationException e1) {
1013
                        this
1014
                                        .addError(
1015
                                                        Messages
1016
                                                                        .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1017
                                                        e1);
1018
                }
1019
        }
1020

    
1021
        private void installPluginsLabels() {
1022
                Iterator<String> i = pluginsConfig.keySet().iterator();
1023

    
1024
                while (i.hasNext()) {
1025
                        String name = i.next();
1026
                        PluginConfig pc = pluginsConfig.get(name);
1027
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1028

    
1029
                        LabelSet[] ls = pc.getLabelSet();
1030

    
1031
                        for (int j = 0; j < ls.length; j++) {
1032
                                PluginClassLoader loader = ps.getClassLoader();
1033

    
1034
                                try {
1035
                                        Class clase = loader.loadClass(ls[j].getClassName());
1036
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
1037
                                } catch (ClassNotFoundException e) {
1038
                                        this.addError(
1039
                                                        Messages.getString("Launcher.labelset_class"), e);
1040
                                }
1041
                        }
1042
                }
1043
        }
1044

    
1045
        private String configureSkin(XMLEntity xml, String defaultSkin) {
1046
                if (defaultSkin == null) {
1047
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
1048
                                if (xml.getChild(i).contains("Skin-Selected")) {
1049
                                        String className = xml.getChild(i).getStringProperty(
1050
                                                        "Skin-Selected");
1051
                                        return className;
1052
                                }
1053
                        }
1054
                }
1055
                // return "com.iver.core.mdiManager.NewSkin";
1056
                return defaultSkin;
1057
        }
1058

    
1059
        private void fixSkin(SkinExtension skinExtension,
1060
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1061
                // now insert the skin selected.
1062
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1063
                // MDIManagerFactory.setSkinExtension(se,
1064
                // ps.getClassLoader());
1065

    
1066
                Class<? extends IExtension> skinClass;
1067

    
1068
                try {
1069
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1070
                                        .loadClass(skinExtension.getClassName());
1071

    
1072
                        IExtension skinInstance = skinClass.newInstance();
1073
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1074
                                        skinInstance, ExtensionDecorator.INACTIVE);
1075
                        classesExtensions.put(skinClass, newExtensionDecorator);
1076
                } catch (ClassNotFoundException e) {
1077
                        logger.error(Messages
1078
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1079
                                        e);
1080
                        throw new MDIManagerLoadException(e);
1081
                } catch (InstantiationException e) {
1082
                        logger
1083
                                        .error(
1084
                                                        Messages
1085
                                                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1086
                                                        e);
1087
                        throw new MDIManagerLoadException(e);
1088
                } catch (IllegalAccessException e) {
1089
                        logger
1090
                                        .error(
1091
                                                        Messages
1092
                                                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1093
                                                        e);
1094
                        throw new MDIManagerLoadException(e);
1095
                }
1096

    
1097
        }
1098

    
1099
        /**
1100
         * DOCUMENT ME!
1101
         * 
1102
         * @throws MDIManagerLoadException
1103
         */
1104
        private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1105
                XMLEntity entity = null;
1106
                try {
1107
                        entity = persistenceFromXML();
1108
                } catch (ConfigurationException e1) {
1109
                        // TODO Auto-generated catch block
1110
                        e1.printStackTrace();
1111
                }
1112
                Iterator<String> i = pluginsConfig.keySet().iterator();
1113

    
1114
                SkinExtension skinExtension = null;
1115
                PluginClassLoader pluginClassLoader = null;
1116
                List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1117
                while (i.hasNext()) {
1118
                        String name = i.next();
1119
                        PluginConfig pc = pluginsConfig.get(name);
1120
                        PluginServices ps = pluginsServices.get(name);
1121

    
1122
                        if (pc.getExtensions().getSkinExtension() != null) {
1123
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1124
                                // logger.warn(Messages.getString(
1125
                                // "Launcher.Dos_skin_extension"));
1126
                                // }
1127

    
1128
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1129
                                for (int numExten = 0; numExten < se.length; numExten++) {
1130
                                        skinExtensions.add(se[numExten]);
1131
                                }
1132
                                for (int j = 0; j < se.length; j++) {
1133
                                        String configuredSkin = this.configureSkin(entity,
1134
                                                        defaultSkin);
1135
                                        if ((configuredSkin != null)
1136
                                                        && configuredSkin.equals(se[j].getClassName())) {
1137
                                                skinExtension = se[j];
1138
                                                pluginClassLoader = ps.getClassLoader();
1139
                                        }
1140
                                }
1141
                        }
1142
                }
1143

    
1144
                if ((skinExtension != null) && (pluginClassLoader != null)) {
1145
                        // configured skin was found
1146
                        fixSkin(skinExtension, pluginClassLoader);
1147
                } else {
1148
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1149
                                // try first NewSkin (from CorePlugin)
1150
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
1151
                        } else if (skinExtensions.size() > 0) {
1152
                                // try to load the first skin found
1153
                                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1154
                                skinPlugin((String) se.getClassName());
1155
                        } else {
1156
                                throw new MDIManagerLoadException("No Skin-Extension installed");
1157
                        }
1158
                }
1159

    
1160
        }
1161

    
1162
        private static void frameIcon(Theme theme) {
1163
                Iterator<String> i = pluginsConfig.keySet().iterator();
1164

    
1165
                while (i.hasNext()) {
1166
                        String pName = i.next();
1167
                        PluginConfig pc = pluginsConfig.get(pName);
1168
                        if (pc.getIcon() != null) {
1169
                                if (theme.getIcon() != null) {
1170
                                        frame.setIconImage(theme.getIcon().getImage());
1171
                                } else {
1172

    
1173
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1174
                                                        pc.getIcon().getSrc());
1175
                                        frame.setIconImage(icon.getImage());
1176

    
1177
                                }
1178
                                if (theme.getName() != null) {
1179
                                        frame.setTitlePrefix(theme.getName());
1180
                                } else {
1181
                                        frame.setTitlePrefix(pc.getIcon().getText());
1182
                                }
1183
                                if (theme.getBackgroundImage() != null) {
1184

    
1185
                                        PluginServices.getMDIManager().setBackgroundImage(
1186
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1187
                                }
1188
                        }
1189
                }
1190
        }
1191

    
1192
        private void initializeExtensions() {
1193

    
1194
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1195
                                pluginsOrdered.size());
1196
                classLoaders.add(getClass().getClassLoader());
1197
                Iterator<String> iter = pluginsOrdered.iterator();
1198

    
1199
                // logger.debug("Initializing plugins libraries: ");
1200
                // while (iter.hasNext()) {
1201
                // String pName = (String) iter.next();
1202
                // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1203
                // classLoaders.add(ps.getClassLoader());
1204
                // }
1205
                //
1206
                // // Create the libraries initializer and
1207
                // // initialize the plugin libraries
1208
                // new DefaultLibrariesInitializer(
1209
                // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1210
                // .fullInitialize();
1211
                //
1212
                // // Remove them all, we don't need them anymore
1213
                // classLoaders.clear();
1214
                // classLoaders = null;
1215

    
1216
                logger.info("Initializing plugins: ");
1217
                // iter = pluginsOrdered.iterator();
1218
                while (iter.hasNext()) {
1219
                        String pName = (String) iter.next();
1220
                        logger.info("Initializing plugin " + pName);
1221
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1222
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1223

    
1224
                        Extension[] exts = pc.getExtensions().getExtension();
1225

    
1226
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1227
                                        new ExtensionComparator());
1228

    
1229
                        for (int j = 0; j < exts.length; j++) {
1230
                                if (!exts[j].getActive()) {
1231
                                        continue;
1232
                                }
1233

    
1234
                                if (orderedExtensions.contains(exts[j])) {
1235
                                        logger.warn("Two extensions with the same priority ("
1236
                                                        + exts[j].getClassName() + ")");
1237
                                }
1238

    
1239
                                orderedExtensions.add(exts[j]);
1240
                        }
1241

    
1242
                        Iterator<Extension> e = orderedExtensions.iterator();
1243

    
1244
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1245
                        while (e.hasNext()) {
1246
                                Extension extension = e.next();
1247
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1248

    
1249
                                try {
1250
                                        logger.info("Initializing " + extension.getClassName()
1251
                                                        + "...");
1252
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1253
                                                        .getClassLoader().loadClass(
1254
                                                                        extension.getClassName());
1255
                                        extensionInstance = extensionClass.newInstance();
1256

    
1257
                                        // CON DECORATOR
1258
                                        // ANTES: classesExtensions.put(extensionClass,
1259
                                        // extensionInstance);
1260
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1261
                                        // instancia para
1262
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por
1263
                                        // ejemplo)
1264
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos
1265
                                        // como par?metro
1266
                                        // la extensi?n original que acabamos de crear
1267
                                        // 0-> Inactivo, controla la extension
1268
                                        // 1-> Siempre visible
1269
                                        // 2-> Invisible
1270
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1271
                                                        extensionInstance, ExtensionDecorator.INACTIVE);
1272
                                        classesExtensions
1273
                                                        .put(extensionClass, newExtensionDecorator);
1274

    
1275
                                        extensionInstance.initialize();
1276
                                        extensions.add(extensionInstance);
1277

    
1278
                                } catch (NoClassDefFoundError e1) {
1279
                                        this.addError("Can't find class extension ("
1280
                                                        + extension.getClassName() + ")", e1);
1281
                                } catch (Throwable e1) {
1282
                                        this.addError("Can't initialize extension '"
1283
                                                        + extension.getClassName() + "'.", e1);
1284
                                }
1285
                        }
1286
                }
1287
        }
1288

    
1289
        private void postInitializeExtensions() {
1290
                logger.info("PostInitializing extensions: ");
1291

    
1292
                for (int i = 0; i < extensions.size(); i++) {
1293
                        org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1294
                                        .get(i);
1295
                        logger.info("PostInitializing "
1296
                                        + extensionInstance.getClass().getName() + "...");
1297
                        try {
1298
                                extensionInstance.postInitialize();
1299
                        } catch (Throwable ex) {
1300
                                this.addError("postInitialize of extension '"
1301
                                                + extensionInstance.getClass().getName() + "' failed",
1302
                                                ex);
1303
                        }
1304
                }
1305
        }
1306

    
1307
        private void registerActionOfExtensions(ActionInfoManager actionManager,
1308
                        Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1309
                ActionInfo actionInfo;
1310
                while (extensiones.hasMoreElements()) {
1311
                        SkinExtensionType extension = extensiones.nextElement();
1312
                        Class<? extends IExtension> classExtension;
1313
                        try {
1314
                                classExtension = (Class<? extends IExtension>) loader
1315
                                                .loadClass(extension.getClassName());
1316

    
1317
                                Enumeration<Action> actions = extension.enumerateAction();
1318
                                while (actions.hasMoreElements()) {
1319
                                        Action action = actions.nextElement();
1320
                                        if (action.getName() == null) {
1321
                                                logger.info("invalid action name (null) in "+ extension.getClassName()+" of "+ loader.toString());
1322
                                        } else {
1323
                                                actionInfo = actionManager.createAction(
1324
                                                                classExtension, action.getName(),
1325
                                                                action.getLabel(), action.getActionCommand(),
1326
                                                                action.getIcon(), null, action.getPosition(),
1327
                                                                action.getTooltip());
1328
                                                actionManager.registerAction(actionInfo);
1329
                                                if( action.getPosition() < 100000000 ) {
1330
                                                        logger.info("Invalid position in action ("+ actionInfo.toString()+ ").");
1331
                                                        action.setPosition( action.getPosition() + 1000000000);
1332
                                                }
1333
                                        }
1334
                                }
1335

    
1336
                                Enumeration<Menu> menus = extension.enumerateMenu();
1337
                                while (menus.hasMoreElements()) {
1338
                                        Menu menu = menus.nextElement();
1339
                                        if (!menu.getIs_separator() ) {
1340
                                                actionInfo = actionManager.createAction(
1341
                                                        classExtension, menu.getName(), menu.getText(),
1342
                                                        menu.getActionCommand(), menu.getIcon(),
1343
                                                        menu.getKey(), menu.getPosition(),
1344
                                                        menu.getTooltip());
1345
                                                actionInfo = actionManager.registerAction(actionInfo);
1346
                                                if (actionInfo != null) {
1347
                                                        menu.setActionCommand(actionInfo.getCommand());
1348
                                                        menu.setTooltip(actionInfo.getTooltip());
1349
                                                        menu.setIcon(actionInfo.getIconName());
1350
                                                        menu.setPosition(actionInfo.getPosition());
1351
                                                        menu.setKey(actionInfo.getAccelerator());
1352
                                                        menu.setName(actionInfo.getName());
1353
                                                }
1354
                                        } 
1355
                                        if( menu.getPosition() < 100000000 ) {
1356
                                                logger.info("Invalid position in menu ("+ menu.getText() + ").");
1357
                                                menu.setPosition( menu.getPosition() + 1000000000);
1358
                                        }
1359

    
1360
                                }
1361
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1362
                                while (toolBars.hasMoreElements()) {
1363
                                        ToolBar toolBar = toolBars.nextElement();
1364

    
1365
                                        Enumeration<ActionTool> actionTools = toolBar
1366
                                                        .enumerateActionTool();
1367
                                        while (actionTools.hasMoreElements()) {
1368
                                                ActionTool actionTool = actionTools.nextElement();
1369
                                                actionInfo = actionManager.createAction(
1370
                                                                classExtension, actionTool.getName(),
1371
                                                                actionTool.getText(),
1372
                                                                actionTool.getActionCommand(),
1373
                                                                actionTool.getIcon(),
1374
                                                                null,
1375
                                                                actionTool.getPosition(),
1376
                                                                actionTool.getTooltip());
1377
                                                actionInfo = actionManager.registerAction(actionInfo);
1378
                                                if (actionInfo != null) {
1379
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1380
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1381
                                                        actionTool.setIcon(actionInfo.getIconName());
1382
                                                        actionTool.setPosition(actionInfo.getPosition());
1383
                                                        actionTool.setName(actionInfo.getName());
1384
                                                }
1385
                                        }
1386

    
1387
                                        Enumeration<SelectableTool> selectableTool = toolBar
1388
                                                        .enumerateSelectableTool();
1389
                                        while (selectableTool.hasMoreElements()) {
1390
                                                SelectableTool actionTool = selectableTool
1391
                                                                .nextElement();
1392
                                                actionInfo = actionManager.createAction(
1393
                                                                classExtension, actionTool.getName(),
1394
                                                                actionTool.getText(),
1395
                                                                actionTool.getActionCommand(),
1396
                                                                actionTool.getIcon(),
1397
                                                                actionTool.getEnableText(),
1398
                                                                actionTool.getPosition(),
1399
                                                                actionTool.getTooltip());
1400
                                                actionInfo = actionManager.registerAction(actionInfo);
1401
                                                if (actionInfo != null) {
1402
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1403
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1404
                                                        actionTool.setIcon(actionInfo.getIconName());
1405
                                                        actionTool.setPosition(actionInfo.getPosition());
1406
                                                        actionTool.setName(actionInfo.getName());
1407
                                                }
1408
                                        }
1409
                                }
1410
                        } catch (ClassNotFoundException e) {
1411
                                logger.warn(
1412
                                                "Can't register actions of extension '"
1413
                                                                + extension.getClassName() + "'", e);
1414
                        }
1415
                }
1416
        }
1417
        
1418
        @SuppressWarnings("unchecked")
1419
        private void registerActions() {
1420
                logger.info("registerActions");
1421

    
1422
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1423
                Iterator<String> it = pluginsConfig.keySet().iterator();
1424

    
1425
                while (it.hasNext()) {
1426
                        String pluginName = it.next();
1427
                        PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1428
                        PluginServices pluginService = pluginsServices.get(pluginName);
1429
                        PluginClassLoader loader =  pluginService.getClassLoader();
1430

    
1431
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1432

    
1433
                        Extensions extensionConfig = pluginConfig.getExtensions();
1434
                        
1435
                        
1436
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1437
                        registerActionOfExtensions(actionManager, extensiones, loader);
1438

    
1439
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1440
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1441

    
1442
                        PopupMenus pluginPopupMenus = pluginConfig.getPopupMenus();
1443
                        if (pluginPopupMenus != null) {
1444
                                PopupMenu[] menus1 = pluginPopupMenus.getPopupMenu();
1445
                                for (int j = 0; j < menus1.length; j++) {
1446
                                        PopupMenu popupMenu = menus1[j];
1447
                                        Enumeration<Menu> menus2 = popupMenu.enumerateMenu();
1448
                                        while (menus2.hasMoreElements()) {
1449
                                                Menu menu = menus2.nextElement();
1450
                                                if (!menu.getIs_separator() ) {
1451
                                                        if( menu.getName() == null) {   
1452
                                                                logger.info("Null name for popmenu '"+menu.getText()+"' in plugin "+ pluginService.getPluginName() );
1453
                                                        } else {
1454
                                                                ActionInfo actionInfo = actionManager.getAction(menu.getName());
1455
                                                                if( actionInfo!=null ) {
1456
                                                                        menu.setActionCommand(actionInfo.getCommand());
1457
                                                                        menu.setTooltip(actionInfo.getTooltip());
1458
                                                                        menu.setIcon(actionInfo.getIconName());
1459
                                                                        menu.setPosition(actionInfo.getPosition());
1460
                                                                        menu.setText( actionInfo.getLabel());
1461
                                                                        menu.setKey(actionInfo.getAccelerator());
1462
                                                                }
1463
                                                        }
1464
                                                }
1465
                                        }
1466
                                }
1467
                        }
1468
                        
1469

    
1470
                }
1471
        }
1472
        
1473

    
1474
        private TreeSet<SortableMenu> getOrderedMenus() { 
1475

    
1476
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1477
                                new MenuComparator());
1478

    
1479
                Iterator<String> i = pluginsConfig.keySet().iterator();
1480

    
1481
                while (i.hasNext()) {
1482
                        String pName = i.next();
1483
                        try {
1484
                                PluginServices ps = pluginsServices.get(pName);
1485
                                PluginConfig pc = pluginsConfig.get(pName);
1486

    
1487
                                Extension[] exts = pc.getExtensions().getExtension();
1488

    
1489
                                for (int j = 0; j < exts.length; j++) {
1490
                                        if (!exts[j].getActive()) {
1491
                                                continue;
1492
                                        }
1493

    
1494
                                        Menu[] menus = exts[j].getMenu();
1495

    
1496
                                        for (int k = 0; k < menus.length; k++) {
1497
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1498
                                                                exts[j], menus[k]);
1499

    
1500
                                                if (orderedMenus.contains(sm)) {
1501
                                                        this
1502
                                                                        .addError(Messages
1503
                                                                                        .getString("Launcher.Two_menus_with_the_same_position")
1504
                                                                                        + " - "
1505
                                                                                        + menus[k].getText()
1506
                                                                                        + " - " + exts[j].getClassName());
1507
                                                }
1508

    
1509
                                                orderedMenus.add(sm);
1510
                                        }
1511
                                }
1512

    
1513
                                // Se instalan las extensiones de MDI
1514
                                SkinExtension[] skinExts = pc.getExtensions()
1515
                                                .getSkinExtension();
1516
                                for (int j = 0; j < skinExts.length; j++) {
1517

    
1518
                                        if (skinExts[j] != null) {
1519
                                                Menu[] menu = skinExts[j].getMenu();
1520

    
1521
                                                for (int k = 0; k < menu.length; k++) {
1522
                                                        SortableMenu sm = new SortableMenu(ps
1523
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1524

    
1525
                                                        if (orderedMenus.contains(sm)) {
1526
                                                                this
1527
                                                                                .addError(Messages
1528
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1529
                                                                                                + skinExts[j].getClassName());
1530
                                                        }
1531

    
1532
                                                        orderedMenus.add(sm);
1533
                                                }
1534
                                        }
1535
                                }
1536

    
1537
                        } catch (Throwable e) {
1538
                                addError("Error initializing menus of plugin '" + pName + "'",
1539
                                                e);
1540
                        }
1541

    
1542
                }
1543

    
1544
                return orderedMenus;
1545
        }
1546

    
1547
        private void installPluginsMenus() {
1548
                logger.info("installPluginsMenus");
1549

    
1550
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1551

    
1552
                // Se itera por los menus ordenados
1553
                Iterator<SortableMenu> e = orderedMenus.iterator();
1554

    
1555
                // Se ordenan los menues
1556
                while (e.hasNext()) {
1557
                        try {
1558
                                SortableMenu sm = e.next();
1559

    
1560
                                logger.info(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1561
                                
1562
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1563

    
1564
                        } catch (ClassNotFoundException ex) {
1565
                                this
1566
                                                .addError(
1567
                                                                Messages
1568
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1569
                                                                ex);
1570
                        } catch (NoClassDefFoundError ex) {
1571
                                this
1572
                                                .addError(
1573
                                                                Messages
1574
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1575
                                                                ex);
1576
                        } catch (Throwable ex) {
1577
                                this
1578
                                                .addError(
1579
                                                                Messages
1580
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1581
                                                                ex);
1582
                        }
1583
                }
1584
        }
1585

    
1586
        public class PluginMenuItem {
1587
                private Menu menu;
1588
                private PluginClassLoader loader;
1589
                private SkinExtensionType extension;
1590

    
1591
                PluginMenuItem(PluginClassLoader loader,
1592
                                SkinExtensionType extension, Menu menu) {
1593
                        this.menu = menu;
1594
                        this.loader = loader;
1595
                        this.extension = extension;
1596
                }
1597
                
1598
                public PluginServices getPlugin() {
1599
                        String pluginName = loader.getPluginName();
1600
                        return PluginServices.getPluginServices(pluginName);
1601
                }
1602
                
1603
                public String getExtensionName() {
1604
                        return this.extension.getClassName();
1605
                }
1606
                
1607
                public IExtension getExtension() {
1608
                        Class<?> extensionClass;
1609
                        try {
1610
                                extensionClass = loader.loadClass(this.extension.getClassName());
1611
                        } catch (ClassNotFoundException e) {
1612
                                return null;
1613
                        }
1614
                        return PluginServices.getExtension(extensionClass);
1615
                }
1616
                
1617
                public String getText() {
1618
                        return this.menu.getText();
1619
                }
1620

    
1621
                public long getPosition() {
1622
                        return this.menu.getPosition();
1623
                }
1624
                
1625
                public String getName() {
1626
                        return this.menu.getName();
1627
                }
1628
                
1629
                public boolean isParent() {
1630
                        return menu.getIs_separator();
1631
                }
1632
                
1633
                public String getPluginName() {
1634
                        return this.loader.getPluginName();
1635
                }
1636
                
1637
                public ActionInfo getAction() {
1638
                        ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1639
                        return manager.getAction(this.menu.getName());
1640
                }
1641
        }
1642
        
1643
        public List<PluginMenuItem> getPluginMenuItems() {
1644
                List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1645

    
1646
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1647
                Iterator<SortableMenu> e = orderedMenus.iterator();
1648
                while (e.hasNext()) {
1649
                                SortableMenu sm = e.next();
1650
                                PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1651
                                menuItems.add(item);
1652
                }
1653
                return menuItems;
1654
        }
1655

    
1656
        
1657
        /**
1658
         * Installs the menus, toolbars, actiontools, selectable toolbars and
1659
         * combos. The order in which they are shown is determined here.
1660
         */
1661
        private void installPluginsControls() {
1662
                logger.info("installPluginsControls (toolbars)");
1663

    
1664
                Iterator<String> i = pluginsConfig.keySet().iterator();
1665

    
1666
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1667
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1668
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1669
                                new ExtensionComparator());
1670

    
1671
                // First of all, sort the extensions.
1672
                // We need to iterate on the plugins, and iterate on each plugin's
1673
                // extensions
1674
                // (each plugin may contain one or more extensions)
1675
                while (i.hasNext()) { // iterate on the plugins
1676
                        String pName = i.next();
1677
                        try {
1678
                                PluginConfig pc = pluginsConfig.get(pName);
1679
                                PluginServices ps = pluginsServices.get(pName);
1680

    
1681
                                Extension[] exts = pc.getExtensions().getExtension();
1682

    
1683
                                for (int j = 0; j < exts.length; j++) { // iterate on the
1684
                                        // extensions
1685
                                        String cname = "unknow";
1686
                                        try {
1687
                                                cname = exts[j].getClassName();
1688
                                                if (exts[j].getActive()
1689
                                                                && !cname.equals(LibraryExtension.class
1690
                                                                                .getName())) {
1691
                                                        if (orderedExtensions.contains(exts[j])) {
1692
                                                                this
1693
                                                                                .addError(Messages
1694
                                                                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1695
                                                                                                + cname);
1696
                                                        }
1697

    
1698
                                                        orderedExtensions.add(exts[j]);
1699
                                                        extensionPluginServices.put(exts[j], ps);
1700
                                                        extensionPluginConfig.put(exts[j], pc);
1701
                                                }
1702
                                        } catch (Exception e) {
1703
                                                addError("Error initializing controls of plugin '"
1704
                                                                + pName + "' extension '" + cname + "'", e);
1705
                                        }
1706
                                }
1707
                        } catch (Throwable e) {
1708
                                addError("Error initializing controls of plugin '" + pName
1709
                                                + "'", e);
1710
                        }
1711
                }
1712

    
1713
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1714
                                new ToolComparator());
1715
                Iterator<Extension> e = orderedExtensions.iterator();
1716

    
1717
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1718
                // selectabletools)
1719
                // and load the combo-scales and combo-buttons for the status bar
1720
                while (e.hasNext()) {
1721
                        Extension ext = e.next();
1722
                        String extName = "unknow";
1723
                        try {
1724
                                extName = ext.getClassName();
1725
                                ToolBar[] toolbars = ext.getToolBar();
1726

    
1727
                                // get tools from toolbars
1728
                                for (int k = 0; k < toolbars.length; k++) {
1729
                                        ActionTool[] tools = toolbars[k].getActionTool();
1730

    
1731
                                        for (int t = 0; t < tools.length; t++) {
1732
                                                SortableTool sm = new SortableTool(
1733
                                                                (extensionPluginServices.get(ext))
1734
                                                                                .getClassLoader(), ext, toolbars[k],
1735
                                                                tools[t]);
1736
                                                orderedTools.add(sm);
1737
                                        }
1738

    
1739
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1740

    
1741
                                        for (int t = 0; t < sTools.length; t++) {
1742
                                                SortableTool sm = new SortableTool(
1743
                                                                (extensionPluginServices.get(ext))
1744
                                                                                .getClassLoader(), ext, toolbars[k],
1745
                                                                sTools[t]);
1746
                                                orderedTools.add(sm);
1747
                                        }
1748
                                }
1749

    
1750
                                // get controls for statusBar
1751
                                PluginServices ps = extensionPluginServices.get(ext);
1752
                                PluginClassLoader loader = ps.getClassLoader();
1753

    
1754
                                // ArrayList componentList = new ArrayList();
1755
                                ComboScale[] comboScaleArray = ext.getComboScale();
1756
                                for (int k = 0; k < comboScaleArray.length; k++) {
1757
                                        org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1758
                                        String label = comboScaleArray[k].getLabel();
1759
                                        if (label != null) {
1760
                                                combo.setLabel(label);
1761
                                        }
1762
                                        String name = comboScaleArray[k].getName();
1763
                                        if (name != null) {
1764
                                                combo.setName(name);
1765
                                        }
1766
                                        String[] elementsString = ((String) comboScaleArray[k]
1767
                                                        .getElements()).split(";");
1768
                                        long[] elements = new long[elementsString.length];
1769
                                        for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
1770
                                                try {
1771
                                                        elements[currentElem] = Long
1772
                                                                        .parseLong(elementsString[currentElem]);
1773
                                                } catch (NumberFormatException nfex1) {
1774
                                                        this
1775
                                                                        .addError(ext.getClassName()
1776
                                                                                        + " -- "
1777
                                                                                        + Messages
1778
                                                                                                        .getString("error_parsing_comboscale_elements"));
1779
                                                        elements[currentElem] = 0;
1780
                                                }
1781
                                        }
1782
                                        combo.setItems(elements);
1783
                                        try {
1784
                                                long value = Long.parseLong((String) comboScaleArray[k]
1785
                                                                .getValue());
1786
                                                combo.setScale(value);
1787
                                        } catch (NumberFormatException nfex2) {
1788
                                                this
1789
                                                                .addError(ext.getClassName()
1790
                                                                                + " -- "
1791
                                                                                + Messages
1792
                                                                                                .getString("error_parsing_comboscale_value"));
1793
                                        }
1794
                                        try {
1795
                                                frame.addStatusBarControl(loader.loadClass(ext
1796
                                                                .getClassName()), combo);
1797
                                        } catch (ClassNotFoundException e1) {
1798
                                                this
1799
                                                                .addError(
1800
                                                                                Messages
1801
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1802
                                                                                e1);
1803
                                        }
1804
                                }
1805

    
1806
                                ComboButton[] comboButtonArray = ext.getComboButton();
1807
                                for (int k = 0; k < comboButtonArray.length; k++) {
1808
                                        ComboButtonElement[] elementList = comboButtonArray[k]
1809
                                                        .getComboButtonElement();
1810
                                        org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1811
                                        String name = comboButtonArray[k].getName();
1812
                                        if (name != null) {
1813
                                                combo.setName(name);
1814
                                        }
1815
                                        for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
1816
                                                ComboButtonElement element = elementList[currentElement];
1817
                                                ImageIcon icon;
1818
                                                URL iconLocation = loader
1819
                                                                .getResource(element.getIcon());
1820
                                                if (iconLocation == null) {
1821
                                                        this.addError(Messages.getString("Icon_not_found_")
1822
                                                                        + element.getIcon());
1823
                                                } else {
1824
                                                        icon = new ImageIcon(iconLocation);
1825
                                                        JButton button = new JButton(icon);
1826
                                                        combo.addButton(button);
1827
                                                        button.setActionCommand(element.getActionCommand());
1828
                                                }
1829
                                        }
1830
                                        try {
1831
                                                frame.addStatusBarControl(loader.loadClass(ext
1832
                                                                .getClassName()), combo);
1833
                                        } catch (ClassNotFoundException e1) {
1834
                                                this
1835
                                                                .addError(
1836
                                                                                Messages
1837
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1838
                                                                                e1);
1839
                                        }
1840
                                }
1841
                        } catch (Throwable e2) {
1842
                                addError(
1843
                                                "Error initializing tools and status bars of extension '"
1844
                                                                + extName + "'", e2);
1845
                        }
1846
                }
1847

    
1848
                // Add the tools from MDI extensions to the ordered tool-list, so that
1849
                // we get a sorted list containing all the tools
1850
                i = pluginsConfig.keySet().iterator();
1851
                while (i.hasNext()) {
1852
                        String pName = (String) i.next();
1853
                        try {
1854
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1855
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
1856

    
1857
                                SkinExtension[] skinExts = pc.getExtensions()
1858
                                                .getSkinExtension();
1859
                                for (int j = 0; j < skinExts.length; j++) {
1860

    
1861
                                        if (skinExts[j] != null) {
1862
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1863

    
1864
                                                for (int k = 0; k < toolbars.length; k++) {
1865
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1866

    
1867
                                                        for (int t = 0; t < tools.length; t++) {
1868
                                                                SortableTool stb = new SortableTool(ps
1869
                                                                                .getClassLoader(), skinExts[j],
1870
                                                                                toolbars[k], tools[t]);
1871
                                                                orderedTools.add(stb);
1872
                                                        }
1873

    
1874
                                                        SelectableTool[] sTools = toolbars[k]
1875
                                                                        .getSelectableTool();
1876

    
1877
                                                        for (int t = 0; t < sTools.length; t++) {
1878
                                                                SortableTool stb = new SortableTool(ps
1879
                                                                                .getClassLoader(), skinExts[j],
1880
                                                                                toolbars[k], sTools[t]);
1881
                                                                orderedTools.add(stb);
1882
                                                        }
1883
                                                }
1884
                                        }
1885
                                }
1886
                                // Install popup menus
1887
                                PopupMenus pus = pc.getPopupMenus();
1888
                                if (pus != null) {
1889
                                        PopupMenu[] menus = pus.getPopupMenu();
1890
                                        for (int j = 0; j < menus.length; j++) {
1891
                                                String menuName = "(unknow)";
1892
                                                try  {
1893
                                                        menuName = menus[j].getName();
1894
                                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1895
                                                } catch(Throwable ex) {
1896
                                                        addError("Error adding popup menu' "+ menuName +"' in plugin '"+pName+"'.");
1897
                                                }
1898
                                        }
1899
                                }
1900
                        } catch (Throwable e3) {
1901
                                addError("Error initializing skins of the plugin '" + pName
1902
                                                + "'", e3);
1903
                        }
1904
                }
1905

    
1906
                // loop on the ordered extension list, to add them to the interface in
1907
                // an ordered way
1908
                Iterator<SortableTool> t = orderedTools.iterator();
1909
                while (t.hasNext()) {
1910
                        SortableTool stb = t.next();
1911
                        try {
1912
                                if (stb.actiontool != null) {
1913
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1914
                                                        stb.actiontool);
1915
                                } else {
1916
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1917
                                                        stb.selectabletool);
1918
                                }
1919
                        } catch (ClassNotFoundException ex) {
1920
                                this
1921
                                                .addError(
1922
                                                                Messages
1923
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1924
                                                                ex);
1925
                        } catch (Throwable e2) {
1926
                                addError("Error adding tools to the interface of extension '"
1927
                                                + stb.extension.getClassName() + "'", e2);
1928
                        }
1929
                }
1930
        }
1931

    
1932
        /**
1933
         * Adds new plugins to the the andami-config file.
1934
         */
1935
        private void updateAndamiConfig() {
1936
                Set<String> olds = new HashSet<String>();
1937

    
1938
                Plugin[] plugins = andamiConfig.getPlugin();
1939

    
1940
                for (int i = 0; i < plugins.length; i++) {
1941
                        olds.add(plugins[i].getName());
1942
                }
1943

    
1944
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1945

    
1946
                while (i.hasNext()) {
1947
                        PluginServices ps = i.next();
1948

    
1949
                        if (!olds.contains(ps.getPluginName())) {
1950
                                Plugin p = new Plugin();
1951
                                p.setName(ps.getPluginName());
1952
                                p.setUpdate(false);
1953

    
1954
                                andamiConfig.addPlugin(p);
1955
                        }
1956
                }
1957
        }
1958

    
1959
        private void pluginsClassLoaders() {
1960
                Set<String> installed = new HashSet<String>();
1961

    
1962
                // Se itera hasta que est?n todos instalados
1963
                while (installed.size() != pluginsConfig.size()) {
1964
                        boolean circle = true;
1965

    
1966
                        // Hacemos una pasada por todos los plugins
1967
                        Iterator<String> i = pluginsConfig.keySet().iterator();
1968

    
1969
                        while (i.hasNext()) {
1970
                                String pluginName = i.next();
1971
                                PluginConfig config = (PluginConfig) pluginsConfig
1972
                                                .get(pluginName);
1973

    
1974
                                if (installed.contains(pluginName)) {
1975
                                        continue;
1976
                                }
1977

    
1978
                                // Se obtienen las dependencias y sus class loaders
1979
                                boolean ready = true;
1980
                                Depends[] dependencies = config.getDepends();
1981
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1982

    
1983
                                for (int j = 0; j < dependencies.length; j++) {
1984
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1985
                                                this
1986
                                                                .addError(Messages
1987
                                                                                .getString("Launcher.Dependencia_no_resuelta_en_plugin")
1988
                                                                                + " "
1989
                                                                                + pluginName
1990
                                                                                + ": "
1991
                                                                                + dependencies[j].getPluginName());
1992

    
1993
                                                continue;
1994
                                        }
1995

    
1996
                                        if (!installed.contains(dependencies[j].getPluginName())) {
1997
                                                ready = false;
1998
                                        } else {
1999
                                                loaders[j] = (pluginsServices.get(dependencies[j]
2000
                                                                .getPluginName())).getClassLoader();
2001
                                        }
2002
                                }
2003

    
2004
                                // Si no est?n sus dependencias satisfechas se aborta la
2005
                                // instalaci?n
2006
                                if (!ready) {
2007
                                        continue;
2008
                                }
2009

    
2010
                                // Se genera el class loader
2011
                                String jardir = config.getLibraries().getLibraryDir();
2012
                                File jarDir = new File(andamiConfig.getPluginsDirectory(),
2013
                                                pluginName + File.separator + jardir);
2014
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
2015

    
2016
                                        public boolean accept(File pathname) {
2017
                                                return (pathname.getName().toUpperCase()
2018
                                                                .endsWith(".JAR"))
2019
                                                                || (pathname.getName().toUpperCase()
2020
                                                                                .endsWith(".ZIP"));
2021
                                        }
2022
                                });
2023

    
2024
                                URL[] urls = new URL[jarFiles.length];
2025

    
2026
                                for (int j = 0; j < jarFiles.length; j++) {
2027
                                        try {
2028
                                                urls[j] = new URL("file:" + jarFiles[j]);
2029
                                        } catch (MalformedURLException e) {
2030
                                                this.addError(Messages
2031
                                                                .getString("Launcher.No_se_puede_acceder_a")
2032
                                                                + " " + jarFiles[j]);
2033
                                        }
2034
                                }
2035

    
2036
                                PluginClassLoader loader;
2037

    
2038
                                try {
2039
                                        loader = new PluginClassLoader(urls, andamiConfig
2040
                                                        .getPluginsDirectory()
2041
                                                        + File.separator + pluginName, Launcher.class
2042
                                                        .getClassLoader(), loaders);
2043

    
2044
                                        PluginServices ps = new PluginServices(loader);
2045

    
2046
                                        pluginsServices.put(ps.getPluginName(), ps);
2047

    
2048
                                        installed.add(pluginName);
2049
                                        // FJP: Los metemos ordenados para luego no cargar uno que
2050
                                        // necesita de otro antes de tiempo. Esto lo usaremos al
2051
                                        // inicializar los plugins
2052
                                        pluginsOrdered.add(pluginName);
2053

    
2054
                                        circle = false;
2055
                                } catch (IOException e) {
2056
                                        this
2057
                                                        .addError(
2058
                                                                        Messages
2059
                                                                                        .getString("Launcher.Error_con_las_librerias_del_plugin"),
2060
                                                                        e);
2061
                                        pluginsConfig.remove(pluginName);
2062
                                        i = pluginsConfig.keySet().iterator();
2063
                                }
2064
                        }
2065

    
2066
                        if (circle) {
2067
                                this.addError(Messages
2068
                                                .getString("Launcher.Hay_dependencias_circulares"));
2069

    
2070
                                break;
2071
                        }
2072
                }
2073

    
2074
                // Se eliminan los plugins que no fueron instalados
2075
                Iterator<String> i = pluginsConfig.keySet().iterator();
2076

    
2077
                while (i.hasNext()) {
2078
                        String pluginName = i.next();
2079
                        PluginServices ps = (PluginServices) pluginsServices
2080
                                        .get(pluginName);
2081

    
2082
                        if (ps == null) {
2083
                                pluginsConfig.remove(pluginName);
2084
                                i = pluginsConfig.keySet().iterator();
2085
                        }
2086
                }
2087
                registerActions();
2088
        }
2089

    
2090
        private void pluginsMessages() {
2091
                Iterator<String> iterator = pluginsOrdered.iterator();
2092
                PluginConfig config;
2093
                PluginServices ps;
2094

    
2095
                while (iterator.hasNext()) {
2096
                        String pluginName = iterator.next();
2097
                        config = pluginsConfig.get(pluginName);
2098
                        ps = pluginsServices.get(pluginName);
2099

    
2100
                        if ((config.getResourceBundle() != null)
2101
                                        && !config.getResourceBundle().getName().equals("")) {
2102
                                // add the locale files associated with the plugin
2103
                                org.gvsig.i18n.Messages.addResourceFamily(config
2104
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2105
                                                pluginName);
2106
                        }
2107
                }
2108
        }
2109

    
2110
        static public PluginServices getPluginServices(String name) {
2111
                return (PluginServices) pluginsServices.get(name);
2112
        }
2113

    
2114
        static String getPluginsDir() {
2115
                return andamiConfig.getPluginsDirectory();
2116
        }
2117

    
2118
        static void setPluginsDir(String s) {
2119
                andamiConfig.setPluginsDirectory(s);
2120
        }
2121

    
2122
        static MDIFrame getMDIFrame() {
2123
                return frame;
2124
        }
2125

    
2126
        private void loadPlugins(String pluginsDirectory) {
2127
                File pDir = new File(pluginsDirectory);
2128

    
2129
                if (!pDir.exists()) {
2130
                        logger
2131
                                        .error("\n\tPlugins directory not found: "
2132
                                                        + pDir.getAbsolutePath()
2133
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2134
                        System.exit(-1);
2135
                        return;
2136
                }
2137

    
2138
                File[] pluginDirs = pDir.listFiles();
2139
                if (pluginDirs.length == 0) {
2140
                        logger
2141
                                        .error("\n\tPlugins directory is empty: "
2142
                                                        + pDir.getAbsolutePath()
2143
                                                        + "Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2144
                        System.exit(-1);
2145
                        return;
2146
                }
2147

    
2148
                for (int i = 0; i < pluginDirs.length; i++) {
2149
                        if (pluginDirs[i].isDirectory()) {
2150
                                String pluginName =  pluginDirs[i].getName();
2151
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2152
                                                "config.xml");
2153

    
2154
                                try {
2155
                                        FileInputStream is = new FileInputStream(configXml);
2156
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2157
                                        if (xml == null) {
2158
                                                // the encoding was not correctly detected, use system
2159
                                                // default
2160
                                                xml = new FileReader(configXml);
2161
                                        } else {
2162
                                                // use a buffered reader to improve performance
2163
                                                xml = new BufferedReader(xml);
2164
                                        }
2165
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2166
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
2167
                                } catch (FileNotFoundException e) {
2168
                                        logger.info("Plugin '"+pluginName+"' without config.xml ("
2169
                                                                        + pluginDirs[i].getAbsolutePath() + ").");
2170
                                } catch (MarshalException e) {
2171
                                        this.addError("Can't load plugin '"+pluginName+"', incorrect config.xml." + e.getMessage() +" ("
2172
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2173
                                } catch (ValidationException e) {
2174
                                        this.addError("Can't load plugin '"+pluginName+"', invalid config.xml." + e.getMessage() +" ("
2175
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2176
                                }
2177
                        }
2178
                }
2179

    
2180
                if (pluginsConfig.size() == 0) {
2181
                        logger.error("No valid plugin was found. The plugins directory currently is: "
2182
                                                        + pDir.getAbsolutePath()
2183
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2184
                        System.exit(-1);
2185
                        return;
2186
                }
2187
        }
2188

    
2189
        private static Locale getLocale(String language, String country,
2190
                        String variant) {
2191
                if (variant != null) {
2192
                        return new Locale(language, country, variant);
2193
                } else if (country != null) {
2194
                        return new Locale(language, country);
2195
                } else if (language != null) {
2196
                        return new Locale(language);
2197
                } else {
2198
                        return new Locale("es");
2199
                }
2200
        }
2201

    
2202
        private static void andamiConfigToXML(String file) throws IOException,
2203
                        MarshalException, ValidationException {
2204
                // write on a temporary file in order to not destroy current file if
2205
                // there is some problem while marshaling
2206
                File tmpFile = new File(file + "-"
2207
                                + DateTime.getCurrentDate().getTime());
2208
                File xml = new File(file);
2209
                File parent = xml.getParentFile();
2210
                parent.mkdirs();
2211

    
2212
                BufferedOutputStream os = new BufferedOutputStream(
2213
                                new FileOutputStream(tmpFile));
2214
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2215
                andamiConfig.marshal(writer);
2216
                writer.close();
2217

    
2218
                // if marshaling process finished correctly, move the file to the
2219
                // correct one
2220
                xml.delete();
2221
                if (!tmpFile.renameTo(xml)) {
2222
                        // if rename was not succesful, try copying it
2223
                        FileChannel sourceChannel = new FileInputStream(tmpFile)
2224
                                        .getChannel();
2225
                        FileChannel destinationChannel = new FileOutputStream(xml)
2226
                                        .getChannel();
2227
                        sourceChannel.transferTo(0, sourceChannel.size(),
2228
                                        destinationChannel);
2229
                        sourceChannel.close();
2230
                        destinationChannel.close();
2231
                }
2232
        }
2233

    
2234
        private static void andamiConfigFromXML(String file)
2235
                        throws ConfigurationException {
2236
                File xml = new File(file);
2237

    
2238
                InputStreamReader reader = null;
2239
                try {
2240
                        // Se lee la configuraci?n
2241
                        reader = XMLEncodingUtils.getReader(xml);
2242
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2243
                } catch (FileNotFoundException e) {
2244
                        // Si no existe se ponen los valores por defecto
2245
                        andamiConfig = getDefaultAndamiConfig();
2246
                } catch (MarshalException e) {
2247
                        // try to close the stream, maybe it remains open
2248
                        if (reader != null) {
2249
                                try {
2250
                                        reader.close();
2251
                                } catch (IOException e1) {
2252
                                }
2253
                        }
2254
                        // if there was a problem reading the file, backup it and create a
2255
                        // new one with default values
2256
                        String backupFile = file + "-"
2257
                                        + DateTime.getCurrentDate().getTime();
2258
                        NotificationManager
2259
                                        .addError(
2260
                                                        Messages
2261
                                                                        .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2262
                                                                        + backupFile, new ConfigurationException(e));
2263
                        xml.renameTo(new File(backupFile));
2264
                        andamiConfig = getDefaultAndamiConfig();
2265
                } catch (ValidationException e) {
2266
                        throw new ConfigurationException(e);
2267
                }
2268
        }
2269

    
2270
        private static AndamiConfig getDefaultAndamiConfig() {
2271
                AndamiConfig andamiConfig = new AndamiConfig();
2272

    
2273
                Andami andami = new Andami();
2274
                andami.setUpdate(true);
2275
                andamiConfig.setAndami(andami);
2276
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2277
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2278
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2279

    
2280
                if (System.getProperty("javawebstart.version") != null) // Es java web
2281
                // start)
2282
                {
2283
                        andamiConfig
2284
                                        .setPluginsDirectory(new File(appHomeDir, "extensiones")
2285
                                                        .getAbsolutePath());
2286
                } else {
2287
                        andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2288
                                        .getAbsolutePath());
2289
                }
2290

    
2291
                andamiConfig.setPlugin(new Plugin[0]);
2292
                return andamiConfig;
2293
        }
2294

    
2295
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2296
                File xml = getPluginsPersistenceFile(true);
2297

    
2298
                if (xml.exists()) {
2299
                        InputStreamReader reader = null;
2300

    
2301
                        try {
2302
                                reader = XMLEncodingUtils.getReader(xml);
2303
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2304
                                return new XMLEntity(tag);
2305
                        } catch (FileNotFoundException e) {
2306
                                throw new ConfigurationException(e);
2307
                        } catch (MarshalException e) {
2308

    
2309
                                // try to reopen with default encoding (for backward
2310
                                // compatibility)
2311
                                try {
2312
                                        reader = new FileReader(xml);
2313
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2314
                                        return new XMLEntity(tag);
2315

    
2316
                                } catch (MarshalException ex) {
2317
                                        // try to close the stream, maybe it remains open
2318
                                        if (reader != null) {
2319
                                                try {
2320
                                                        reader.close();
2321
                                                } catch (IOException e1) {
2322
                                                }
2323
                                        }
2324
                                        // backup the old file
2325
                                        String backupFile = getPluginsPersistenceFile(true)
2326
                                                        .getPath()
2327
                                                        + "-" + DateTime.getCurrentDate().getTime();
2328
                                        NotificationManager
2329
                                                        .addError(
2330
                                                                        Messages
2331
                                                                                        .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2332
                                                                                        + backupFile,
2333
                                                                        new ConfigurationException(e));
2334
                                        xml.renameTo(new File(backupFile));
2335
                                        // create a new, empty configuration
2336
                                        return new XMLEntity();
2337
                                } catch (FileNotFoundException ex) {
2338
                                        return new XMLEntity();
2339
                                } catch (ValidationException ex) {
2340
                                        throw new ConfigurationException(e);
2341
                                }
2342
                        } catch (ValidationException e) {
2343
                                throw new ConfigurationException(e);
2344
                        }
2345
                } else {
2346
                        return new XMLEntity();
2347
                }
2348
        }
2349

    
2350
        private static File getPluginsPersistenceFile(boolean read) {
2351
                if (read) {
2352
                        File pluginsPersistenceFile = new File(getAppHomeDir(),
2353
                                        "plugins-persistence-2_0.xml");
2354
                        if (pluginsPersistenceFile.exists()) {
2355
                                return pluginsPersistenceFile;
2356
                        }
2357
                        pluginsPersistenceFile = new File(getAppHomeDir(),
2358
                                        "plugins-persistence.xml");
2359
                        if (pluginsPersistenceFile.exists()) {
2360
                                return pluginsPersistenceFile;
2361
                        }
2362
                }
2363
                return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2364

    
2365
        }
2366

    
2367
        private static void persistenceToXML(XMLEntity entity)
2368
                        throws ConfigurationException {
2369
                // write on a temporary file in order to not destroy current file if
2370
                // there is some problem while marshaling
2371
                File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2372
                                + "-" + DateTime.getCurrentDate().getTime());
2373

    
2374
                File xml = getPluginsPersistenceFile(false);
2375
                OutputStreamWriter writer = null;
2376

    
2377
                try {
2378
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2379
                                        CASTORENCODING);
2380
                        entity.getXmlTag().marshal(writer);
2381
                        writer.close();
2382

    
2383
                        // if marshaling process finished correctly, move the file to the
2384
                        // correct one
2385
                        xml.delete();
2386
                        if (!tmpFile.renameTo(xml)) {
2387
                                // if rename was not succesful, try copying it
2388
                                FileChannel sourceChannel = new FileInputStream(tmpFile)
2389
                                                .getChannel();
2390
                                FileChannel destinationChannel = new FileOutputStream(xml)
2391
                                                .getChannel();
2392
                                sourceChannel.transferTo(0, sourceChannel.size(),
2393
                                                destinationChannel);
2394
                                sourceChannel.close();
2395
                                destinationChannel.close();
2396

    
2397
                        }
2398
                } catch (FileNotFoundException e) {
2399
                        throw new ConfigurationException(e);
2400
                } catch (MarshalException e) {
2401
                        // try to close the stream, maybe it remains open
2402
                        if (writer != null) {
2403
                                try {
2404
                                        writer.close();
2405
                                } catch (IOException e1) {
2406
                                }
2407
                        }
2408
                } catch (ValidationException e) {
2409
                        throw new ConfigurationException(e);
2410
                } catch (IOException e) {
2411
                        throw new ConfigurationException(e);
2412
                }
2413
        }
2414

    
2415
        static MDIFrame getFrame() {
2416
                return frame;
2417
        }
2418

    
2419
        /**
2420
         * Gracefully closes the application. It shows dialogs to save data, finish
2421
         * processes, etc, then it terminates the extensions, removes temporal files
2422
         * and finally exits.
2423
         */
2424
        public synchronized static void closeApplication() {
2425
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2426
                terminationProcess.run();
2427
        }
2428

    
2429
        static HashMap getClassesExtensions() {
2430
                return classesExtensions;
2431
        }
2432

    
2433
        private static Extensions[] getExtensions() {
2434
                List<Extensions> array = new ArrayList<Extensions>();
2435
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2436

    
2437
                while (iter.hasNext()) {
2438
                        array.add(iter.next().getExtensions());
2439
                }
2440

    
2441
                return array.toArray(new Extensions[array.size()]);
2442
        }
2443

    
2444
        public static Iterator getExtensionIterator() {
2445
                return extensions.iterator();
2446
        }
2447

    
2448
        public static HashMap getPluginConfig() {
2449
                return pluginsConfig;
2450
        }
2451

    
2452
        public static Extension getExtension(String s) {
2453
                Extensions[] exts = getExtensions();
2454

    
2455
                for (int i = 0; i < exts.length; i++) {
2456
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2457
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2458
                                        return exts[i].getExtension(j);
2459
                                }
2460
                        }
2461
                }
2462

    
2463
                return null;
2464
        }
2465

    
2466
        public static AndamiConfig getAndamiConfig() {
2467
                return andamiConfig;
2468
        }
2469

    
2470
        private static class ExtensionComparator implements Comparator {
2471

    
2472
                public int compare(Object o1, Object o2) {
2473
                        Extension e1 = (Extension) o1;
2474
                        Extension e2 = (Extension) o2;
2475

    
2476
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2477
                                return -1;
2478
                        }
2479

    
2480
                        if (e1.hasPriority() && !e2.hasPriority()) {
2481
                                return Integer.MIN_VALUE;
2482
                        }
2483

    
2484
                        if (e2.hasPriority() && !e1.hasPriority()) {
2485
                                return Integer.MAX_VALUE;
2486
                        }
2487

    
2488
                        if (e1.getPriority() != e2.getPriority()) {
2489
                                return e2.getPriority() - e1.getPriority();
2490
                        } else {
2491
                                return (e2.toString().compareTo(e1.toString()));
2492
                        }
2493
                }
2494
        }
2495

    
2496
        private static class MenuComparator implements Comparator<SortableMenu> {
2497

    
2498
                private static ExtensionComparator extComp = new ExtensionComparator();
2499

    
2500
                public int compare(SortableMenu e1, SortableMenu e2) {
2501

    
2502
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2503
                                if (e1.extension instanceof SkinExtensionType) {
2504
                                        return 1;
2505
                                } else if (e2.extension instanceof SkinExtensionType) {
2506
                                        return -1;
2507
                                } else {
2508
                                        return extComp.compare(e1.extension, e2.extension);
2509
                                }
2510
                        }
2511

    
2512
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2513
                                return Integer.MIN_VALUE;
2514
                        }
2515

    
2516
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2517
                                return Integer.MAX_VALUE;
2518
                        }
2519
                        
2520
                        if( e1.menu.getPosition() == e2.menu.getPosition() ) {
2521
                                // we don't return 0 unless both objects are the same, otherwise
2522
                                // the objects get overwritten in the treemap
2523
                                return (e1.toString().compareTo(e2.toString()));
2524
                        }
2525
                    if( e1.menu.getPosition() > e2.menu.getPosition() ) {
2526
                                return Integer.MAX_VALUE;
2527
                        }
2528
                    return Integer.MIN_VALUE;
2529
                    
2530
                }
2531
        }
2532

    
2533
        private static class SortableMenu {
2534

    
2535
                public PluginClassLoader loader;
2536
                public Menu menu;
2537
                public SkinExtensionType extension;
2538

    
2539
                public SortableMenu(PluginClassLoader loader,
2540
                                SkinExtensionType skinExt, Menu menu2) {
2541
                        extension = skinExt;
2542
                        menu = menu2;
2543
                        this.loader = loader;
2544
                }
2545
                
2546
        }
2547

    
2548
        private static class SortableTool {
2549

    
2550
                public PluginClassLoader loader;
2551
                public ToolBar toolbar;
2552
                public ActionTool actiontool;
2553
                public SelectableTool selectabletool;
2554
                public SkinExtensionType extension;
2555

    
2556
                public SortableTool(PluginClassLoader loader,
2557
                                SkinExtensionType skinExt, ToolBar toolbar2,
2558
                                ActionTool actiontool2) {
2559
                        extension = skinExt;
2560
                        toolbar = toolbar2;
2561
                        actiontool = actiontool2;
2562
                        this.loader = loader;
2563
                }
2564

    
2565
                public SortableTool(PluginClassLoader loader,
2566
                                SkinExtensionType skinExt, ToolBar toolbar2,
2567
                                SelectableTool selectabletool2) {
2568
                        extension = skinExt;
2569
                        toolbar = toolbar2;
2570
                        selectabletool = selectabletool2;
2571
                        this.loader = loader;
2572
                }
2573
        }
2574

    
2575
        private static class ToolBarComparator implements Comparator<SortableTool> {
2576

    
2577
                private static ExtensionComparator extComp = new ExtensionComparator();
2578

    
2579
                public int compare(SortableTool e1, SortableTool e2) {
2580

    
2581
                        // if the toolbars have the same name, they are considered to be
2582
                        // the same toolbar, so we don't need to do further comparing
2583
                        if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2584
                                return 0;
2585
                        }
2586

    
2587
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2588
                                if (e1.extension instanceof SkinExtensionType) {
2589
                                        return 1;
2590
                                } else if (e2.extension instanceof SkinExtensionType) {
2591
                                        return -1;
2592
                                } else {
2593
                                        return extComp.compare(e1.extension, e2.extension);
2594
                                }
2595
                        }
2596

    
2597
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2598
                                return Integer.MIN_VALUE;
2599
                        }
2600

    
2601
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2602
                                return Integer.MAX_VALUE;
2603
                        }
2604
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2605
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2606
                        }
2607

    
2608
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2609
                                        && e1.toolbar.getSelectableTool().equals(
2610
                                                        e2.toolbar.getSelectableTool())) {
2611
                                return 0;
2612
                        }
2613
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2614
                }
2615
        }
2616

    
2617
        /**
2618
         * <p>
2619
         * This class is used to compare tools (selectabletool and actiontool),
2620
         * using the "position" attribute.
2621
         * </p>
2622
         * <p>
2623
         * The ordering criteria are:
2624
         * </p>
2625
         * <ul>
2626
         * <li>If the tools are placed in different toolbars, they use the toolbars'
2627
         * order. (using the ToolBarComparator).</li>
2628
         * <li></li>
2629
         * <li>If any of the tools has not 'position' attribute, the tool which
2630
         * <strong>has</strong> the attribute will be placed first.</li>
2631
         * <li>If both tools have the same position (or they don't have a 'position'
2632
         * attribute), the priority of the extensions where the tool is defined.</li>
2633
         * </ul>
2634
         * 
2635
         * @author cesar
2636
         * @version $Revision: 38651 $
2637
         */
2638
        private static class ToolComparator implements Comparator<SortableTool> {
2639

    
2640
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2641

    
2642
                public int compare(SortableTool e1, SortableTool e2) {
2643
                        // compare the toolbars which contain the tools
2644
                        long result = toolBarComp.compare(e1, e2);
2645
                        if (result != 0) { // if the toolbars are different, use their order
2646
                                return result>0? 1:-1;
2647
                        }
2648
                        // otherwise, compare the tools
2649
                        long e1Position = -1, e2Position = -1;
2650

    
2651
                        if (e1.actiontool != null) {
2652
                                if (e1.actiontool.hasPosition()) {
2653
                                        e1Position = e1.actiontool.getPosition();
2654
                                }
2655
                        } else if (e1.selectabletool != null) {
2656
                                if (e1.selectabletool.hasPosition()) {
2657
                                        e1Position = e1.selectabletool.getPosition();
2658
                                }
2659
                        }
2660

    
2661
                        if (e2.actiontool != null) {
2662
                                if (e2.actiontool.hasPosition()) {
2663
                                        e2Position = e2.actiontool.getPosition();
2664
                                }
2665
                        } else if (e2.selectabletool != null) {
2666
                                if (e2.selectabletool.hasPosition()) {
2667
                                        e2Position = e2.selectabletool.getPosition();
2668
                                }
2669
                        }
2670

    
2671
                        if ((e1Position == -1) && (e2Position != -1)) {
2672
                                return 1;
2673
                        }
2674
                        if ((e1Position != -1) && (e2Position == -1)) {
2675
                                return -1;
2676
                        }
2677
                        if ((e1Position != -1) && (e2Position != -1)) {
2678
                                result = e1Position - e2Position;
2679
                                // we don't return 0 unless both objects are the same, otherwise
2680
                                // the objects get overwritten in the treemap
2681
                                if (result != 0) {
2682
                                        return  result>0? 1:-1;
2683
                                }
2684
                        }
2685
                        return e1.toString().compareTo(e2.toString());
2686
                }
2687
        }
2688

    
2689
        /**
2690
         * validates the user before starting gvsig
2691
         * 
2692
         */
2693
        private static void validate() {
2694

    
2695
                IAuthentication session = null;
2696
                try {
2697
                        session = (IAuthentication) Class.forName(
2698
                                        "com.iver.andami.authentication.Session").newInstance();
2699

    
2700
                } catch (ClassNotFoundException e) {
2701
                        return;
2702
                } catch (InstantiationException e) {
2703
                        return;
2704
                } catch (IllegalAccessException e) {
2705
                        return;
2706
                }
2707

    
2708
                session.setPluginDirectory(andamiConfig.getPluginsDirectory());
2709
                if (session.validationRequired()) {
2710
                        if (session.Login()) {
2711
                                logger.info("You are logged in");
2712
                        } else {
2713
                                JOptionPane.showMessageDialog((Component) PluginServices
2714
                                                .getMainFrame(), "You are not logged in");
2715
                        }
2716
                        PluginServices.setAuthentication(session);
2717
                }
2718
        }
2719

    
2720
        public static String getDefaultLookAndFeel() {
2721
                String osName = (String) System.getProperty("os.name");
2722

    
2723
                if ((osName.length() > 4)
2724
                                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2725
                        return nonWinDefaultLookAndFeel;
2726
                }
2727
                if (osName.toLowerCase().startsWith("mac os x")) {
2728
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2729
                }
2730

    
2731
                return UIManager.getSystemLookAndFeelClassName();
2732
        }
2733

    
2734
        /**
2735
         * Gets the ISO 839 two-characters-long language code matching the provided
2736
         * language code (which may be an ISO 839-2/T three-characters-long code or
2737
         * an ISO 839-1 two-characters-long code).
2738
         * 
2739
         * If the provided parameter is already two characters long, it returns the
2740
         * parameter without any modification.
2741
         * 
2742
         * @param langCode
2743
         *            A language code representing either an ISO 839-2/T language
2744
         *            code or an ISO 839-1 code.
2745
         * @return A two-characters-long code specifying an ISO 839 language code.
2746
         */
2747
        private static String normalizeLanguageCode(String langCode) {
2748
                final String fileName = "iso_639.tab";
2749
                if (langCode.length() == 2) {
2750
                        return langCode;
2751
                } else if (langCode.length() == 3) {
2752
                        if (langCode.equals("va") || langCode.equals("val")) { // special
2753
                                // case
2754
                                // for
2755
                                // Valencian
2756
                                return "ca";
2757
                        }
2758
                        URL isoCodes = Launcher.class.getClassLoader()
2759
                                        .getResource(fileName);
2760
                        if (isoCodes != null) {
2761
                                try {
2762
                                        BufferedReader reader = new BufferedReader(
2763
                                                        new InputStreamReader(isoCodes.openStream(),
2764
                                                                        "ISO-8859-1"));
2765
                                        String line;
2766

    
2767
                                        while ((line = reader.readLine()) != null) {
2768
                                                String[] language = line.split("\t");
2769
                                                if (language[0].equals(langCode)) {
2770
                                                        // the three
2771
                                                        // characters code
2772
                                                        return language[2]; // third column i the two
2773
                                                        // characters code
2774
                                                }
2775
                                        }
2776
                                } catch (IOException ex) {
2777
                                        logger.error(Messages
2778
                                                        .getString("Error_reading_isocodes_file"), ex);
2779
                                        return "es";
2780
                                }
2781
                        } else {
2782
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2783
                                return "es";
2784
                        }
2785
                }
2786
                return "es";
2787
        }
2788

    
2789
        /**
2790
         * Configures the locales (languages and local resources) to be used by the
2791
         * application.
2792
         * 
2793
         * First it tries to get the locale from the command line parameters, then
2794
         * the andami-config file is checked.
2795
         * 
2796
         * The locale name is normalized to get a two characters language code as
2797
         * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
2798
         * also accepted from the command line or the configuration file).
2799
         * 
2800
         * Finally, the gvsig-i18n library and the default locales for Java and
2801
         * Swing are configured.
2802
         * 
2803
         */
2804
        private static void configureLocales(String[] args) {
2805
                // Configurar el locale
2806
                String localeStr = null;
2807
                /*
2808
                 * for (int i=2; i < args.length; i++) { int index =
2809
                 * args[i].indexOf("language="); if (index != -1) localeStr =
2810
                 * args[i].substring(index+9); }
2811
                 */
2812
                localeStr = PluginServices.getArgumentByName("language");
2813
                if (localeStr == null) {
2814
                        localeStr = andamiConfig.getLocaleLanguage();
2815
                }
2816
                localeStr = normalizeLanguageCode(localeStr);
2817
                locale = getLocale(localeStr, andamiConfig.getLocaleCountry(),
2818
                                andamiConfig.getLocaleVariant());
2819
                Locale.setDefault(locale);
2820
                JComponent.setDefaultLocale(locale);
2821
                org.gvsig.i18n.Messages.addLocale(locale);
2822
                // add english and spanish as fallback languages
2823
                if (localeStr.equals("es") || localeStr.equals("ca")
2824
                                || localeStr.equals("gl") || localeStr.equals("eu")
2825
                                || localeStr.equals("va")) {
2826
                        // prefer Spanish for languages spoken in Spain
2827
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2828
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2829
                } else {
2830
                        // prefer English for the rest
2831
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2832
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2833
                }
2834

    
2835
        // Create classloader for the i18n resources in the
2836
        // andami and user i18n folder. Those values will have
2837
        // precedence over any other values added afterwards
2838
        File andamiI18nFolder =
2839
            new File(System.getProperty("user.dir"), "i18n");
2840
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2841

    
2842
        logger.info("Loading i18n resources from the application and user "
2843
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2844

    
2845
        URL[] i18nURLs;
2846
        try {
2847
            i18nURLs =
2848
                new URL[] { userI18nFolder.toURI().toURL(),
2849
                    andamiI18nFolder.toURI().toURL() };
2850
            ClassLoader i18nClassLoader = new URLClassLoader(i18nURLs);
2851
            org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
2852
                "Andami Launcher");
2853
        } catch (MalformedURLException e) {
2854
            logger.error("Error loading i18n resources from the application "
2855
                + "and user folders: " + andamiI18nFolder + ", "
2856
                + userI18nFolder, e);
2857
        }
2858

    
2859
        // Finally load the andami own i18n resources
2860
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2861
            "Andami Launcher");
2862
        }
2863

    
2864
        /**
2865
         * Gets Home Directory location of the application into users home folder.
2866
         * 
2867
         * May be set from outside the aplication by means of
2868
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2869
         * 
2870
         * @return
2871
         */
2872
        public static String getAppHomeDir() {
2873
                return appHomeDir;
2874
        }
2875
        
2876
    public static File getApplicationHomeFolder() {
2877
        return new File(getAppHomeDir());
2878
    }
2879

    
2880
        /**
2881
         * Sets Home Directory location of the application. May be set from outside
2882
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
2883
         * the name of the application
2884
         * 
2885
         * @param appHomeDir
2886
         */
2887
        public static void setAppHomeDir(String appHomeDir) {
2888
                Launcher.appHomeDir = appHomeDir;
2889
        }
2890

    
2891
        /**
2892
         * Initialize the extesion that have to take the control of the state of
2893
         * action controls of the UI of all extensions. <br>
2894
         * <br>
2895
         * For use this option you have to add an argument to the command line like
2896
         * this: <br>
2897
         * <br>
2898
         * -exclusiveUI={pathToExtensionClass} <br>
2899
         * 
2900
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
2901
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
2902
         */
2903
        private static void initializeExclusiveUIExtension() {
2904
                String name = PluginServices.getArgumentByName("exclusiveUI");
2905
                if (name == null) {
2906
                        return;
2907
                }
2908

    
2909
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
2910
                                .iterator();
2911
                int charIndex;
2912
                Class<? extends IExtension> key;
2913
                while (iter.hasNext()) {
2914
                        key = iter.next();
2915
                        charIndex = key.getName().indexOf(name);
2916
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2917
                        if (charIndex == 0) {
2918
                                IExtension ext = classesExtensions.get(key);
2919
                                if (ext instanceof ExtensionDecorator) {
2920
                                        ext = ((ExtensionDecorator) ext).getExtension();
2921
                                }
2922
                                if (ext instanceof ExclusiveUIExtension) {
2923
                                        PluginServices
2924
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
2925
                                }
2926
                                break;
2927
                        }
2928
                }
2929

    
2930
                logger
2931
                                .error(Messages
2932
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2933
                                                + " '" + name + "'");
2934
        }
2935

    
2936
        // public static void initIconThemes() {
2937
        // // load the iconTheme
2938
        // IconThemeManager iconManager = new IconThemeManager();
2939
        // PluginServices.setIconThemeManager(iconManager);
2940
        // IconThemeInfo selectedTheme = iconManager.readConfig();
2941
        // if (selectedTheme!=null) {
2942
        // iconManager.setDefault(selectedTheme);
2943
        // logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2944
        // }
2945
        // else {
2946
        // // set the default dir and try to load the default theme
2947
        // try {
2948
        // iconManager.setThemesDir(new File("iconThemes"));
2949
        // IconThemeInfo[] list = iconManager.list();
2950
        //
2951
        // for (int i=0; i<list.length; i++) {
2952
        // if (list[i].getResourceName().equals("iconThemes/icons")) {
2953
        // iconManager.setDefault(list[i]);
2954
        // logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2955
        // return;
2956
        // }
2957
        // }
2958
        // } catch (FileNotFoundException e) {
2959
        // logger.info("IconTheme basedir does not exist");
2960
        // }
2961
        // // create an empty theme
2962
        // IconThemeInfo info = new IconThemeInfo();
2963
        // info.setName("No theme loaded");
2964
        // info.setResource(null); // null resource means that no real theme is
2965
        // loaded
2966
        // info.setDescription("No theme loaded");
2967
        // info.setVersion("0");
2968
        // iconManager.setDefault(new IconTheme(info));
2969
        // logger.info("Setting an empty icon theme");
2970
        //
2971
        // }
2972
        // }
2973

    
2974
        public static void initIconThemes() {
2975
                PluginsManager pluginsManager = PluginsLocator.getManager();
2976
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
2977
                
2978
                File f = new File(pluginsManager.getApplicationFolder(),"icon-theme");
2979
                if( !f.exists() ) { 
2980
                        f.mkdir();
2981
                }
2982
                iconManager.getRepository().add(f,"_Global");
2983
                
2984
                f = new File(pluginsManager.getApplicationHomeFolder(),"icon-theme");
2985
                if( !f.exists() ) {
2986
                        f.mkdir();
2987
                }
2988
                iconManager.getRepository().add(f,"_User");
2989
                
2990
                // TODO: falta por cargar de algun fichero de config el nombre del tema 
2991
                //                  por deecto a usar y seleccionarlo aqui como tema corriente.
2992
                //
2993
        }
2994

    
2995
        /**
2996
         * Manages Andami termination process
2997
         * 
2998
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2999
         */
3000
        public class TerminationProcess {
3001

    
3002
                private boolean proceed = false;
3003
                private UnsavedDataPanel panel = null;
3004

    
3005
                public void run() {
3006
                        try {
3007
                                int exit = manageUnsavedData();
3008
                                if ((exit == JOptionPane.NO_OPTION)
3009
                                                || (exit == JOptionPane.CLOSED_OPTION)) {
3010
                                        // the user doesn't want to exit
3011
                                        return;
3012
                                }
3013
                                closeAndami();
3014
                        } catch (Exception e) {
3015
                                // It is not possible to close the application.
3016
                                // this exception has been registered before
3017
                        }
3018
                }
3019

    
3020
                /**
3021
                 * Finishes the application without asking user if want or not to save
3022
                 * unsaved data.
3023
                 */
3024
                public void closeAndami() {
3025
                        try {
3026
                                saveAndamiConfig();
3027
                        } catch (Exception ex) {
3028
                                logger
3029
                                                .error(
3030
                                                                "There was an error exiting application, can't save andami-config.xml",
3031
                                                                ex);
3032
                        }
3033

    
3034
                        try {
3035
                                // Persistencia de los plugins
3036
                                savePluginPersistence();
3037
                                savePluginsProperties();
3038
                        } catch (Exception ex) {
3039
                                logger
3040
                                                .error(
3041
                                                                "There was an error exiting application, can't save plugins properties",
3042
                                                                ex);
3043
                        }
3044

    
3045
                        // Finalize all the extensions
3046
                        finalizeExtensions();
3047

    
3048
                        try {
3049
                                // Clean any temp data created
3050
                                Utilities.cleanUpTempFiles();
3051
                        } catch (Exception ex) {
3052
                                logger
3053
                                                .error(
3054
                                                                "There was an error exiting application, can't remove temporary files",
3055
                                                                ex);
3056
                        }
3057

    
3058
                        logger.info("Quiting application.");
3059

    
3060
                        // Para la depuraci?n de memory leaks
3061
                        System.gc();
3062

    
3063
                        System.exit(0);
3064
                }
3065

    
3066
                /**
3067
         * 
3068
         */
3069
                public void saveAndamiConfig() {
3070
                        // Configuraci?n de Andami
3071
                        try {
3072
                                andamiConfigToXML(andamiConfigPath);
3073
                        } catch (MarshalException e) {
3074
                                logger
3075
                                                .error(
3076
                                                                Messages
3077
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3078
                                                                e);
3079
                        } catch (ValidationException e) {
3080
                                logger
3081
                                                .error(
3082
                                                                Messages
3083
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3084
                                                                e);
3085
                        } catch (IOException e) {
3086
                                logger
3087
                                                .error(
3088
                                                                Messages
3089
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3090
                                                                e);
3091
                        }
3092
                }
3093

    
3094
                private void savePluginsProperties() {
3095
                        PluginsManager manager = PluginsLocator.getManager();
3096
                        List<PluginServices> plugins = manager.getPlugins();
3097
                        for (PluginServices plugin : plugins) {
3098
                                if (plugin != null) {
3099
                                        plugin.savePluginProperties();
3100
                                }
3101
                        }
3102
                }
3103

    
3104
                /**
3105
                 * Exectutes the terminate method for all the extensions, in the reverse
3106
                 * order they were initialized
3107
                 * 
3108
                 */
3109
                private void finalizeExtensions() {
3110
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3111
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3112
                                                .get(i);
3113
                                String extensionName = "(unknow)";
3114
                                try {
3115
                                        extensionName = extensionInstance.getClass().getName();
3116
                                        extensionInstance.terminate();
3117
                                } catch (Exception ex) {
3118
                                        logger.error(MessageFormat.format(
3119
                                                        "There was an error extension ending {0}",
3120
                                                        extensionName), ex);
3121
                                }
3122
                        }
3123
                }
3124

    
3125
                private IUnsavedData[] getUnsavedData() throws Exception {
3126
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3127
                        IExtension exclusiveExtension = PluginServices
3128
                                        .getExclusiveUIExtension();
3129

    
3130
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3131
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3132
                                                .get(i);
3133
                                IExtensionStatus status = null;
3134
                                if (exclusiveExtension != null) {
3135
                                        status = exclusiveExtension.getStatus(extensionInstance);
3136
                                } else {
3137
                                        status = extensionInstance.getStatus();
3138
                                }
3139
                                if (status != null) {
3140
                                        try {
3141
                                                if (status.hasUnsavedData()) {
3142
                                                        IUnsavedData[] array = status.getUnsavedData();
3143
                                                        for (int element = 0; element < array.length; element++) {
3144
                                                                unsavedDataList.add(array[element]);
3145
                                                        }
3146
                                                }
3147
                                        } catch (Exception e) {
3148
                                                logger.info("Error calling the hasUnsavedData method",
3149
                                                                new Exception());
3150
                                                int option = JOptionPane
3151
                                                                .showConfirmDialog(
3152
                                                                                frame,
3153
                                                                                Messages
3154
                                                                                                .getString("error_getting_unsaved_data"),
3155
                                                                                Messages.getString("MDIFrame.salir"),
3156
                                                                                JOptionPane.YES_NO_OPTION);
3157
                                                if (option == JOptionPane.NO_OPTION) {
3158
                                                        throw e;
3159
                                                }
3160
                                        }
3161
                                }
3162
                        }
3163
                        return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3164
                                        .size()]);
3165
                }
3166

    
3167
                public UnsavedDataPanel getUnsavedDataPanel() {
3168
                        if (panel == null) {
3169
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3170
                        }
3171
                        return panel;
3172
                }
3173

    
3174
                /**
3175
                 * Checks if the extensions have some unsaved data, and shows a dialog
3176
                 * to allow saving it. This dialog also allows to don't exit Andami.
3177
                 * 
3178
                 * @return true if the user confirmed he wishes to exit, false otherwise
3179
                 * @throws Exception
3180
                 */
3181
                public int manageUnsavedData() throws Exception {
3182
                        IUnsavedData[] unsavedData = getUnsavedData();
3183

    
3184
                        // there was no unsaved data
3185
                        if (unsavedData.length == 0) {
3186
                                int option = JOptionPane
3187
                                                .showConfirmDialog(frame, Messages
3188
                                                                .getString("MDIFrame.quiere_salir"), Messages
3189
                                                                .getString("MDIFrame.salir"),
3190
                                                                JOptionPane.YES_NO_OPTION);
3191
                                return option;
3192
                        }
3193

    
3194
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3195
                        panel.setUnsavedDataArray(unsavedData);
3196

    
3197
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3198

    
3199
                                public void cancel(UnsavedDataPanel panel) {
3200
                                        proceed(false);
3201
                                        PluginServices.getMDIManager().closeWindow(panel);
3202

    
3203
                                }
3204

    
3205
                                public void discard(UnsavedDataPanel panel) {
3206
                                        proceed(true);
3207
                                        PluginServices.getMDIManager().closeWindow(panel);
3208

    
3209
                                }
3210

    
3211
                                public void accept(UnsavedDataPanel panel) {
3212
                                        IUnsavedData[] unsavedDataArray = panel
3213
                                                        .getSelectedsUnsavedData();
3214
                                        boolean saved;
3215
                                        for (int i = 0; i < unsavedDataArray.length; i++) {
3216
                                                try {
3217
                                                        saved = unsavedDataArray[i].saveData();
3218
                                                } catch (Exception ex) {
3219
                                                        PluginServices.getLogger().error(
3220
                                                                        "Error saving"
3221
                                                                                        + unsavedDataArray[i]
3222
                                                                                                        .getResourceName(), ex);
3223
                                                        saved = false;
3224
                                                }
3225
                                                if (!saved) {
3226
                                                        JOptionPane
3227
                                                                        .showMessageDialog(
3228
                                                                                        panel,
3229
                                                                                        PluginServices
3230
                                                                                                        .getText(this,
3231
                                                                                                                        "The_following_resource_could_not_be_saved_")
3232
                                                                                                        + "\n"
3233
                                                                                                        + unsavedDataArray[i]
3234
                                                                                                                        .getResourceName()
3235
                                                                                                        + " -- "
3236
                                                                                                        + unsavedDataArray[i]
3237
                                                                                                                        .getDescription(),
3238
                                                                                        PluginServices.getText(this,
3239
                                                                                                        "Resource_was_not_saved"),
3240
                                                                                        JOptionPane.ERROR_MESSAGE);
3241

    
3242
                                                        try {
3243
                                                                unsavedDataArray = getUnsavedData();
3244
                                                        } catch (Exception e) {
3245
                                                                // This exception has been registered before
3246
                                                        }
3247
                                                        panel.setUnsavedDataArray(unsavedDataArray);
3248
                                                        return;
3249
                                                }
3250
                                        }
3251
                                        proceed(true);
3252
                                        PluginServices.getMDIManager().closeWindow(panel);
3253
                                }
3254
                        });
3255

    
3256
                        PluginServices.getMDIManager().addWindow(panel);
3257
                        if (proceed) {
3258
                                return JOptionPane.YES_OPTION;
3259
                        } else {
3260
                                return JOptionPane.NO_OPTION;
3261
                        }
3262
                }
3263

    
3264
                private void proceed(boolean proceed) {
3265
                        this.proceed = proceed;
3266
                }
3267

    
3268
        }
3269

    
3270
        public static TerminationProcess getTerminationProcess() {
3271
                return (new Launcher()).new TerminationProcess();
3272
        }
3273

    
3274
        /**
3275
         * Launch the gvSIG package installer.
3276
         * 
3277
         * @throws Exception
3278
         *             if there is any error
3279
         */
3280
        private void doInstall(String[] args) throws Exception {
3281
                String installURL = null;
3282
                String installURLFile = null;
3283
                String gvSIGVersion = null;
3284
                String[] myArgs = new String[3];
3285

    
3286
                Options options = new Options();
3287
                options.addOption("i", "install", false, "install");
3288
                options.addOption("u", "installURL", true, "installURL");
3289
                options.addOption("f", "installURLFile", true, "installURLFile");
3290
                options.addOption("v", "installVersion", true, "installVersion");
3291
                options.addOption("A", "applicationName", true, "applicationName");
3292
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3293
                options.addOption("l", "language", true, "language");
3294

    
3295
                CommandLineParser parser = new PosixParser();
3296
                CommandLine line = null;
3297
                try {
3298
                        line = parser.parse(options, args);
3299
                        boolean hasAllMandatoryOptions = true;
3300
                        if (!line.hasOption("install")) {
3301
                                hasAllMandatoryOptions = false;
3302
                        }
3303
                        if (line.hasOption("installURL")) {
3304
                                installURL = line.getOptionValue("installURL");
3305
                        }
3306
                        if (line.hasOption("installURLFile")) {
3307
                                installURLFile = line.getOptionValue("installURLFile");
3308
                        }
3309
                        if (line.hasOption("installVersion")) {
3310
                                gvSIGVersion = line.getOptionValue("installVersion");
3311
                        }
3312
                        if (line.hasOption("applicationName")) {
3313
                                myArgs[0] = line.getOptionValue("applicationName");
3314
                        } else {
3315
                                hasAllMandatoryOptions = false;
3316
                        }
3317
                        if (line.hasOption("pluginsFolder")) {
3318
                                myArgs[1] = line.getOptionValue("pluginsFolder");
3319
                        } else {
3320
                                hasAllMandatoryOptions = false;
3321
                        }
3322
                        if (line.hasOption("language")) {
3323
                                myArgs[2] = "language=" + line.getOptionValue("language");
3324
                        } else {
3325
                            // prevent null
3326
                            myArgs[2] = "";
3327
                        }
3328
                        if (!hasAllMandatoryOptions) {
3329
                                System.err
3330
                                                .println(Messages.get("usage")
3331
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
3332
                                                                + "[--installURLFile=File] "
3333
                                                                + "--install [--installURL=URL] [language=locale]");
3334
                                return;
3335
                        }
3336
                } catch (ParseException exp) {
3337
                        System.out.println("Unexpected exception:" + exp.getMessage());
3338
                }
3339

    
3340
                initializeApp(myArgs);
3341
                initializeLibraries();
3342
                AndamiConfig config = getAndamiConfig();
3343
                config.setLocaleLanguage(locale.getLanguage());
3344
                config.setLocaleCountry(locale.getCountry());
3345
                config.setLocaleVariant(locale.getVariant());
3346
                
3347
                InstallerManager installerManager = InstallerLocator
3348
                                .getInstallerManager();
3349
                // set the gvSIG version to the install manager, to compose the download
3350
                // URL:
3351
                installerManager.setVersion(gvSIGVersion);
3352

    
3353

    
3354
                // Configure default index download URL
3355
                if (installURL != null) {
3356
                        SwingInstallerLocator.getSwingInstallerManager()
3357
                                        .setDefaultDownloadURL(installURL);
3358
                }
3359

    
3360
                if (installURLFile != null) {
3361
                        // TODO: Convertir a File y pasarlo
3362
                        SwingInstallerLocator.getSwingInstallerManager()
3363
                                        .setDefaultDownloadURL(new File(installURLFile));
3364
                }
3365

    
3366
                // Launch installer
3367
                PluginsManager manager = PluginsLocator.getManager();
3368

    
3369
                File defaultAddonsRepository = PluginsLocator.getManager()
3370
                                .getPluginsFolder();
3371
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3372
                installerManager
3373
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3374

    
3375
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3376
                                .getSwingInstallerManager().createInstallPackageWizard(
3377
                                                manager.getApplicationFolder(),
3378
                                                manager.getInstallFolder());
3379
                installPackageWizard
3380
                                .setWizardActionListener(new InstallerWizardActionListener() {
3381

    
3382
                                        public void finish(InstallerWizardPanel installerWizard) {
3383
                                                System.exit(0);
3384
                                        }
3385

    
3386
                                        public void cancel(InstallerWizardPanel installerWizard) {
3387
                                                System.exit(0);
3388
                                        }
3389
                                });
3390

    
3391
                // the wizard will show the Typical or Advanced mode option.
3392
                installPackageWizard.setAskTypicalOrCustom(true);
3393
                // default packages will be selected.
3394
                installPackageWizard.setSelectDefaultPackages(true);
3395

    
3396

    
3397
                // 1. Create the frame.
3398
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3399

    
3400
                // 2. What happens when the frame closes?
3401
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3402
                Runtime.getRuntime().addShutdownHook(new Thread() {
3403

    
3404
                        @Override
3405
                        public void run() {
3406
                                getTerminationProcess().saveAndamiConfig();
3407
                        }
3408
                });
3409

    
3410
                // 3. Add the installer panel to the frame
3411
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3412

    
3413
                // 4. Size the frame and center on the screen
3414
                frame.pack();
3415
                frame.setLocationRelativeTo(null);
3416

    
3417
                // 5. Show it.
3418
                frame.setVisible(true);
3419
        }
3420

    
3421
        public static String getInformation() {
3422
                PluginsManager pluginmgr = PluginsLocator.getManager();
3423
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3424

    
3425
                StringWriter writer = new StringWriter();
3426

    
3427
                Properties props = System.getProperties();
3428

    
3429
                // OS information
3430
                String osName = props.getProperty("os.name");
3431
                writer.write("OS\n");
3432
                writer.write("    name   : " + osName + "\n");
3433
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3434
                writer.write("    version: " + props.get("os.version") + "\n");
3435
                if (osName.startsWith("Linux")) {
3436
                        try {
3437
                                String[] command = { "lsb_release", "-a" };
3438
                                Process p = Runtime.getRuntime().exec(command);
3439
                                InputStream is = p.getInputStream();
3440
                                BufferedReader reader = new BufferedReader(
3441
                                                new InputStreamReader(is));
3442
                                String line;
3443
                                while ((line = reader.readLine()) != null) {
3444
                                        writer.write("    " + line + "\n");
3445
                                }
3446
                        } catch (Exception ex) {
3447
                                writer
3448
                                                .write("Can't get detailled os information (lsb_release -a).");
3449
                        }
3450
                }
3451

    
3452
                // JRE information
3453
                writer.write("JRE\n");
3454
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3455
                writer.write("    version: " + props.get("java.version") + "\n");
3456
                writer.write("    home   : " + props.get("java.home") + "\n");
3457

    
3458
                writer.write("HTTP Proxy\n");
3459
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3460
                                + "\n");
3461
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3462
                                + "\n");
3463
                writer.write("    http.proxyUserName : "
3464
                                + props.get("http.proxyUserName") + "\n");
3465
                writer.write("    http.proxyPassword : "
3466
                                + props.get("http.proxyPassword") + "\n");
3467

    
3468
                String skinName = "(unknow)";
3469
                try {
3470
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3471
                } catch (Throwable e) {
3472
                        // Ignore
3473
                }
3474
                writer.write("Application\n");
3475
                writer.write("    locale language         : "
3476
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3477
                writer.write("    application forlder     : "
3478
                                + pluginmgr.getApplicationFolder() + "\n");
3479
                writer.write("    install forlder         : "
3480
                                + pluginmgr.getInstallFolder() + "\n");
3481
                writer.write("    application home forlder: "
3482
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3483
                writer.write("    plugins forlder         : "
3484
                                + pluginmgr.getPluginsFolder() + "\n");
3485
                writer.write("    theme                   : "
3486
                                + Launcher.theme.getSource() + "\n");
3487
                // writer.write("    Skin                    : " + skinName + "\n");
3488

    
3489
                try {
3490
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3491
                                        .getPluginsFolder());
3492
                        writer.write("Installed packages\n");
3493
                        for (int i = 0; i < pkgs.length; i++) {
3494
                                writer.write("    ");
3495
                                writer.write(pkgs[i].toStringCompact());
3496
                                writer.write("\n");
3497
                        }
3498
                } catch (Throwable e) {
3499
                        writer.write("Can't get installed package information.");
3500
                }
3501
                return writer.toString();
3502
        }
3503

    
3504
        private void logger_info(String msg) {
3505
                String info[] = msg.split("\n");
3506
                for (int i = 0; i < info.length; i++) {
3507
                        logger.info(info[i]);
3508
                }
3509
        }
3510

    
3511
}