Statistics
| Revision:

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

History | View | Annotate | Download (106 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.commons.io.FileUtils;
106
import org.apache.commons.io.FilenameUtils;
107
import org.apache.log4j.AppenderSkeleton;
108
import org.apache.log4j.PatternLayout;
109
import org.apache.log4j.PropertyConfigurator;
110
import org.apache.log4j.RollingFileAppender;
111
import org.apache.log4j.spi.LoggingEvent;
112
import org.exolab.castor.xml.MarshalException;
113
import org.exolab.castor.xml.ValidationException;
114
import org.gvsig.andami.actioninfo.ActionInfo;
115
import org.gvsig.andami.actioninfo.ActionInfoManager;
116
import org.gvsig.andami.authentication.IAuthentication;
117
import org.gvsig.andami.config.generate.Andami;
118
import org.gvsig.andami.config.generate.AndamiConfig;
119
import org.gvsig.andami.config.generate.Plugin;
120
import org.gvsig.andami.messages.Messages;
121
import org.gvsig.andami.messages.NotificationManager;
122
import org.gvsig.andami.plugins.ExclusiveUIExtension;
123
import org.gvsig.andami.plugins.ExtensionDecorator;
124
import org.gvsig.andami.plugins.IExtension;
125
import org.gvsig.andami.plugins.PluginClassLoader;
126
import org.gvsig.andami.plugins.config.generate.Action;
127
import org.gvsig.andami.plugins.config.generate.ActionTool;
128
import org.gvsig.andami.plugins.config.generate.ComboButton;
129
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
130
import org.gvsig.andami.plugins.config.generate.ComboScale;
131
import org.gvsig.andami.plugins.config.generate.Depends;
132
import org.gvsig.andami.plugins.config.generate.Extension;
133
import org.gvsig.andami.plugins.config.generate.Extensions;
134
import org.gvsig.andami.plugins.config.generate.LabelSet;
135
import org.gvsig.andami.plugins.config.generate.Menu;
136
import org.gvsig.andami.plugins.config.generate.PluginConfig;
137
import org.gvsig.andami.plugins.config.generate.PopupMenu;
138
import org.gvsig.andami.plugins.config.generate.PopupMenus;
139
import org.gvsig.andami.plugins.config.generate.SelectableTool;
140
import org.gvsig.andami.plugins.config.generate.SkinExtension;
141
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
142
import org.gvsig.andami.plugins.config.generate.ToolBar;
143
import org.gvsig.andami.plugins.status.IExtensionStatus;
144
import org.gvsig.andami.plugins.status.IUnsavedData;
145
import org.gvsig.andami.ui.AndamiEventQueue;
146
import org.gvsig.andami.ui.MDIManagerLoadException;
147
import org.gvsig.andami.ui.ToolsWindowManager;
148
import org.gvsig.andami.ui.fonts.FontUtils;
149
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
150
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
151
import org.gvsig.andami.ui.splash.MultiSplashWindow;
152
import org.gvsig.andami.ui.theme.Theme;
153
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
154
import org.gvsig.installer.lib.api.InstallerLocator;
155
import org.gvsig.installer.lib.api.InstallerManager;
156
import org.gvsig.installer.lib.api.PackageInfo;
157
import org.gvsig.installer.lib.api.Version;
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.BaseException;
163
import org.gvsig.tools.exception.ListBaseException;
164
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
165
import org.gvsig.tools.swing.api.ToolsSwingLocator;
166
import org.gvsig.tools.swing.icontheme.IconTheme;
167
import org.gvsig.tools.swing.icontheme.IconThemeManager;
168
import org.gvsig.tools.util.FolderSet;
169
import org.gvsig.tools.util.FolderSet.FolderEntry;
170
import org.gvsig.utils.DateTime;
171
import org.gvsig.utils.XMLEntity;
172
import org.gvsig.utils.xml.XMLEncodingUtils;
173
import org.gvsig.utils.xmlEntity.generate.XmlTag;
174
import org.slf4j.Logger;
175
import org.slf4j.LoggerFactory;
176

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

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

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

    
219
        protected static ListBaseException launcherrors = null;
220

    
221
        protected static Theme theme = null;
222

    
223
        private static final class ProxyAuth extends Authenticator {
224

    
225
                private PasswordAuthentication auth;
226

    
227
                private ProxyAuth(String user, String pass) {
228
                        auth = new PasswordAuthentication(user, pass.toCharArray());
229
                }
230

    
231
                protected PasswordAuthentication getPasswordAuthentication() {
232
                        return auth;
233
                }
234
        }
235

    
236
        private static Launcher launcherInstance;
237

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

    
265
        protected void downloadExtensions(String extDir) {
266
                // do nothing
267
        }
268

    
269
        public static class LaunchException extends ListBaseException {
270

    
271
                private static final long serialVersionUID = 4541192746962684705L;
272

    
273
                public LaunchException() {
274
                        super("Errors in initialization of application.",
275
                                        "_errors_in_initialization_of_application",
276
                                        serialVersionUID);
277
                }
278

    
279
        }
280

    
281
        protected void addError(Throwable ex) {
282
                if (launcherrors == null) {
283
                        launcherrors = new LaunchException();
284
                }
285
                launcherrors.add(ex);
286
        }
287

    
288
        protected void addError(String msg, Throwable cause) {
289
                logger.error(msg, cause);
290
                this.addError(new RuntimeException(msg, cause));
291
        }
292

    
293
        protected void addError(String msg) {
294
                this.addError(msg, null);
295
        }
296

    
297
        public void doMain(String[] args) throws Exception {
298

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

    
304
                initializeApp(args);
305

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

    
311
                        public PermissionCollection getPermissions(CodeSource codesource) {
312
                                Permissions perms = new Permissions();
313
                                perms.add(new AllPermission());
314
                                return (perms);
315
                        }
316

    
317
                        public void refresh() {
318
                        }
319
                });
320

    
321
                /*
322
        new ToolsLibrary().initialize();
323
        new ToolsSwingLibrary().initialize();
324
        new ToolsSwingDefaultImplLibrary().initialize();
325
        */
326
        
327
        new DefaultLibrariesInitializer().fullInitialize(true);
328

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

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

    
351
                // Mostrar la ventana de inicio
352
                Frame f = new Frame();
353
                splashWindow = new MultiSplashWindow(f, theme, 190);
354

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

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

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

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

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

    
405
                // 5. Initialize libraries
406
                splashWindow.process(50, PluginServices.getText(Launcher.class,
407
                                "SplashWindow.initialize_libraries"));
408
                initializeLibraries();
409

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

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

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

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

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

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

    
445
                SwingUtilities.invokeAndWait(new Runnable() {
446

    
447
                        public void run() {
448
                                frame.init();
449
                        }
450
                });
451
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
452

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

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

    
466
                        public void run() {
467
                                initializeExtensions();
468
                        }
469
                });
470

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

    
476
                        public void run() {
477
                                initializeExclusiveUIExtension();
478
                        }
479
                });
480
                frame.setClassesExtensions(classesExtensions);
481

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

    
487
                        public void run() {
488
                                installPluginsControls();
489

    
490
                        }
491
                });
492

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

    
498
                        public void run() {
499
                                installPluginsMenus();
500

    
501
                        }
502
                });
503

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

    
509
                        public void run() {
510
                                installPluginsLabels();
511

    
512
                        }
513
                });
514

    
515
                // 18. Se instalan los bookmarks de los plugins
516

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

    
522
                /* 
523
                 * Initialize installer local repository folders 
524
                 */
525
                initializeLocalAddOnRepositoryFolders();
526

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

    
532
                        public void run() {
533
                                postInitializeExtensions();
534

    
535
                        }
536
                });
537

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

    
543
                SwingUtilities.invokeAndWait(new Runnable() {
544

    
545
                        public void run() {
546
                                frame.enableControls();
547
                        }
548
                });
549

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

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

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

    
561
        }
562

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

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

    
568
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
569
                installerManager.setDefaultLocalAddonRepository(defaultAddonsRepository);
570
                
571
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
572
                FolderSet fset = iconManager.getRepository();
573
                Iterator<FolderSet.FolderEntry> it = fset.iterator();
574
                while( it.hasNext() ) {
575
                        FolderEntry entry = it.next();
576
                        installerManager.addLocalAddonRepository(entry.getFolder());
577
                }
578
        }
579
        
580

    
581
        
582
        /**
583
     * 
584
     */
585
        private void initializeLibraries() {
586
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
587
                                pluginsOrdered.size() + 1);
588
                classLoaders.add(getClass().getClassLoader());
589
                Iterator<String> iter = pluginsOrdered.iterator();
590

    
591
                logger.debug("Initializing plugins libraries: ");
592
                while (iter.hasNext()) {
593
                        String pName = (String) iter.next();
594
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
595
                        classLoaders.add(ps.getClassLoader());
596
                }
597

    
598
                // Create the libraries initializer and
599
                // initialize the plugin libraries
600
                new DefaultLibrariesInitializer(classLoaders
601
                                .toArray(new ClassLoader[classLoaders.size()]))
602
                                .fullInitialize(true);
603

    
604
                // Remove them all, we don't need them anymore
605
                classLoaders.clear();
606
                classLoaders = null;
607
        }
608

    
609
        /**
610
         * @param args
611
         * @throws IOException
612
         * @throws ConfigurationException
613
         */
614
        private void initializeApp(String[] args) throws IOException,
615
                        ConfigurationException {
616
                if (!validJVM()) {
617
                        System.exit(-1);
618
                }
619

    
620
                // Clean temporal files
621
                Utilities.cleanUpTempFiles();
622

    
623
                appName = args[0];
624

    
625
                getOrCreateConfigFolder();
626

    
627
                configureLogging(appName);
628

    
629
                loadAndamiConfig(args[1]);
630

    
631
                // Hacemos visibles los argumentos como una propiedad est?tica
632
                // de plugin services para quien lo quiera usar (por ejemplo, para
633
                // cargar un proyecto por l?nea de comandos)
634
                PluginServices.setArguments(args);
635

    
636
                configureLocales(args);
637

    
638
                logger.info("Load and initialize andami and plugins libraries");
639
                // LibrariesInitializer libsInitializer =
640
                // new DefaultLibrariesInitializer();
641
                // libsInitializer.initialize(true);
642
                // libsInitializer.postInitialize(true);
643

    
644
                logger.info("Configure LookAndFeel");
645
                configureLookAndFeel();
646
        }
647

    
648
        /**
649
     * 
650
     */
651
        private void configureLookAndFeel() {
652
                // Se pone el lookAndFeel
653
                try {
654
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
655
                        if (lookAndFeel == null) {
656
                                lookAndFeel = getDefaultLookAndFeel();
657
                        }
658
                        UIManager.setLookAndFeel(lookAndFeel);
659
                } catch (Exception e) {
660
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
661
                }
662
                FontUtils.initFonts();
663
        }
664

    
665
        /**
666
         * @param args
667
         * @throws ConfigurationException
668
         */
669
        private void loadAndamiConfig(String pluginFolder)
670
                        throws ConfigurationException {
671
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
672
                // locale
673
                // Buscar actualizaci?nes al comenzar
674
                // Andami
675
                // Plugins
676
                // Directorio de las extensiones
677
                andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
678
                andamiConfigFromXML(andamiConfigPath);
679
                andamiConfig.setPluginsDirectory(pluginFolder);
680
        }
681

    
682
        /**
683
     * 
684
     */
685
        private void getOrCreateConfigFolder() {
686
                // Create application configuration folder
687
                appHomeDir = System.getProperty(appName + ".home");
688
                if (appHomeDir == null) {
689
                        appHomeDir = System.getProperty("user.home");
690
                }
691

    
692
                appHomeDir += File.separator + appName;
693
                File parent = new File(appHomeDir);
694
                parent.mkdirs();
695
        }
696

    
697
        /**
698
         * @param args
699
         * @throws IOException
700
         */
701
        private void configureLogging(String appName) throws IOException {
702
                // Configurar el log4j
703
                Launcher.class.getClassLoader().getResource(".");
704
                PropertyConfigurator.configure("log4j.properties");
705

    
706
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
707
                RollingFileAppender fa = new RollingFileAppender(l, appHomeDir
708
                                + File.separator + appName + ".log", false);
709
                fa.setMaxFileSize("512KB");
710
                fa.setMaxBackupIndex(3);
711
                org.apache.log4j.Logger.getRootLogger().addAppender(fa);
712
        }
713

    
714
        private class NotificationAppender extends AppenderSkeleton {
715

    
716
                @Override
717
                protected void append(LoggingEvent event) {
718
                        if (event.getLevel() == org.apache.log4j.Level.ERROR
719
                                        || event.getLevel() == org.apache.log4j.Level.FATAL) {
720
                                NotificationManager.dispatchError(event.getRenderedMessage(),
721
                                                null);
722
                                return;
723
                        }
724
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
725
                        // NotificationManager.dispatchWarning(event.getRenderedMessage(),
726
                        // null);
727
                        // return;
728
                        // }
729
                }
730

    
731
                @Override
732
                public void close() {
733
                        // TODO Auto-generated method stub
734

    
735
                }
736

    
737
                @Override
738
                public boolean requiresLayout() {
739
                        // TODO Auto-generated method stub
740
                        return false;
741
                }
742

    
743
        }
744

    
745
        /**
746
         * Return the directory applicaction is installed.
747
         */
748
        public static String getApplicationDirectory() {
749
                return getApplicationFolder().getAbsolutePath();
750
        }
751
        
752
    public static File getApplicationFolder() {
753
        // TODO: check if there is a better way to handle this
754
        return new File(System.getProperty("user.dir"));
755
    }
756

    
757
        private void registerIcons() {
758
                IconTheme theme = PluginServices.getIconTheme();
759
                ClassLoader loader = Launcher.class.getClassLoader();        
760
                
761
                String[][] icons = {
762
                                // MultiSplashWindow
763
                                { "main", "splash-default" },
764
                                // NewStatusBar
765
                                { "main", "statusbar-info" },
766
                                { "main", "statusbar-warning" },
767
                                { "main", "statusbar-error" }
768
                };
769
                for( int i=0; i<icons.length; i++) {
770
                        try {
771
                                IconThemeHelper.registerIcon(icons[i][0], icons[i][1], Launcher.class);
772
                        } catch(Exception e) {
773
                                logger.info("Can't register icon '"+icons[i][0]+"' ("+icons[i][1]+").");
774
                        }
775
                }                
776
                theme.setDefaultIcon(loader.getResource("images/main/default-icon.png" ));
777
        }
778

    
779
        /**
780
         * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de la
781
         * aplicaci?n.
782
         * 
783
         * @return Theme
784
         */
785
        private Theme getTheme(String pluginsDirectory) {
786
                File themeFile = null;
787
                Theme theme = new Theme();
788

    
789
                // Try to get theme from args
790
                String name = PluginServices.getArgumentByName("andamiTheme");
791
                if (name != null) {
792
                        themeFile = new File(name);
793
                        logger.info("search andami-theme in {}", themeFile
794
                                        .getAbsolutePath());
795
                        if (themeFile.exists()) {
796
                                theme.readTheme(themeFile);
797
                                logger.info("andami-theme found in {}", themeFile
798
                                                .getAbsolutePath());
799
                                return theme;
800
                        }
801
                }
802

    
803
                // Try to get theme from a plugin
804
                File pluginsDir = new File(pluginsDirectory);
805
                if (!pluginsDir.isAbsolute()) {
806
                        pluginsDir = new File(System.getProperty("user.dir"),
807
                                        pluginsDirectory);
808
                }
809
                if (pluginsDir.exists()) {
810
                        logger.info("search andami-theme in plugins folder.");
811
                        File[] pluginDirs = pluginsDir.listFiles();
812
                        if (pluginDirs.length > 0) {
813
                                for (int i = 0; i < pluginDirs.length; i++) {
814
                                        File pluginThemeFile = new File(pluginDirs[i], "theme"
815
                                                        + File.separator + "andami-theme.xml");
816
                                        if (pluginThemeFile.exists()) {
817
                                                themeFile = pluginThemeFile;
818
                                                // This if is a hack to allow more themes than the
819
                                                // one available in org.gvsig.app. Remove this
820
                                                // when a the theme format is changed to allow for
821
                                                // priorities
822
                                                if (!"org.gvsig.app".equals(pluginDirs[i].getName())) {
823
                                                        break;
824
                                                }
825
                                        }
826
                                }
827
                        }
828
                }
829

    
830
                // The theme file will be the one into a plugin or by default the one
831
                // in the org.gvsig.app plugin
832
                if (themeFile != null && themeFile.exists()) {
833
                        theme.readTheme(themeFile);
834
                        logger.info("andami-theme found in plugin {}", themeFile
835
                                        .getAbsolutePath());
836
                        return theme;
837
                }
838

    
839
                // Try to get theme from dir gvSIG in user home
840
                themeFile = new File(getAppHomeDir(), "theme" + File.separator
841
                                + "andami-theme.xml");
842
                logger.info("search andami-theme in user's home {}", themeFile
843
                                .getAbsolutePath());
844
                if (themeFile.exists()) {
845
                        theme.readTheme(themeFile);
846
                        logger.info("andami-theme found in user's home {}", themeFile
847
                                        .getAbsolutePath());
848
                        return theme;
849
                }
850

    
851
                // Try to get theme from the instalation dir of gvSIG.
852
                themeFile = new File(getApplicationDirectory(), "theme"
853
                                + File.separator + "andami-theme.xml");
854
                logger.info("search andami-theme in installation folder {}", themeFile
855
                                .getAbsolutePath());
856
                if (themeFile.exists()) {
857
                        theme.readTheme(themeFile);
858
                        logger.info("andami-theme found in instalation folder {}",
859
                                        themeFile.getAbsolutePath());
860
                        return theme;
861
                }
862
                logger.info("Apply default andami-theme.");
863
                return theme;
864
        }
865

    
866
        /**
867
         * Establece los datos que ten?amos guardados respecto de la configuraci?n
868
         * del proxy.
869
         */
870
        private void configureProxy() {
871
                String host = prefs.get("firewall.http.host", "");
872
                String port = prefs.get("firewall.http.port", "");
873

    
874
                System.getProperties().put("http.proxyHost", host);
875
                System.getProperties().put("http.proxyPort", port);
876

    
877
                // Ponemos el usuario y clave del proxy, si existe
878
                String proxyUser = prefs.get("firewall.http.user", null);
879
                String proxyPassword = prefs.get("firewall.http.password", null);
880
                if (proxyUser != null) {
881
                        System.getProperties().put("http.proxyUserName", proxyUser);
882
                        System.getProperties().put("http.proxyPassword", proxyPassword);
883

    
884
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
885
                } else {
886
                        Authenticator.setDefault(new ProxyAuth("", ""));
887
                }
888
        }
889

    
890
        /**
891
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal
892
         * de Andami. TODO Pendiente de ver como se asigna un pluginServices para el
893
         * launcher.
894
         * 
895
         * @author LWS
896
         */
897
        private void restoreMDIStatus(XMLEntity xml) {
898
                if (xml == null) {
899
                        xml = new XMLEntity();
900
                }
901
                // restore frame size
902
                Dimension sz = new Dimension(700, 580);
903
                if (xml.contains("MDIFrameSize")) {
904
                        int[] wh = xml.getIntArrayProperty("MDIFrameSize");
905
                        sz = new Dimension(wh[0], wh[1]);
906
                }
907
                frame.setSize(sz);
908
                // restore frame location
909
                Point pos = new Point(10, 10);
910
                if (xml.contains("MDIFramePos")) {
911
                        int[] xy = xml.getIntArrayProperty("MDIFramePos");
912
                        pos = new Point(xy[0], xy[1]);
913
                }
914
                frame.setLocation(pos);
915

    
916
                // restore frame status (Maximized, minimized, etc);
917
                int state = java.awt.Frame.MAXIMIZED_BOTH;
918
                if (xml.contains("MDIFrameState")) {
919
                        state = xml.getIntProperty("MDIFrameState");
920
                }
921
                frame.setExtendedState(state);
922
        }
923

    
924
        private XMLEntity saveMDIStatus() {
925
                XMLEntity xml = new XMLEntity();
926
                // save frame size
927
                int[] wh = new int[2];
928
                wh[0] = frame.getWidth();
929
                wh[1] = frame.getHeight();
930
                xml.putProperty("MDIFrameSize", wh);
931
                // save frame location
932
                int[] xy = new int[2];
933
                xy[0] = frame.getX();
934
                xy[1] = frame.getY();
935
                xml.putProperty("MDIFramePos", xy);
936
                // save frame status
937
                xml.putProperty("MDIFrameState", frame.getExtendedState());
938
                return xml;
939
        }
940

    
941
        private boolean validJVM() {
942
                char thirdCharacter = System.getProperty("java.version").charAt(2);
943
                if (thirdCharacter < '4') {
944
                        return false;
945
                } else {
946
                        return true;
947
                }
948
        }
949

    
950
        private void loadPluginsPersistence() throws ConfigurationException {
951
                XMLEntity entity = persistenceFromXML();
952

    
953
                for (int i = 0; i < entity.getChildrenCount(); i++) {
954
                        XMLEntity plugin = entity.getChild(i);
955
                        String pName = plugin
956
                                        .getStringProperty("com.iver.andami.pluginName");
957

    
958
                        if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
959
                                pName = "org.gvsig.app";
960
                        }
961
                        if (pluginsServices.get(pName) != null) {
962
                                ((PluginServices) pluginsServices.get(pName))
963
                                                .setPersistentXML(plugin);
964
                        } else {
965
                                if (pName.startsWith("Andami.Launcher")) {
966
                                        restoreMDIStatus(plugin);
967
                                }
968
                        }
969
                }
970
        }
971

    
972
        /**
973
         * Salva la persistencia de los plugins.
974
         * 
975
         * @author LWS
976
         */
977
        private void savePluginPersistence() {
978
                Iterator<String> i = pluginsConfig.keySet().iterator();
979

    
980
                XMLEntity entity = new XMLEntity();
981

    
982
                while (i.hasNext()) {
983
                        String pName = i.next();
984
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
985
                        XMLEntity ent = ps.getPersistentXML();
986

    
987
                        if (ent != null) {
988
                                ent.putProperty("com.iver.andami.pluginName", pName);
989
                                entity.addChild(ent);
990
                        }
991
                }
992
                XMLEntity ent = saveMDIStatus();
993
                if (ent != null) {
994
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
995
                        entity.addChild(ent);
996
                }
997
                try {
998
                        persistenceToXML(entity);
999
                } catch (ConfigurationException e1) {
1000
                        this
1001
                                        .addError(
1002
                                                        Messages
1003
                                                                        .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1004
                                                        e1);
1005
                }
1006
        }
1007

    
1008
        private void installPluginsLabels() {
1009
                Iterator<String> i = pluginsConfig.keySet().iterator();
1010

    
1011
                while (i.hasNext()) {
1012
                        String name = i.next();
1013
                        PluginConfig pc = pluginsConfig.get(name);
1014
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1015

    
1016
                        LabelSet[] ls = pc.getLabelSet();
1017

    
1018
                        for (int j = 0; j < ls.length; j++) {
1019
                                PluginClassLoader loader = ps.getClassLoader();
1020

    
1021
                                try {
1022
                                        Class clase = loader.loadClass(ls[j].getClassName());
1023
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
1024
                                } catch (ClassNotFoundException e) {
1025
                                        this.addError(
1026
                                                        Messages.getString("Launcher.labelset_class"), e);
1027
                                }
1028
                        }
1029
                }
1030
        }
1031

    
1032
        private String configureSkin(XMLEntity xml, String defaultSkin) {
1033
                if (defaultSkin == null) {
1034
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
1035
                                if (xml.getChild(i).contains("Skin-Selected")) {
1036
                                        String className = xml.getChild(i).getStringProperty(
1037
                                                        "Skin-Selected");
1038
                                        return className;
1039
                                }
1040
                        }
1041
                }
1042
                // return "com.iver.core.mdiManager.NewSkin";
1043
                return defaultSkin;
1044
        }
1045

    
1046
        private void fixSkin(SkinExtension skinExtension,
1047
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1048
                // now insert the skin selected.
1049
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1050
                // MDIManagerFactory.setSkinExtension(se,
1051
                // ps.getClassLoader());
1052

    
1053
                Class<? extends IExtension> skinClass;
1054

    
1055
                try {
1056
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1057
                                        .loadClass(skinExtension.getClassName());
1058

    
1059
                        IExtension skinInstance = skinClass.newInstance();
1060
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1061
                                        skinInstance, ExtensionDecorator.INACTIVE);
1062
                        classesExtensions.put(skinClass, newExtensionDecorator);
1063
                } catch (ClassNotFoundException e) {
1064
                        logger.error(Messages
1065
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1066
                                        e);
1067
                        throw new MDIManagerLoadException(e);
1068
                } catch (InstantiationException e) {
1069
                        logger
1070
                                        .error(
1071
                                                        Messages
1072
                                                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1073
                                                        e);
1074
                        throw new MDIManagerLoadException(e);
1075
                } catch (IllegalAccessException e) {
1076
                        logger
1077
                                        .error(
1078
                                                        Messages
1079
                                                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1080
                                                        e);
1081
                        throw new MDIManagerLoadException(e);
1082
                }
1083

    
1084
        }
1085

    
1086
        /**
1087
         * DOCUMENT ME!
1088
         * 
1089
         * @throws MDIManagerLoadException
1090
         */
1091
        private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1092
                XMLEntity entity = null;
1093
                try {
1094
                        entity = persistenceFromXML();
1095
                } catch (ConfigurationException e1) {
1096
                        // TODO Auto-generated catch block
1097
                        e1.printStackTrace();
1098
                }
1099
                Iterator<String> i = pluginsConfig.keySet().iterator();
1100

    
1101
                SkinExtension skinExtension = null;
1102
                PluginClassLoader pluginClassLoader = null;
1103
                List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1104
                while (i.hasNext()) {
1105
                        String name = i.next();
1106
                        PluginConfig pc = pluginsConfig.get(name);
1107
                        PluginServices ps = pluginsServices.get(name);
1108

    
1109
                        if (pc.getExtensions().getSkinExtension() != null) {
1110
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1111
                                // logger.warn(Messages.getString(
1112
                                // "Launcher.Dos_skin_extension"));
1113
                                // }
1114

    
1115
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1116
                                for (int numExten = 0; numExten < se.length; numExten++) {
1117
                                        skinExtensions.add(se[numExten]);
1118
                                }
1119
                                for (int j = 0; j < se.length; j++) {
1120
                                        String configuredSkin = this.configureSkin(entity,
1121
                                                        defaultSkin);
1122
                                        if ((configuredSkin != null)
1123
                                                        && configuredSkin.equals(se[j].getClassName())) {
1124
                                                skinExtension = se[j];
1125
                                                pluginClassLoader = ps.getClassLoader();
1126
                                        }
1127
                                }
1128
                        }
1129
                }
1130

    
1131
                if ((skinExtension != null) && (pluginClassLoader != null)) {
1132
                        // configured skin was found
1133
                        fixSkin(skinExtension, pluginClassLoader);
1134
                } else {
1135
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1136
                                // try first NewSkin (from CorePlugin)
1137
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
1138
                        } else if (skinExtensions.size() > 0) {
1139
                                // try to load the first skin found
1140
                                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1141
                                skinPlugin((String) se.getClassName());
1142
                        } else {
1143
                                throw new MDIManagerLoadException("No Skin-Extension installed");
1144
                        }
1145
                }
1146

    
1147
        }
1148

    
1149
        private static void frameIcon(Theme theme) {
1150
                Iterator<String> i = pluginsConfig.keySet().iterator();
1151

    
1152
                while (i.hasNext()) {
1153
                        String pName = i.next();
1154
                        PluginConfig pc = pluginsConfig.get(pName);
1155
                        if (pc.getIcon() != null) {
1156
                                if (theme.getIcon() != null) {
1157
                                        frame.setIconImage(theme.getIcon().getImage());
1158
                                } else {
1159

    
1160
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1161
                                                        pc.getIcon().getSrc());
1162
                                        frame.setIconImage(icon.getImage());
1163

    
1164
                                }
1165
                                if (theme.getName() != null) {
1166
                                        frame.setTitlePrefix(theme.getName());
1167
                                } else {
1168
                                        frame.setTitlePrefix(pc.getIcon().getText());
1169
                                }
1170
                                if (theme.getBackgroundImage() != null) {
1171

    
1172
                                        PluginServices.getMDIManager().setBackgroundImage(
1173
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1174
                                }
1175
                        }
1176
                }
1177
        }
1178

    
1179
        private void initializeExtensions() {
1180

    
1181
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1182
                                pluginsOrdered.size());
1183
                classLoaders.add(getClass().getClassLoader());
1184
                Iterator<String> iter = pluginsOrdered.iterator();
1185

    
1186
                // logger.debug("Initializing plugins libraries: ");
1187
                // while (iter.hasNext()) {
1188
                // String pName = (String) iter.next();
1189
                // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1190
                // classLoaders.add(ps.getClassLoader());
1191
                // }
1192
                //
1193
                // // Create the libraries initializer and
1194
                // // initialize the plugin libraries
1195
                // new DefaultLibrariesInitializer(
1196
                // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1197
                // .fullInitialize();
1198
                //
1199
                // // Remove them all, we don't need them anymore
1200
                // classLoaders.clear();
1201
                // classLoaders = null;
1202

    
1203
                logger.info("Initializing plugins: ");
1204
                // iter = pluginsOrdered.iterator();
1205
                while (iter.hasNext()) {
1206
                        String pName = (String) iter.next();
1207
                        logger.info("Initializing plugin " + pName);
1208
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1209
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1210

    
1211
                        Extension[] exts = pc.getExtensions().getExtension();
1212

    
1213
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1214
                                        new ExtensionComparator());
1215

    
1216
                        for (int j = 0; j < exts.length; j++) {
1217
                                if (!exts[j].getActive()) {
1218
                                        continue;
1219
                                }
1220

    
1221
                                if (orderedExtensions.contains(exts[j])) {
1222
                                        logger.warn("Two extensions with the same priority ("
1223
                                                        + exts[j].getClassName() + ")");
1224
                                }
1225

    
1226
                                orderedExtensions.add(exts[j]);
1227
                        }
1228

    
1229
                        Iterator<Extension> e = orderedExtensions.iterator();
1230

    
1231
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1232
                        while (e.hasNext()) {
1233
                                Extension extension = e.next();
1234
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1235

    
1236
                                try {
1237
                                        logger.info("Initializing " + extension.getClassName()
1238
                                                        + "...");
1239
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1240
                                                        .getClassLoader().loadClass(
1241
                                                                        extension.getClassName());
1242
                                        extensionInstance = extensionClass.newInstance();
1243

    
1244
                                        // CON DECORATOR
1245
                                        // ANTES: classesExtensions.put(extensionClass,
1246
                                        // extensionInstance);
1247
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1248
                                        // instancia para
1249
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por
1250
                                        // ejemplo)
1251
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos
1252
                                        // como par?metro
1253
                                        // la extensi?n original que acabamos de crear
1254
                                        // 0-> Inactivo, controla la extension
1255
                                        // 1-> Siempre visible
1256
                                        // 2-> Invisible
1257
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1258
                                                        extensionInstance, ExtensionDecorator.INACTIVE);
1259
                                        classesExtensions
1260
                                                        .put(extensionClass, newExtensionDecorator);
1261

    
1262
                                        extensionInstance.initialize();
1263
                                        extensions.add(extensionInstance);
1264

    
1265
                                } catch (NoClassDefFoundError e1) {
1266
                                        this.addError("Can't find class extension ("
1267
                                                        + extension.getClassName() + ")", e1);
1268
                                } catch (Throwable e1) {
1269
                                        this.addError("Can't initialize extension '"
1270
                                                        + extension.getClassName() + "'.", e1);
1271
                                }
1272
                        }
1273
                }
1274
        }
1275

    
1276
        private void postInitializeExtensions() {
1277
                logger.info("PostInitializing extensions: ");
1278

    
1279
                for (int i = 0; i < extensions.size(); i++) {
1280
                        org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1281
                                        .get(i);
1282
                        logger.info("PostInitializing "
1283
                                        + extensionInstance.getClass().getName() + "...");
1284
                        try {
1285
                                extensionInstance.postInitialize();
1286
                        } catch (Throwable ex) {
1287
                                this.addError("postInitialize of extension '"
1288
                                                + extensionInstance.getClass().getName() + "' failed",
1289
                                                ex);
1290
                        }
1291
                }
1292
        }
1293

    
1294
        private void registerActionOfExtensions(ActionInfoManager actionManager,
1295
                        Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1296
                ActionInfo actionInfo;
1297
                while (extensiones.hasMoreElements()) {
1298
                        SkinExtensionType extension = extensiones.nextElement();
1299
                        Class<? extends IExtension> classExtension;
1300
                        try {
1301
                                classExtension = (Class<? extends IExtension>) loader
1302
                                                .loadClass(extension.getClassName());
1303

    
1304
                                Enumeration<Action> actions = extension.enumerateAction();
1305
                                while (actions.hasMoreElements()) {
1306
                                        Action action = actions.nextElement();
1307
                                        if (action.getName() == null) {
1308
                                                logger.info("invalid action name (null) in "+ extension.getClassName()+" of "+ loader.toString());
1309
                                        } else {
1310
                                                actionInfo = actionManager.createAction(
1311
                                                                classExtension, action.getName(),
1312
                                                                action.getLabel(), action.getActionCommand(),
1313
                                                                action.getIcon(), null, action.getPosition(),
1314
                                                                action.getTooltip());
1315
                                                actionManager.registerAction(actionInfo);
1316
                                                if( action.getPosition() < 100000000 ) {
1317
                                                        logger.info("Invalid position in action ("+ actionInfo.toString()+ ").");
1318
                                                        action.setPosition( action.getPosition() + 1000000000);
1319
                                                }
1320
                                        }
1321
                                }
1322

    
1323
                                Enumeration<Menu> menus = extension.enumerateMenu();
1324
                                while (menus.hasMoreElements()) {
1325
                                        Menu menu = menus.nextElement();
1326
                                        if (!menu.getIs_separator() ) {
1327
                                                actionInfo = actionManager.createAction(
1328
                                                        classExtension, menu.getName(), menu.getText(),
1329
                                                        menu.getActionCommand(), menu.getIcon(),
1330
                                                        menu.getKey(), menu.getPosition(),
1331
                                                        menu.getTooltip());
1332
                                                actionInfo = actionManager.registerAction(actionInfo);
1333
                                                if (actionInfo != null) {
1334
                                                        menu.setActionCommand(actionInfo.getCommand());
1335
                                                        menu.setTooltip(actionInfo.getTooltip());
1336
                                                        menu.setIcon(actionInfo.getIconName());
1337
                                                        menu.setPosition(actionInfo.getPosition());
1338
                                                        menu.setKey(actionInfo.getAccelerator());
1339
                                                        menu.setName(actionInfo.getName());
1340
                                                }
1341
                                        } 
1342
                                        if( menu.getPosition() < 100000000 ) {
1343
                                                logger.info("Invalid position in menu ("+ menu.getText() + ").");
1344
                                                menu.setPosition( menu.getPosition() + 1000000000);
1345
                                        }
1346

    
1347
                                }
1348
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1349
                                while (toolBars.hasMoreElements()) {
1350
                                        ToolBar toolBar = toolBars.nextElement();
1351

    
1352
                                        Enumeration<ActionTool> actionTools = toolBar
1353
                                                        .enumerateActionTool();
1354
                                        while (actionTools.hasMoreElements()) {
1355
                                                ActionTool actionTool = actionTools.nextElement();
1356
                                                actionInfo = actionManager.createAction(
1357
                                                                classExtension, actionTool.getName(),
1358
                                                                actionTool.getText(),
1359
                                                                actionTool.getActionCommand(),
1360
                                                                actionTool.getIcon(),
1361
                                                                null,
1362
                                                                actionTool.getPosition(),
1363
                                                                actionTool.getTooltip());
1364
                                                actionInfo = actionManager.registerAction(actionInfo);
1365
                                                if (actionInfo != null) {
1366
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1367
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1368
                                                        actionTool.setIcon(actionInfo.getIconName());
1369
                                                        actionTool.setPosition(actionInfo.getPosition());
1370
                                                        actionTool.setName(actionInfo.getName());
1371
                                                }
1372
                                        }
1373

    
1374
                                        Enumeration<SelectableTool> selectableTool = toolBar
1375
                                                        .enumerateSelectableTool();
1376
                                        while (selectableTool.hasMoreElements()) {
1377
                                                SelectableTool actionTool = selectableTool
1378
                                                                .nextElement();
1379
                                                actionInfo = actionManager.createAction(
1380
                                                                classExtension, actionTool.getName(),
1381
                                                                actionTool.getText(),
1382
                                                                actionTool.getActionCommand(),
1383
                                                                actionTool.getIcon(),
1384
                                                                actionTool.getEnableText(),
1385
                                                                actionTool.getPosition(),
1386
                                                                actionTool.getTooltip());
1387
                                                actionInfo = actionManager.registerAction(actionInfo);
1388
                                                if (actionInfo != null) {
1389
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1390
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1391
                                                        actionTool.setIcon(actionInfo.getIconName());
1392
                                                        actionTool.setPosition(actionInfo.getPosition());
1393
                                                        actionTool.setName(actionInfo.getName());
1394
                                                }
1395
                                        }
1396
                                }
1397
                        } catch (ClassNotFoundException e) {
1398
                                logger.warn(
1399
                                                "Can't register actions of extension '"
1400
                                                                + extension.getClassName() + "'", e);
1401
                        }
1402
                }
1403
        }
1404
        
1405
        @SuppressWarnings("unchecked")
1406
        private void registerActions() {
1407
                logger.info("registerActions");
1408

    
1409
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1410
                Iterator<String> it = pluginsConfig.keySet().iterator();
1411

    
1412
                while (it.hasNext()) {
1413
                        String pluginName = it.next();
1414
                        PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1415
                        PluginServices pluginService = pluginsServices.get(pluginName);
1416
                        PluginClassLoader loader =  pluginService.getClassLoader();
1417

    
1418
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1419

    
1420
                        Extensions extensionConfig = pluginConfig.getExtensions();
1421
                        
1422
                        
1423
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1424
                        registerActionOfExtensions(actionManager, extensiones, loader);
1425

    
1426
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1427
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1428

    
1429
                        PopupMenus pluginPopupMenus = pluginConfig.getPopupMenus();
1430
                        if (pluginPopupMenus != null) {
1431
                                PopupMenu[] menus1 = pluginPopupMenus.getPopupMenu();
1432
                                for (int j = 0; j < menus1.length; j++) {
1433
                                        PopupMenu popupMenu = menus1[j];
1434
                                        Enumeration<Menu> menus2 = popupMenu.enumerateMenu();
1435
                                        while (menus2.hasMoreElements()) {
1436
                                                Menu menu = menus2.nextElement();
1437
                                                if (!menu.getIs_separator() ) {
1438
                                                        if( menu.getName() == null) {   
1439
                                                                logger.info("Null name for popmenu '"+menu.getText()+"' in plugin "+ pluginService.getPluginName() );
1440
                                                        } else {
1441
                                                                ActionInfo actionInfo = actionManager.getAction(menu.getName());
1442
                                                                if( actionInfo!=null ) {
1443
                                                                        menu.setActionCommand(actionInfo.getCommand());
1444
                                                                        menu.setTooltip(actionInfo.getTooltip());
1445
                                                                        menu.setIcon(actionInfo.getIconName());
1446
                                                                        menu.setPosition(actionInfo.getPosition());
1447
                                                                        menu.setText( actionInfo.getLabel());
1448
                                                                        menu.setKey(actionInfo.getAccelerator());
1449
                                                                }
1450
                                                        }
1451
                                                }
1452
                                        }
1453
                                }
1454
                        }
1455
                        
1456

    
1457
                }
1458
        }
1459
        
1460

    
1461
        private TreeSet<SortableMenu> getOrderedMenus() { 
1462

    
1463
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1464
                                new MenuComparator());
1465

    
1466
                Iterator<String> i = pluginsConfig.keySet().iterator();
1467

    
1468
                while (i.hasNext()) {
1469
                        String pName = i.next();
1470
                        try {
1471
                                PluginServices ps = pluginsServices.get(pName);
1472
                                PluginConfig pc = pluginsConfig.get(pName);
1473

    
1474
                                Extension[] exts = pc.getExtensions().getExtension();
1475

    
1476
                                for (int j = 0; j < exts.length; j++) {
1477
                                        if (!exts[j].getActive()) {
1478
                                                continue;
1479
                                        }
1480

    
1481
                                        Menu[] menus = exts[j].getMenu();
1482

    
1483
                                        for (int k = 0; k < menus.length; k++) {
1484
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1485
                                                                exts[j], menus[k]);
1486

    
1487
                                                if (orderedMenus.contains(sm)) {
1488
                                                        this
1489
                                                                        .addError(Messages
1490
                                                                                        .getString("Launcher.Two_menus_with_the_same_position")
1491
                                                                                        + " - "
1492
                                                                                        + menus[k].getText()
1493
                                                                                        + " - " + exts[j].getClassName());
1494
                                                }
1495

    
1496
                                                orderedMenus.add(sm);
1497
                                        }
1498
                                }
1499

    
1500
                                // Se instalan las extensiones de MDI
1501
                                SkinExtension[] skinExts = pc.getExtensions()
1502
                                                .getSkinExtension();
1503
                                for (int j = 0; j < skinExts.length; j++) {
1504

    
1505
                                        if (skinExts[j] != null) {
1506
                                                Menu[] menu = skinExts[j].getMenu();
1507

    
1508
                                                for (int k = 0; k < menu.length; k++) {
1509
                                                        SortableMenu sm = new SortableMenu(ps
1510
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1511

    
1512
                                                        if (orderedMenus.contains(sm)) {
1513
                                                                this
1514
                                                                                .addError(Messages
1515
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1516
                                                                                                + skinExts[j].getClassName());
1517
                                                        }
1518

    
1519
                                                        orderedMenus.add(sm);
1520
                                                }
1521
                                        }
1522
                                }
1523

    
1524
                        } catch (Throwable e) {
1525
                                addError("Error initializing menus of plugin '" + pName + "'",
1526
                                                e);
1527
                        }
1528

    
1529
                }
1530

    
1531
                return orderedMenus;
1532
        }
1533

    
1534
        private void installPluginsMenus() {
1535
                logger.info("installPluginsMenus");
1536

    
1537
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1538

    
1539
                // Se itera por los menus ordenados
1540
                Iterator<SortableMenu> e = orderedMenus.iterator();
1541

    
1542
                // Se ordenan los menues
1543
                while (e.hasNext()) {
1544
                        try {
1545
                                SortableMenu sm = e.next();
1546

    
1547
                                logger.info(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1548
                                
1549
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1550

    
1551
                        } catch (ClassNotFoundException ex) {
1552
                                this
1553
                                                .addError(
1554
                                                                Messages
1555
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1556
                                                                ex);
1557
                        } catch (NoClassDefFoundError ex) {
1558
                                this
1559
                                                .addError(
1560
                                                                Messages
1561
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1562
                                                                ex);
1563
                        } catch (Throwable ex) {
1564
                                this
1565
                                                .addError(
1566
                                                                Messages
1567
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1568
                                                                ex);
1569
                        }
1570
                }
1571
        }
1572

    
1573
        public class PluginMenuItem {
1574
                private Menu menu;
1575
                private PluginClassLoader loader;
1576
                private SkinExtensionType extension;
1577

    
1578
                PluginMenuItem(PluginClassLoader loader,
1579
                                SkinExtensionType extension, Menu menu) {
1580
                        this.menu = menu;
1581
                        this.loader = loader;
1582
                        this.extension = extension;
1583
                }
1584
                
1585
                public PluginServices getPlugin() {
1586
                        String pluginName = loader.getPluginName();
1587
                        return PluginServices.getPluginServices(pluginName);
1588
                }
1589
                
1590
                public String getExtensionName() {
1591
                        return this.extension.getClassName();
1592
                }
1593
                
1594
                public IExtension getExtension() {
1595
                        Class<?> extensionClass;
1596
                        try {
1597
                                extensionClass = loader.loadClass(this.extension.getClassName());
1598
                        } catch (ClassNotFoundException e) {
1599
                                return null;
1600
                        }
1601
                        return PluginServices.getExtension(extensionClass);
1602
                }
1603
                
1604
                public String getText() {
1605
                        return this.menu.getText();
1606
                }
1607

    
1608
                public long getPosition() {
1609
                        return this.menu.getPosition();
1610
                }
1611
                
1612
                public String getName() {
1613
                        return this.menu.getName();
1614
                }
1615
                
1616
                public boolean isParent() {
1617
                        return menu.getIs_separator();
1618
                }
1619
                
1620
                public String getPluginName() {
1621
                        return this.loader.getPluginName();
1622
                }
1623
                
1624
                public ActionInfo getAction() {
1625
                        ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1626
                        return manager.getAction(this.menu.getName());
1627
                }
1628
        }
1629
        
1630
        public List<PluginMenuItem> getPluginMenuItems() {
1631
                List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1632

    
1633
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1634
                Iterator<SortableMenu> e = orderedMenus.iterator();
1635
                while (e.hasNext()) {
1636
                                SortableMenu sm = e.next();
1637
                                PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1638
                                menuItems.add(item);
1639
                }
1640
                return menuItems;
1641
        }
1642

    
1643
        
1644
        /**
1645
         * Installs the menus, toolbars, actiontools, selectable toolbars and
1646
         * combos. The order in which they are shown is determined here.
1647
         */
1648
        private void installPluginsControls() {
1649
                logger.info("installPluginsControls (toolbars)");
1650

    
1651
                Iterator<String> i = pluginsConfig.keySet().iterator();
1652

    
1653
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1654
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1655
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1656
                                new ExtensionComparator());
1657

    
1658
                // First of all, sort the extensions.
1659
                // We need to iterate on the plugins, and iterate on each plugin's
1660
                // extensions
1661
                // (each plugin may contain one or more extensions)
1662
                while (i.hasNext()) { // iterate on the plugins
1663
                        String pName = i.next();
1664
                        try {
1665
                                PluginConfig pc = pluginsConfig.get(pName);
1666
                                PluginServices ps = pluginsServices.get(pName);
1667

    
1668
                                Extension[] exts = pc.getExtensions().getExtension();
1669

    
1670
                                for (int j = 0; j < exts.length; j++) { // iterate on the
1671
                                        // extensions
1672
                                        String cname = "unknow";
1673
                                        try {
1674
                                                cname = exts[j].getClassName();
1675
                                                if (exts[j].getActive()
1676
                                                                && !cname.equals(LibraryExtension.class
1677
                                                                                .getName())) {
1678
                                                        if (orderedExtensions.contains(exts[j])) {
1679
                                                                this
1680
                                                                                .addError(Messages
1681
                                                                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1682
                                                                                                + cname);
1683
                                                        }
1684

    
1685
                                                        orderedExtensions.add(exts[j]);
1686
                                                        extensionPluginServices.put(exts[j], ps);
1687
                                                        extensionPluginConfig.put(exts[j], pc);
1688
                                                }
1689
                                        } catch (Exception e) {
1690
                                                addError("Error initializing controls of plugin '"
1691
                                                                + pName + "' extension '" + cname + "'", e);
1692
                                        }
1693
                                }
1694
                        } catch (Throwable e) {
1695
                                addError("Error initializing controls of plugin '" + pName
1696
                                                + "'", e);
1697
                        }
1698
                }
1699

    
1700
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1701
                                new ToolComparator());
1702
                Iterator<Extension> e = orderedExtensions.iterator();
1703

    
1704
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1705
                // selectabletools)
1706
                // and load the combo-scales and combo-buttons for the status bar
1707
                while (e.hasNext()) {
1708
                        Extension ext = e.next();
1709
                        String extName = "unknow";
1710
                        try {
1711
                                extName = ext.getClassName();
1712
                                ToolBar[] toolbars = ext.getToolBar();
1713

    
1714
                                // get tools from toolbars
1715
                                for (int k = 0; k < toolbars.length; k++) {
1716
                                        ActionTool[] tools = toolbars[k].getActionTool();
1717

    
1718
                                        for (int t = 0; t < tools.length; t++) {
1719
                                                SortableTool sm = new SortableTool(
1720
                                                                (extensionPluginServices.get(ext))
1721
                                                                                .getClassLoader(), ext, toolbars[k],
1722
                                                                tools[t]);
1723
                                                orderedTools.add(sm);
1724
                                        }
1725

    
1726
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1727

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

    
1737
                                // get controls for statusBar
1738
                                PluginServices ps = extensionPluginServices.get(ext);
1739
                                PluginClassLoader loader = ps.getClassLoader();
1740

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

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

    
1835
                // Add the tools from MDI extensions to the ordered tool-list, so that
1836
                // we get a sorted list containing all the tools
1837
                i = pluginsConfig.keySet().iterator();
1838
                while (i.hasNext()) {
1839
                        String pName = (String) i.next();
1840
                        try {
1841
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1842
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
1843

    
1844
                                SkinExtension[] skinExts = pc.getExtensions()
1845
                                                .getSkinExtension();
1846
                                for (int j = 0; j < skinExts.length; j++) {
1847

    
1848
                                        if (skinExts[j] != null) {
1849
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1850

    
1851
                                                for (int k = 0; k < toolbars.length; k++) {
1852
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1853

    
1854
                                                        for (int t = 0; t < tools.length; t++) {
1855
                                                                SortableTool stb = new SortableTool(ps
1856
                                                                                .getClassLoader(), skinExts[j],
1857
                                                                                toolbars[k], tools[t]);
1858
                                                                orderedTools.add(stb);
1859
                                                        }
1860

    
1861
                                                        SelectableTool[] sTools = toolbars[k]
1862
                                                                        .getSelectableTool();
1863

    
1864
                                                        for (int t = 0; t < sTools.length; t++) {
1865
                                                                SortableTool stb = new SortableTool(ps
1866
                                                                                .getClassLoader(), skinExts[j],
1867
                                                                                toolbars[k], sTools[t]);
1868
                                                                orderedTools.add(stb);
1869
                                                        }
1870
                                                }
1871
                                        }
1872
                                }
1873
                                // Install popup menus
1874
                                PopupMenus pus = pc.getPopupMenus();
1875
                                if (pus != null) {
1876
                                        PopupMenu[] menus = pus.getPopupMenu();
1877
                                        for (int j = 0; j < menus.length; j++) {
1878
                                                String menuName = "(unknow)";
1879
                                                try  {
1880
                                                        menuName = menus[j].getName();
1881
                                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1882
                                                } catch(Throwable ex) {
1883
                                                        addError("Error adding popup menu' "+ menuName +"' in plugin '"+pName+"'.");
1884
                                                }
1885
                                        }
1886
                                }
1887
                        } catch (Throwable e3) {
1888
                                addError("Error initializing skins of the plugin '" + pName
1889
                                                + "'", e3);
1890
                        }
1891
                }
1892

    
1893
                // loop on the ordered extension list, to add them to the interface in
1894
                // an ordered way
1895
                Iterator<SortableTool> t = orderedTools.iterator();
1896
                while (t.hasNext()) {
1897
                        SortableTool stb = t.next();
1898
                        try {
1899
                                if (stb.actiontool != null) {
1900
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1901
                                                        stb.actiontool);
1902
                                } else {
1903
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
1904
                                                        stb.selectabletool);
1905
                                }
1906
                        } catch (ClassNotFoundException ex) {
1907
                                this
1908
                                                .addError(
1909
                                                                Messages
1910
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1911
                                                                ex);
1912
                        } catch (Throwable e2) {
1913
                                addError("Error adding tools to the interface of extension '"
1914
                                                + stb.extension.getClassName() + "'", e2);
1915
                        }
1916
                }
1917
        }
1918

    
1919
        /**
1920
         * Adds new plugins to the the andami-config file.
1921
         */
1922
        private void updateAndamiConfig() {
1923
                Set<String> olds = new HashSet<String>();
1924

    
1925
                Plugin[] plugins = andamiConfig.getPlugin();
1926

    
1927
                for (int i = 0; i < plugins.length; i++) {
1928
                        olds.add(plugins[i].getName());
1929
                }
1930

    
1931
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1932

    
1933
                while (i.hasNext()) {
1934
                        PluginServices ps = i.next();
1935

    
1936
                        if (!olds.contains(ps.getPluginName())) {
1937
                                Plugin p = new Plugin();
1938
                                p.setName(ps.getPluginName());
1939
                                p.setUpdate(false);
1940

    
1941
                                andamiConfig.addPlugin(p);
1942
                        }
1943
                }
1944
        }
1945

    
1946
        private void pluginsClassLoaders() {
1947
                Set<String> installed = new HashSet<String>();
1948

    
1949
                // Se itera hasta que est?n todos instalados
1950
                while (installed.size() != pluginsConfig.size()) {
1951
                        boolean circle = true;
1952

    
1953
                        // Hacemos una pasada por todos los plugins
1954
                        Iterator<String> i = pluginsConfig.keySet().iterator();
1955

    
1956
                        while (i.hasNext()) {
1957
                                String pluginName = i.next();
1958
                                PluginConfig config = (PluginConfig) pluginsConfig
1959
                                                .get(pluginName);
1960

    
1961
                                if (installed.contains(pluginName)) {
1962
                                        continue;
1963
                                }
1964

    
1965
                                // Se obtienen las dependencias y sus class loaders
1966
                                boolean ready = true;
1967
                                Depends[] dependencies = config.getDepends();
1968
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1969

    
1970
                                for (int j = 0; j < dependencies.length; j++) {
1971
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1972
                                                this
1973
                                                                .addError(Messages
1974
                                                                                .getString("Launcher.Dependencia_no_resuelta_en_plugin")
1975
                                                                                + " "
1976
                                                                                + pluginName
1977
                                                                                + ": "
1978
                                                                                + dependencies[j].getPluginName());
1979

    
1980
                                                continue;
1981
                                        }
1982

    
1983
                                        if (!installed.contains(dependencies[j].getPluginName())) {
1984
                                                ready = false;
1985
                                        } else {
1986
                                                loaders[j] = (pluginsServices.get(dependencies[j]
1987
                                                                .getPluginName())).getClassLoader();
1988
                                        }
1989
                                }
1990

    
1991
                                // Si no est?n sus dependencias satisfechas se aborta la
1992
                                // instalaci?n
1993
                                if (!ready) {
1994
                                        continue;
1995
                                }
1996

    
1997
                                // Se genera el class loader
1998
                                String jardir = config.getLibraries().getLibraryDir();
1999
                                File jarDir = new File(andamiConfig.getPluginsDirectory(),
2000
                                                pluginName + File.separator + jardir);
2001
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
2002

    
2003
                                        public boolean accept(File pathname) {
2004
                                                return (pathname.getName().toUpperCase()
2005
                                                                .endsWith(".JAR"))
2006
                                                                || (pathname.getName().toUpperCase()
2007
                                                                                .endsWith(".ZIP"));
2008
                                        }
2009
                                });
2010

    
2011
                                URL[] urls = new URL[jarFiles.length];
2012

    
2013
                                for (int j = 0; j < jarFiles.length; j++) {
2014
                                        try {
2015
                                                urls[j] = new URL("file:" + jarFiles[j]);
2016
                                        } catch (MalformedURLException e) {
2017
                                                this.addError(Messages
2018
                                                                .getString("Launcher.No_se_puede_acceder_a")
2019
                                                                + " " + jarFiles[j]);
2020
                                        }
2021
                                }
2022

    
2023
                                PluginClassLoader loader;
2024

    
2025
                                try {
2026
                                        loader = new PluginClassLoader(urls, andamiConfig
2027
                                                        .getPluginsDirectory()
2028
                                                        + File.separator + pluginName, Launcher.class
2029
                                                        .getClassLoader(), loaders);
2030

    
2031
                                        PluginServices ps = new PluginServices(loader);
2032

    
2033
                                        pluginsServices.put(ps.getPluginName(), ps);
2034

    
2035
                                        installed.add(pluginName);
2036
                                        // FJP: Los metemos ordenados para luego no cargar uno que
2037
                                        // necesita de otro antes de tiempo. Esto lo usaremos al
2038
                                        // inicializar los plugins
2039
                                        pluginsOrdered.add(pluginName);
2040

    
2041
                                        circle = false;
2042
                                } catch (IOException e) {
2043
                                        this
2044
                                                        .addError(
2045
                                                                        Messages
2046
                                                                                        .getString("Launcher.Error_con_las_librerias_del_plugin"),
2047
                                                                        e);
2048
                                        pluginsConfig.remove(pluginName);
2049
                                        i = pluginsConfig.keySet().iterator();
2050
                                }
2051
                        }
2052

    
2053
                        if (circle) {
2054
                                this.addError(Messages
2055
                                                .getString("Launcher.Hay_dependencias_circulares"));
2056

    
2057
                                break;
2058
                        }
2059
                }
2060

    
2061
                // Se eliminan los plugins que no fueron instalados
2062
                Iterator<String> i = pluginsConfig.keySet().iterator();
2063

    
2064
                while (i.hasNext()) {
2065
                        String pluginName = i.next();
2066
                        PluginServices ps = (PluginServices) pluginsServices
2067
                                        .get(pluginName);
2068

    
2069
                        if (ps == null) {
2070
                                pluginsConfig.remove(pluginName);
2071
                                i = pluginsConfig.keySet().iterator();
2072
                        }
2073
                }
2074
                registerActions();
2075
        }
2076

    
2077
        private void pluginsMessages() {
2078
                Iterator<String> iterator = pluginsOrdered.iterator();
2079
                PluginConfig config;
2080
                PluginServices ps;
2081

    
2082
                while (iterator.hasNext()) {
2083
                        String pluginName = iterator.next();
2084
                        config = pluginsConfig.get(pluginName);
2085
                        ps = pluginsServices.get(pluginName);
2086

    
2087
                        if ((config.getResourceBundle() != null)
2088
                                        && !config.getResourceBundle().getName().equals("")) {
2089
                                // add the locale files associated with the plugin
2090
                                org.gvsig.i18n.Messages.addResourceFamily(config
2091
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2092
                                                pluginName);
2093
                        }
2094
                }
2095
        }
2096

    
2097
        static public PluginServices getPluginServices(String name) {
2098
                return (PluginServices) pluginsServices.get(name);
2099
        }
2100

    
2101
        static String getPluginsDir() {
2102
                return andamiConfig.getPluginsDirectory();
2103
        }
2104

    
2105
        static void setPluginsDir(String s) {
2106
                andamiConfig.setPluginsDirectory(s);
2107
        }
2108

    
2109
        static MDIFrame getMDIFrame() {
2110
                return frame;
2111
        }
2112

    
2113
        private void loadPlugins(String pluginsDirectory) {
2114
                File pDir = new File(pluginsDirectory);
2115

    
2116
                if (!pDir.exists()) {
2117
                        logger
2118
                                        .error("\n\tPlugins directory not found: "
2119
                                                        + pDir.getAbsolutePath()
2120
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2121
                        System.exit(-1);
2122
                        return;
2123
                }
2124

    
2125
                File[] pluginDirs = pDir.listFiles();
2126
                if (pluginDirs.length == 0) {
2127
                        logger
2128
                                        .error("\n\tPlugins directory is empty: "
2129
                                                        + pDir.getAbsolutePath()
2130
                                                        + "Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2131
                        System.exit(-1);
2132
                        return;
2133
                }
2134

    
2135
                for (int i = 0; i < pluginDirs.length; i++) {
2136
                        if (pluginDirs[i].isDirectory()) {
2137
                                String pluginName =  pluginDirs[i].getName();
2138
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2139
                                                "config.xml");
2140

    
2141
                                try {
2142
                                        FileInputStream is = new FileInputStream(configXml);
2143
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2144
                                        if (xml == null) {
2145
                                                // the encoding was not correctly detected, use system
2146
                                                // default
2147
                                                xml = new FileReader(configXml);
2148
                                        } else {
2149
                                                // use a buffered reader to improve performance
2150
                                                xml = new BufferedReader(xml);
2151
                                        }
2152
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2153
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
2154
                                } catch (FileNotFoundException e) {
2155
                                        logger.info("Plugin '"+pluginName+"' without config.xml ("
2156
                                                                        + pluginDirs[i].getAbsolutePath() + ").");
2157
                                } catch (MarshalException e) {
2158
                                        this.addError("Can't load plugin '"+pluginName+"', incorrect config.xml." + e.getMessage() +" ("
2159
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2160
                                } catch (ValidationException e) {
2161
                                        this.addError("Can't load plugin '"+pluginName+"', invalid config.xml." + e.getMessage() +" ("
2162
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2163
                                }
2164
                        }
2165
                }
2166

    
2167
                if (pluginsConfig.size() == 0) {
2168
                        logger.error("No valid plugin was found. The plugins directory currently is: "
2169
                                                        + pDir.getAbsolutePath()
2170
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2171
                        System.exit(-1);
2172
                        return;
2173
                }
2174
        }
2175

    
2176
        private static Locale getLocale(String language, String country,
2177
                        String variant) {
2178
                if (variant != null) {
2179
                        return new Locale(language, country, variant);
2180
                } else if (country != null) {
2181
                        return new Locale(language, country);
2182
                } else if (language != null) {
2183
                        return new Locale(language);
2184
                } else {
2185
                        return new Locale("es");
2186
                }
2187
        }
2188

    
2189
        private static void andamiConfigToXML(String file) throws IOException,
2190
                        MarshalException, ValidationException {
2191
                // write on a temporary file in order to not destroy current file if
2192
                // there is some problem while marshaling
2193
                File tmpFile = new File(file + "-"
2194
                                + DateTime.getCurrentDate().getTime());
2195
                File xml = new File(file);
2196
                File parent = xml.getParentFile();
2197
                parent.mkdirs();
2198

    
2199
                BufferedOutputStream os = new BufferedOutputStream(
2200
                                new FileOutputStream(tmpFile));
2201
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2202
                andamiConfig.marshal(writer);
2203
                writer.close();
2204

    
2205
                // if marshaling process finished correctly, move the file to the
2206
                // correct one
2207
                xml.delete();
2208
                if (!tmpFile.renameTo(xml)) {
2209
                        // if rename was not succesful, try copying it
2210
                        FileChannel sourceChannel = new FileInputStream(tmpFile)
2211
                                        .getChannel();
2212
                        FileChannel destinationChannel = new FileOutputStream(xml)
2213
                                        .getChannel();
2214
                        sourceChannel.transferTo(0, sourceChannel.size(),
2215
                                        destinationChannel);
2216
                        sourceChannel.close();
2217
                        destinationChannel.close();
2218
                }
2219
        }
2220

    
2221
        private static void andamiConfigFromXML(String file)
2222
                        throws ConfigurationException {
2223
                File xml = new File(file);
2224

    
2225
                InputStreamReader reader = null;
2226
                try {
2227
                        // Se lee la configuraci?n
2228
                        reader = XMLEncodingUtils.getReader(xml);
2229
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2230
                } catch (FileNotFoundException e) {
2231
                        // Si no existe se ponen los valores por defecto
2232
                        andamiConfig = getDefaultAndamiConfig();
2233
                } catch (MarshalException e) {
2234
                        // try to close the stream, maybe it remains open
2235
                        if (reader != null) {
2236
                                try {
2237
                                        reader.close();
2238
                                } catch (IOException e1) {
2239
                                }
2240
                        }
2241
                        // if there was a problem reading the file, backup it and create a
2242
                        // new one with default values
2243
                        String backupFile = file + "-"
2244
                                        + DateTime.getCurrentDate().getTime();
2245
                        NotificationManager
2246
                                        .addError(
2247
                                                        Messages
2248
                                                                        .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2249
                                                                        + backupFile, new ConfigurationException(e));
2250
                        xml.renameTo(new File(backupFile));
2251
                        andamiConfig = getDefaultAndamiConfig();
2252
                } catch (ValidationException e) {
2253
                        throw new ConfigurationException(e);
2254
                }
2255
        }
2256

    
2257
        private static AndamiConfig getDefaultAndamiConfig() {
2258
                AndamiConfig andamiConfig = new AndamiConfig();
2259

    
2260
                Andami andami = new Andami();
2261
                andami.setUpdate(true);
2262
                andamiConfig.setAndami(andami);
2263
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2264
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2265
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2266

    
2267
                if (System.getProperty("javawebstart.version") != null) // Es java web
2268
                // start)
2269
                {
2270
                        andamiConfig
2271
                                        .setPluginsDirectory(new File(appHomeDir, "extensiones")
2272
                                                        .getAbsolutePath());
2273
                } else {
2274
                        andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2275
                                        .getAbsolutePath());
2276
                }
2277

    
2278
                andamiConfig.setPlugin(new Plugin[0]);
2279
                return andamiConfig;
2280
        }
2281

    
2282
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2283
                File xml = getPluginsPersistenceFile(true);
2284

    
2285
                if (xml.exists()) {
2286
                        InputStreamReader reader = null;
2287

    
2288
                        try {
2289
                                reader = XMLEncodingUtils.getReader(xml);
2290
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2291
                                return new XMLEntity(tag);
2292
                        } catch (FileNotFoundException e) {
2293
                                throw new ConfigurationException(e);
2294
                        } catch (MarshalException e) {
2295

    
2296
                                // try to reopen with default encoding (for backward
2297
                                // compatibility)
2298
                                try {
2299
                                        reader = new FileReader(xml);
2300
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2301
                                        return new XMLEntity(tag);
2302

    
2303
                                } catch (MarshalException ex) {
2304
                                        // try to close the stream, maybe it remains open
2305
                                        if (reader != null) {
2306
                                                try {
2307
                                                        reader.close();
2308
                                                } catch (IOException e1) {
2309
                                                }
2310
                                        }
2311
                                        // backup the old file
2312
                                        String backupFile = getPluginsPersistenceFile(true)
2313
                                                        .getPath()
2314
                                                        + "-" + DateTime.getCurrentDate().getTime();
2315
                                        NotificationManager
2316
                                                        .addError(
2317
                                                                        Messages
2318
                                                                                        .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2319
                                                                                        + backupFile,
2320
                                                                        new ConfigurationException(e));
2321
                                        xml.renameTo(new File(backupFile));
2322
                                        // create a new, empty configuration
2323
                                        return new XMLEntity();
2324
                                } catch (FileNotFoundException ex) {
2325
                                        return new XMLEntity();
2326
                                } catch (ValidationException ex) {
2327
                                        throw new ConfigurationException(e);
2328
                                }
2329
                        } catch (ValidationException e) {
2330
                                throw new ConfigurationException(e);
2331
                        }
2332
                } else {
2333
                        return new XMLEntity();
2334
                }
2335
        }
2336

    
2337
        private static File getPluginsPersistenceFile(boolean read) {
2338
                if (read) {
2339
                        File pluginsPersistenceFile = new File(getAppHomeDir(),
2340
                                        "plugins-persistence-2_0.xml");
2341
                        if (pluginsPersistenceFile.exists()) {
2342
                                return pluginsPersistenceFile;
2343
                        }
2344
                        pluginsPersistenceFile = new File(getAppHomeDir(),
2345
                                        "plugins-persistence.xml");
2346
                        if (pluginsPersistenceFile.exists()) {
2347
                                return pluginsPersistenceFile;
2348
                        }
2349
                }
2350
                return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2351

    
2352
        }
2353

    
2354
        private static void persistenceToXML(XMLEntity entity)
2355
                        throws ConfigurationException {
2356
                // write on a temporary file in order to not destroy current file if
2357
                // there is some problem while marshaling
2358
                File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2359
                                + "-" + DateTime.getCurrentDate().getTime());
2360

    
2361
                File xml = getPluginsPersistenceFile(false);
2362
                OutputStreamWriter writer = null;
2363

    
2364
                try {
2365
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2366
                                        CASTORENCODING);
2367
                        entity.getXmlTag().marshal(writer);
2368
                        writer.close();
2369

    
2370
                        // if marshaling process finished correctly, move the file to the
2371
                        // correct one
2372
                        xml.delete();
2373
                        if (!tmpFile.renameTo(xml)) {
2374
                                // if rename was not succesful, try copying it
2375
                                FileChannel sourceChannel = new FileInputStream(tmpFile)
2376
                                                .getChannel();
2377
                                FileChannel destinationChannel = new FileOutputStream(xml)
2378
                                                .getChannel();
2379
                                sourceChannel.transferTo(0, sourceChannel.size(),
2380
                                                destinationChannel);
2381
                                sourceChannel.close();
2382
                                destinationChannel.close();
2383

    
2384
                        }
2385
                } catch (FileNotFoundException e) {
2386
                        throw new ConfigurationException(e);
2387
                } catch (MarshalException e) {
2388
                        // try to close the stream, maybe it remains open
2389
                        if (writer != null) {
2390
                                try {
2391
                                        writer.close();
2392
                                } catch (IOException e1) {
2393
                                }
2394
                        }
2395
                } catch (ValidationException e) {
2396
                        throw new ConfigurationException(e);
2397
                } catch (IOException e) {
2398
                        throw new ConfigurationException(e);
2399
                }
2400
        }
2401

    
2402
        static MDIFrame getFrame() {
2403
                return frame;
2404
        }
2405

    
2406
        /**
2407
         * Gracefully closes the application. It shows dialogs to save data, finish
2408
         * processes, etc, then it terminates the extensions, removes temporal files
2409
         * and finally exits.
2410
         */
2411
        public synchronized static void closeApplication() {
2412
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2413
                terminationProcess.run();
2414
        }
2415

    
2416
        static HashMap getClassesExtensions() {
2417
                return classesExtensions;
2418
        }
2419

    
2420
        private static Extensions[] getExtensions() {
2421
                List<Extensions> array = new ArrayList<Extensions>();
2422
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2423

    
2424
                while (iter.hasNext()) {
2425
                        array.add(iter.next().getExtensions());
2426
                }
2427

    
2428
                return array.toArray(new Extensions[array.size()]);
2429
        }
2430

    
2431
        public static Iterator getExtensionIterator() {
2432
                return extensions.iterator();
2433
        }
2434

    
2435
        public static HashMap getPluginConfig() {
2436
                return pluginsConfig;
2437
        }
2438

    
2439
        public static Extension getExtension(String s) {
2440
                Extensions[] exts = getExtensions();
2441

    
2442
                for (int i = 0; i < exts.length; i++) {
2443
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2444
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2445
                                        return exts[i].getExtension(j);
2446
                                }
2447
                        }
2448
                }
2449

    
2450
                return null;
2451
        }
2452

    
2453
        public static AndamiConfig getAndamiConfig() {
2454
                return andamiConfig;
2455
        }
2456

    
2457
        private static class ExtensionComparator implements Comparator {
2458

    
2459
                public int compare(Object o1, Object o2) {
2460
                        Extension e1 = (Extension) o1;
2461
                        Extension e2 = (Extension) o2;
2462

    
2463
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2464
                                return -1;
2465
                        }
2466

    
2467
                        if (e1.hasPriority() && !e2.hasPriority()) {
2468
                                return Integer.MIN_VALUE;
2469
                        }
2470

    
2471
                        if (e2.hasPriority() && !e1.hasPriority()) {
2472
                                return Integer.MAX_VALUE;
2473
                        }
2474

    
2475
                        if (e1.getPriority() != e2.getPriority()) {
2476
                                return e2.getPriority() - e1.getPriority();
2477
                        } else {
2478
                                return (e2.toString().compareTo(e1.toString()));
2479
                        }
2480
                }
2481
        }
2482

    
2483
        private static class MenuComparator implements Comparator<SortableMenu> {
2484

    
2485
                private static ExtensionComparator extComp = new ExtensionComparator();
2486

    
2487
                public int compare(SortableMenu e1, SortableMenu e2) {
2488

    
2489
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2490
                                if (e1.extension instanceof SkinExtensionType) {
2491
                                        return 1;
2492
                                } else if (e2.extension instanceof SkinExtensionType) {
2493
                                        return -1;
2494
                                } else {
2495
                                        return extComp.compare(e1.extension, e2.extension);
2496
                                }
2497
                        }
2498

    
2499
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2500
                                return Integer.MIN_VALUE;
2501
                        }
2502

    
2503
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2504
                                return Integer.MAX_VALUE;
2505
                        }
2506
                        
2507
                        if( e1.menu.getPosition() == e2.menu.getPosition() ) {
2508
                                // we don't return 0 unless both objects are the same, otherwise
2509
                                // the objects get overwritten in the treemap
2510
                                return (e1.toString().compareTo(e2.toString()));
2511
                        }
2512
                    if( e1.menu.getPosition() > e2.menu.getPosition() ) {
2513
                                return Integer.MAX_VALUE;
2514
                        }
2515
                    return Integer.MIN_VALUE;
2516
                    
2517
                }
2518
        }
2519

    
2520
        private static class SortableMenu {
2521

    
2522
                public PluginClassLoader loader;
2523
                public Menu menu;
2524
                public SkinExtensionType extension;
2525

    
2526
                public SortableMenu(PluginClassLoader loader,
2527
                                SkinExtensionType skinExt, Menu menu2) {
2528
                        extension = skinExt;
2529
                        menu = menu2;
2530
                        this.loader = loader;
2531
                }
2532
                
2533
        }
2534

    
2535
        private static class SortableTool {
2536

    
2537
                public PluginClassLoader loader;
2538
                public ToolBar toolbar;
2539
                public ActionTool actiontool;
2540
                public SelectableTool selectabletool;
2541
                public SkinExtensionType extension;
2542

    
2543
                public SortableTool(PluginClassLoader loader,
2544
                                SkinExtensionType skinExt, ToolBar toolbar2,
2545
                                ActionTool actiontool2) {
2546
                        extension = skinExt;
2547
                        toolbar = toolbar2;
2548
                        actiontool = actiontool2;
2549
                        this.loader = loader;
2550
                }
2551

    
2552
                public SortableTool(PluginClassLoader loader,
2553
                                SkinExtensionType skinExt, ToolBar toolbar2,
2554
                                SelectableTool selectabletool2) {
2555
                        extension = skinExt;
2556
                        toolbar = toolbar2;
2557
                        selectabletool = selectabletool2;
2558
                        this.loader = loader;
2559
                }
2560
        }
2561

    
2562
        private static class ToolBarComparator implements Comparator<SortableTool> {
2563

    
2564
                private static ExtensionComparator extComp = new ExtensionComparator();
2565

    
2566
                public int compare(SortableTool e1, SortableTool e2) {
2567

    
2568
                        // if the toolbars have the same name, they are considered to be
2569
                        // the same toolbar, so we don't need to do further comparing
2570
                        if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2571
                                return 0;
2572
                        }
2573

    
2574
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2575
                                if (e1.extension instanceof SkinExtensionType) {
2576
                                        return 1;
2577
                                } else if (e2.extension instanceof SkinExtensionType) {
2578
                                        return -1;
2579
                                } else {
2580
                                        return extComp.compare(e1.extension, e2.extension);
2581
                                }
2582
                        }
2583

    
2584
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2585
                                return Integer.MIN_VALUE;
2586
                        }
2587

    
2588
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2589
                                return Integer.MAX_VALUE;
2590
                        }
2591
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2592
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2593
                        }
2594

    
2595
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2596
                                        && e1.toolbar.getSelectableTool().equals(
2597
                                                        e2.toolbar.getSelectableTool())) {
2598
                                return 0;
2599
                        }
2600
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2601
                }
2602
        }
2603

    
2604
        /**
2605
         * <p>
2606
         * This class is used to compare tools (selectabletool and actiontool),
2607
         * using the "position" attribute.
2608
         * </p>
2609
         * <p>
2610
         * The ordering criteria are:
2611
         * </p>
2612
         * <ul>
2613
         * <li>If the tools are placed in different toolbars, they use the toolbars'
2614
         * order. (using the ToolBarComparator).</li>
2615
         * <li></li>
2616
         * <li>If any of the tools has not 'position' attribute, the tool which
2617
         * <strong>has</strong> the attribute will be placed first.</li>
2618
         * <li>If both tools have the same position (or they don't have a 'position'
2619
         * attribute), the priority of the extensions where the tool is defined.</li>
2620
         * </ul>
2621
         * 
2622
         * @author cesar
2623
         * @version $Revision: 38806 $
2624
         */
2625
        private static class ToolComparator implements Comparator<SortableTool> {
2626

    
2627
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2628

    
2629
                public int compare(SortableTool e1, SortableTool e2) {
2630
                        // compare the toolbars which contain the tools
2631
                        long result = toolBarComp.compare(e1, e2);
2632
                        if (result != 0) { // if the toolbars are different, use their order
2633
                                return result>0? 1:-1;
2634
                        }
2635
                        // otherwise, compare the tools
2636
                        long e1Position = -1, e2Position = -1;
2637

    
2638
                        if (e1.actiontool != null) {
2639
                                if (e1.actiontool.hasPosition()) {
2640
                                        e1Position = e1.actiontool.getPosition();
2641
                                }
2642
                        } else if (e1.selectabletool != null) {
2643
                                if (e1.selectabletool.hasPosition()) {
2644
                                        e1Position = e1.selectabletool.getPosition();
2645
                                }
2646
                        }
2647

    
2648
                        if (e2.actiontool != null) {
2649
                                if (e2.actiontool.hasPosition()) {
2650
                                        e2Position = e2.actiontool.getPosition();
2651
                                }
2652
                        } else if (e2.selectabletool != null) {
2653
                                if (e2.selectabletool.hasPosition()) {
2654
                                        e2Position = e2.selectabletool.getPosition();
2655
                                }
2656
                        }
2657

    
2658
                        if ((e1Position == -1) && (e2Position != -1)) {
2659
                                return 1;
2660
                        }
2661
                        if ((e1Position != -1) && (e2Position == -1)) {
2662
                                return -1;
2663
                        }
2664
                        if ((e1Position != -1) && (e2Position != -1)) {
2665
                                result = e1Position - e2Position;
2666
                                // we don't return 0 unless both objects are the same, otherwise
2667
                                // the objects get overwritten in the treemap
2668
                                if (result != 0) {
2669
                                        return  result>0? 1:-1;
2670
                                }
2671
                        }
2672
                        return e1.toString().compareTo(e2.toString());
2673
                }
2674
        }
2675

    
2676
        /**
2677
         * validates the user before starting gvsig
2678
         * 
2679
         */
2680
        private static void validate() {
2681

    
2682
                IAuthentication session = null;
2683
                try {
2684
                        session = (IAuthentication) Class.forName(
2685
                                        "com.iver.andami.authentication.Session").newInstance();
2686

    
2687
                } catch (ClassNotFoundException e) {
2688
                        return;
2689
                } catch (InstantiationException e) {
2690
                        return;
2691
                } catch (IllegalAccessException e) {
2692
                        return;
2693
                }
2694

    
2695
                session.setPluginDirectory(andamiConfig.getPluginsDirectory());
2696
                if (session.validationRequired()) {
2697
                        if (session.Login()) {
2698
                                logger.info("You are logged in");
2699
                        } else {
2700
                                JOptionPane.showMessageDialog((Component) PluginServices
2701
                                                .getMainFrame(), "You are not logged in");
2702
                        }
2703
                        PluginServices.setAuthentication(session);
2704
                }
2705
        }
2706

    
2707
        public static String getDefaultLookAndFeel() {
2708
                String osName = (String) System.getProperty("os.name");
2709

    
2710
                if ((osName.length() > 4)
2711
                                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2712
                        return nonWinDefaultLookAndFeel;
2713
                }
2714
                if (osName.toLowerCase().startsWith("mac os x")) {
2715
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2716
                }
2717

    
2718
                return UIManager.getSystemLookAndFeelClassName();
2719
        }
2720

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

    
2754
                                        while ((line = reader.readLine()) != null) {
2755
                                                String[] language = line.split("\t");
2756
                                                if (language[0].equals(langCode)) {
2757
                                                        // the three
2758
                                                        // characters code
2759
                                                        return language[2]; // third column i the two
2760
                                                        // characters code
2761
                                                }
2762
                                        }
2763
                                } catch (IOException ex) {
2764
                                        logger.error(Messages
2765
                                                        .getString("Error_reading_isocodes_file"), ex);
2766
                                        return "es";
2767
                                }
2768
                        } else {
2769
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2770
                                return "es";
2771
                        }
2772
                }
2773
                return "es";
2774
        }
2775

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

    
2822
        // Create classloader for the i18n resources in the
2823
        // andami and user i18n folder. Those values will have
2824
        // precedence over any other values added afterwards
2825
        File andamiI18nFolder =
2826
            new File(System.getProperty("user.dir"), "i18n");
2827
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2828

    
2829
        logger.info("Loading i18n resources from the application and user "
2830
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2831

    
2832
        URL[] i18nURLs;
2833
        try {
2834
            i18nURLs =
2835
                new URL[] { userI18nFolder.toURI().toURL(),
2836
                    andamiI18nFolder.toURI().toURL() };
2837
            ClassLoader i18nClassLoader = new URLClassLoader(i18nURLs);
2838
            org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
2839
                "Andami Launcher");
2840
        } catch (MalformedURLException e) {
2841
            logger.error("Error loading i18n resources from the application "
2842
                + "and user folders: " + andamiI18nFolder + ", "
2843
                + userI18nFolder, e);
2844
        }
2845

    
2846
        // Finally load the andami own i18n resources
2847
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2848
            "Andami Launcher");
2849
        }
2850

    
2851
        /**
2852
         * Gets Home Directory location of the application into users home folder.
2853
         * 
2854
         * May be set from outside the aplication by means of
2855
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2856
         * 
2857
         * @return
2858
         */
2859
        public static String getAppHomeDir() {
2860
                return appHomeDir;
2861
        }
2862
        
2863
    public static File getApplicationHomeFolder() {
2864
        return new File(getAppHomeDir());
2865
    }
2866

    
2867
        /**
2868
         * Sets Home Directory location of the application. May be set from outside
2869
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
2870
         * the name of the application
2871
         * 
2872
         * @param appHomeDir
2873
         */
2874
        public static void setAppHomeDir(String appHomeDir) {
2875
                Launcher.appHomeDir = appHomeDir;
2876
        }
2877

    
2878
        /**
2879
         * Initialize the extesion that have to take the control of the state of
2880
         * action controls of the UI of all extensions. <br>
2881
         * <br>
2882
         * For use this option you have to add an argument to the command line like
2883
         * this: <br>
2884
         * <br>
2885
         * -exclusiveUI={pathToExtensionClass} <br>
2886
         * 
2887
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
2888
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
2889
         */
2890
        private static void initializeExclusiveUIExtension() {
2891
                String name = PluginServices.getArgumentByName("exclusiveUI");
2892
                if (name == null) {
2893
                        return;
2894
                }
2895

    
2896
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
2897
                                .iterator();
2898
                int charIndex;
2899
                Class<? extends IExtension> key;
2900
                while (iter.hasNext()) {
2901
                        key = iter.next();
2902
                        charIndex = key.getName().indexOf(name);
2903
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2904
                        if (charIndex == 0) {
2905
                                IExtension ext = classesExtensions.get(key);
2906
                                if (ext instanceof ExtensionDecorator) {
2907
                                        ext = ((ExtensionDecorator) ext).getExtension();
2908
                                }
2909
                                if (ext instanceof ExclusiveUIExtension) {
2910
                                        PluginServices
2911
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
2912
                                }
2913
                                break;
2914
                        }
2915
                }
2916

    
2917
                logger
2918
                                .error(Messages
2919
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2920
                                                + " '" + name + "'");
2921
        }
2922

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

    
2961
        public static void initIconThemes() {
2962
                PluginsManager pluginsManager = PluginsLocator.getManager();
2963
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
2964
                
2965
                File f = new File(pluginsManager.getApplicationFolder(),"icon-theme");
2966
                if( !f.exists() ) { 
2967
                        try {
2968
                                f.mkdir();
2969
                        } catch(Exception ex) {
2970
                                // Do nothing
2971
                        }
2972
                }
2973
                iconManager.getRepository().add(f,"_Global");
2974
                
2975
                f = new File(pluginsManager.getApplicationHomeFolder(),"icon-theme");
2976
                if( !f.exists() ) {
2977
                        try {
2978
                                f.mkdir();
2979
                        } catch(Exception ex) {
2980
                                // Do nothing
2981
                        }
2982
                }
2983
                iconManager.getRepository().add(f,"_User");
2984
                
2985
                Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
2986
                String defaultThemeID = prefs.get("default-theme", null);
2987
                if( defaultThemeID != null ) {
2988
                        IconTheme iconTheme = iconManager.get(defaultThemeID);
2989
                        if( iconTheme != null ) {
2990
                                iconManager.setCurrent(iconTheme);
2991
                        }
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
        private PackageInfo getPackageInfo(String pluginsFolder) {
3275
                try {
3276
                        File packageInfoFile = FileUtils.getFile(pluginsFolder,
3277
                                        "org.gvsig.app", "package.info");
3278
                        if (packageInfoFile.exists()) {
3279
                                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3280
                                FileInputStream fis = new FileInputStream(packageInfoFile);
3281
                                PackageInfo packageInfo = installerManager.createPackageInfo(fis);
3282
                                return packageInfo;
3283
                        }
3284
                        return null;
3285
                } catch (Exception e) {
3286
                        logger.info("Can't locate PackageInfo from plugin org.gvsig.app",e);
3287
                        return null;
3288
                }
3289
        }
3290

    
3291
        /**
3292
         * Launch the gvSIG package installer.
3293
         * 
3294
         * @throws Exception
3295
         *             if there is any error
3296
         */
3297
        private void doInstall(String[] args) throws Exception {
3298
                String installURL = null;
3299
                String installURLFile = null;
3300
                String gvSIGVersion = null;
3301
                String[] myArgs = new String[3];
3302
                PackageInfo packageInfo = null; 
3303

    
3304
                Options options = new Options();
3305
                options.addOption("i", "install", false, "install");
3306
                options.addOption("u", "installURL", true, "installURL");
3307
                options.addOption("f", "installURLFile", true, "installURLFile");
3308
                options.addOption("v", "installVersion", true, "installVersion");
3309
                options.addOption("A", "applicationName", true, "applicationName");
3310
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3311
                options.addOption("l", "language", true, "language");
3312

    
3313
                
3314
                /*
3315
                 * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3316
                 * 
3317
                 * --install
3318
                 * --applicationName=gvSIG
3319
                 * --language=es
3320
                 * --pluginsFolder=gvSIG/extensiones
3321
                 * 
3322
                 * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3323
                 * --installVersion=2.0.0
3324
                 * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3325
                 * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3326
                 * 
3327
                 */
3328
                CommandLineParser parser = new PosixParser();
3329
                CommandLine line = null;
3330
                try {
3331
                        line = parser.parse(options, args);
3332
                        boolean hasAllMandatoryOptions = true;
3333
                        if (!line.hasOption("install")) {
3334
                                hasAllMandatoryOptions = false;
3335
                        }
3336
                        
3337
                        if (line.hasOption("installVersion")) {
3338
                                gvSIGVersion = line.getOptionValue("installVersion");
3339
                        }
3340
                        if (line.hasOption("applicationName")) {
3341
                                myArgs[0] = line.getOptionValue("applicationName");
3342
                        } else {
3343
                                hasAllMandatoryOptions = false;
3344
                        }
3345
                        if (line.hasOption("pluginsFolder")) {
3346
                                myArgs[1] = line.getOptionValue("pluginsFolder");
3347
                        } else {
3348
                                myArgs[1] = "gvSIG/extensiones";
3349
                                hasAllMandatoryOptions = false;
3350
                        }
3351
                        if (line.hasOption("language")) {
3352
                                myArgs[2] = "language=" + line.getOptionValue("language");
3353
                        } else {
3354
                            // prevent null
3355
                            myArgs[2] = "";
3356
                        }
3357
                        
3358
                        if (line.hasOption("installURL")) {
3359
                                installURL = line.getOptionValue("installURL");
3360
                        } else {
3361
                                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3362
                        }
3363
                        
3364
                        if (line.hasOption("installURLFile")) {
3365
                                installURLFile = line.getOptionValue("installURLFile");
3366
                        } else {
3367
                                installURLFile = myArgs[1] + "/org.gvsig.installer.app.extension/defaultDownloadsURLs";
3368
                        }
3369

    
3370
                        if (!hasAllMandatoryOptions) {
3371
                                System.err
3372
                                                .println(Messages.get("usage")
3373
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
3374
                                                                + "[--installURLFile=File] "
3375
                                                                + "--install [--installURL=URL] [language=locale]");
3376
                                return;
3377
                        }
3378
                } catch (ParseException exp) {
3379
                        System.out.println("Unexpected exception:" + exp.getMessage());
3380
                }
3381

    
3382
                initializeApp(myArgs);
3383
                initializeLibraries();
3384
                AndamiConfig config = getAndamiConfig();
3385
                config.setLocaleLanguage(locale.getLanguage());
3386
                config.setLocaleCountry(locale.getCountry());
3387
                config.setLocaleVariant(locale.getVariant());
3388
                
3389
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3390
                
3391
                packageInfo = getPackageInfo(myArgs[1]);
3392
                
3393
                // set the gvSIG version to the install manager, to compose the download URL
3394
                if( packageInfo!=null ) {
3395
                        installerManager.setVersion(packageInfo.getVersion().toString());
3396
                } else {
3397
                        installerManager.setVersion(gvSIGVersion);
3398
                }
3399
                if( !installURL.contains(";") &&
3400
                        !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION) && 
3401
                        !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION) ) {
3402
                        if( packageInfo!=null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA) ||
3403
                                 packageInfo.getState().startsWith(InstallerManager.STATE.RC) ||
3404
                                 packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL)) ) {
3405
                                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";                        
3406
                        }
3407
                }
3408
                // Configure default index download URL
3409
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3410

    
3411
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3412

    
3413
                // Launch installer
3414
                PluginsManager manager = PluginsLocator.getManager();
3415

    
3416
                File defaultAddonsRepository = PluginsLocator.getManager()
3417
                                .getPluginsFolder();
3418
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3419
                installerManager
3420
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3421

    
3422
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3423
                                .getSwingInstallerManager().createInstallPackageWizard(
3424
                                                manager.getApplicationFolder(),
3425
                                                manager.getInstallFolder());
3426
                installPackageWizard
3427
                                .setWizardActionListener(new InstallerWizardActionListener() {
3428

    
3429
                                        public void finish(InstallerWizardPanel installerWizard) {
3430
                                                System.exit(0);
3431
                                        }
3432

    
3433
                                        public void cancel(InstallerWizardPanel installerWizard) {
3434
                                                System.exit(0);
3435
                                        }
3436
                                });
3437

    
3438
                // the wizard will show the Typical or Advanced mode option.
3439
                installPackageWizard.setAskTypicalOrCustom(true);
3440
                // default packages will be selected.
3441
                installPackageWizard.setSelectDefaultPackages(true);
3442

    
3443

    
3444
                // 1. Create the frame.
3445
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3446

    
3447
                // 2. What happens when the frame closes?
3448
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3449
                Runtime.getRuntime().addShutdownHook(new Thread() {
3450

    
3451
                        @Override
3452
                        public void run() {
3453
                                getTerminationProcess().saveAndamiConfig();
3454
                        }
3455
                });
3456

    
3457
                // 3. Add the installer panel to the frame
3458
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3459

    
3460
                // 4. Size the frame and center on the screen
3461
                frame.pack();
3462
                frame.setLocationRelativeTo(null);
3463

    
3464
                // 5. Show it.
3465
                frame.setVisible(true);
3466
        }
3467

    
3468
        public static String getInformation() {
3469
                PluginsManager pluginmgr = PluginsLocator.getManager();
3470
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3471

    
3472
                StringWriter writer = new StringWriter();
3473

    
3474
                Properties props = System.getProperties();
3475

    
3476
                // OS information
3477
                String osName = props.getProperty("os.name");
3478
                writer.write("OS\n");
3479
                writer.write("    name   : " + osName + "\n");
3480
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3481
                writer.write("    version: " + props.get("os.version") + "\n");
3482
                if (osName.startsWith("Linux")) {
3483
                        try {
3484
                                String[] command = { "lsb_release", "-a" };
3485
                                Process p = Runtime.getRuntime().exec(command);
3486
                                InputStream is = p.getInputStream();
3487
                                BufferedReader reader = new BufferedReader(
3488
                                                new InputStreamReader(is));
3489
                                String line;
3490
                                while ((line = reader.readLine()) != null) {
3491
                                        writer.write("    " + line + "\n");
3492
                                }
3493
                        } catch (Exception ex) {
3494
                                writer
3495
                                                .write("Can't get detailled os information (lsb_release -a).");
3496
                        }
3497
                }
3498

    
3499
                // JRE information
3500
                writer.write("JRE\n");
3501
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3502
                writer.write("    version: " + props.get("java.version") + "\n");
3503
                writer.write("    home   : " + props.get("java.home") + "\n");
3504

    
3505
                writer.write("HTTP Proxy\n");
3506
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3507
                                + "\n");
3508
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3509
                                + "\n");
3510
                writer.write("    http.proxyUserName : "
3511
                                + props.get("http.proxyUserName") + "\n");
3512
                writer.write("    http.proxyPassword : "
3513
                                + props.get("http.proxyPassword") + "\n");
3514

    
3515
                String skinName = "(unknow)";
3516
                try {
3517
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3518
                } catch (Throwable e) {
3519
                        // Ignore
3520
                }
3521
                writer.write("Application\n");
3522
                writer.write("    locale language         : "
3523
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3524
                writer.write("    application forlder     : "
3525
                                + pluginmgr.getApplicationFolder() + "\n");
3526
                writer.write("    install forlder         : "
3527
                                + pluginmgr.getInstallFolder() + "\n");
3528
                writer.write("    application home forlder: "
3529
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3530
                writer.write("    plugins forlder         : "
3531
                                + pluginmgr.getPluginsFolder() + "\n");
3532
                writer.write("    theme                   : "
3533
                                + Launcher.theme.getSource() + "\n");
3534
                // writer.write("    Skin                    : " + skinName + "\n");
3535

    
3536
                try {
3537
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3538
                                        .getPluginsFolder());
3539
                        writer.write("Installed packages\n");
3540
                        for (int i = 0; i < pkgs.length; i++) {
3541
                                writer.write("    ");
3542
                                writer.write(pkgs[i].toStringCompact());
3543
                                writer.write("\n");
3544
                        }
3545
                } catch (Throwable e) {
3546
                        writer.write("Can't get installed package information.");
3547
                }
3548
                return writer.toString();
3549
        }
3550

    
3551
        private void logger_info(String msg) {
3552
                String info[] = msg.split("\n");
3553
                for (int i = 0; i < info.length; i++) {
3554
                        logger.info(info[i]);
3555
                }
3556
        }
3557

    
3558
}