Statistics
| Revision:

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

History | View | Annotate | Download (104 KB)

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

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

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

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

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

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

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

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

    
216
        protected static ListBaseException launcherrors = null;
217

    
218
        protected static Theme theme = null;
219

    
220
        private static final class ProxyAuth extends Authenticator {
221

    
222
                private PasswordAuthentication auth;
223

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

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

    
233
        private static Launcher launcherInstance;
234

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

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

    
266
        public static class LaunchException extends ListBaseException {
267

    
268
                private static final long serialVersionUID = 4541192746962684705L;
269

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

    
276
        }
277

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

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

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

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

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

    
301
                initializeApp(args);
302

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
442
                SwingUtilities.invokeAndWait(new Runnable() {
443

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

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

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

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

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

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

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

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

    
487
                        }
488
                });
489

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

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

    
498
                        }
499
                });
500

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

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

    
509
                        }
510
                });
511

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

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

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

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

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

    
532
                        }
533
                });
534

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

    
540
                SwingUtilities.invokeAndWait(new Runnable() {
541

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

    
547
                createDefaultIconTheme();
548

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

    
554
                org.apache.log4j.Logger.getRootLogger().addAppender(
555
                                new NotificationAppender());
556

    
557
        }
558

    
559
        private void initializeLocalAddOnRepositoryFolders() {
560
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
561

    
562
                File defaultAddonsRepository = PluginsLocator.getManager().getPluginsFolder();
563

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

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

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

    
614
                // Remove them all, we don't need them anymore
615
                classLoaders.clear();
616
                classLoaders = null;
617
        }
618

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

    
630
                // Clean temporal files
631
                Utilities.cleanUpTempFiles();
632

    
633
                appName = args[0];
634

    
635
                getOrCreateConfigFolder();
636

    
637
                configureLogging(appName);
638

    
639
                loadAndamiConfig(args[1]);
640

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

    
646
                configureLocales(args);
647

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

    
654
                logger.info("Configure LookAndFeel");
655
                configureLookAndFeel();
656
        }
657

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

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

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

    
702
                appHomeDir += File.separator + appName;
703
                File parent = new File(appHomeDir);
704
                parent.mkdirs();
705
        }
706

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

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

    
724
        private class NotificationAppender extends AppenderSkeleton {
725

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

    
741
                @Override
742
                public void close() {
743
                        // TODO Auto-generated method stub
744

    
745
                }
746

    
747
                @Override
748
                public boolean requiresLayout() {
749
                        // TODO Auto-generated method stub
750
                        return false;
751
                }
752

    
753
        }
754

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

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

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

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

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

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

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

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

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

    
884
                System.getProperties().put("http.proxyHost", host);
885
                System.getProperties().put("http.proxyPort", port);
886

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

    
894
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
895
                } else {
896
                        Authenticator.setDefault(new ProxyAuth("", ""));
897
                }
898
        }
899

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

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

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

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

    
960
        private void loadPluginsPersistence() throws ConfigurationException {
961
                XMLEntity entity = persistenceFromXML();
962

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

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

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

    
990
                XMLEntity entity = new XMLEntity();
991

    
992
                while (i.hasNext()) {
993
                        String pName = i.next();
994
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
995
                        XMLEntity ent = ps.getPersistentXML();
996

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

    
1018
        private void installPluginsLabels() {
1019
                Iterator<String> i = pluginsConfig.keySet().iterator();
1020

    
1021
                while (i.hasNext()) {
1022
                        String name = i.next();
1023
                        PluginConfig pc = pluginsConfig.get(name);
1024
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1025

    
1026
                        LabelSet[] ls = pc.getLabelSet();
1027

    
1028
                        for (int j = 0; j < ls.length; j++) {
1029
                                PluginClassLoader loader = ps.getClassLoader();
1030

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

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

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

    
1063
                Class<? extends IExtension> skinClass;
1064

    
1065
                try {
1066
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1067
                                        .loadClass(skinExtension.getClassName());
1068

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

    
1094
        }
1095

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

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

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

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

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

    
1157
        }
1158

    
1159
        private static void frameIcon(Theme theme) {
1160
                Iterator<String> i = pluginsConfig.keySet().iterator();
1161

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

    
1170
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1171
                                                        pc.getIcon().getSrc());
1172
                                        frame.setIconImage(icon.getImage());
1173

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

    
1182
                                        PluginServices.getMDIManager().setBackgroundImage(
1183
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1184
                                }
1185
                        }
1186
                }
1187
        }
1188

    
1189
        private void initializeExtensions() {
1190

    
1191
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1192
                                pluginsOrdered.size());
1193
                classLoaders.add(getClass().getClassLoader());
1194
                Iterator<String> iter = pluginsOrdered.iterator();
1195

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

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

    
1221
                        Extension[] exts = pc.getExtensions().getExtension();
1222

    
1223
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1224
                                        new ExtensionComparator());
1225

    
1226
                        for (int j = 0; j < exts.length; j++) {
1227
                                if (!exts[j].getActive()) {
1228
                                        continue;
1229
                                }
1230

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

    
1236
                                orderedExtensions.add(exts[j]);
1237
                        }
1238

    
1239
                        Iterator<Extension> e = orderedExtensions.iterator();
1240

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

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

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

    
1272
                                        extensionInstance.initialize();
1273
                                        extensions.add(extensionInstance);
1274

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

    
1286
        private void postInitializeExtensions() {
1287
                logger.info("PostInitializing extensions: ");
1288

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

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

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

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

    
1357
                                }
1358
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1359
                                while (toolBars.hasMoreElements()) {
1360
                                        ToolBar toolBar = toolBars.nextElement();
1361

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

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

    
1419
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1420
                Iterator<String> it = pluginsConfig.keySet().iterator();
1421

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

    
1428
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1429

    
1430
                        Extensions extensionConfig = pluginConfig.getExtensions();
1431
                        
1432
                        
1433
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1434
                        registerActionOfExtensions(actionManager, extensiones, loader);
1435

    
1436
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1437
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1438

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

    
1467
                }
1468
        }
1469
        
1470

    
1471
        private TreeSet<SortableMenu> getOrderedMenus() { 
1472

    
1473
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1474
                                new MenuComparator());
1475

    
1476
                Iterator<String> i = pluginsConfig.keySet().iterator();
1477

    
1478
                while (i.hasNext()) {
1479
                        String pName = i.next();
1480
                        try {
1481
                                PluginServices ps = pluginsServices.get(pName);
1482
                                PluginConfig pc = pluginsConfig.get(pName);
1483

    
1484
                                Extension[] exts = pc.getExtensions().getExtension();
1485

    
1486
                                for (int j = 0; j < exts.length; j++) {
1487
                                        if (!exts[j].getActive()) {
1488
                                                continue;
1489
                                        }
1490

    
1491
                                        Menu[] menus = exts[j].getMenu();
1492

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

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

    
1506
                                                orderedMenus.add(sm);
1507
                                        }
1508
                                }
1509

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

    
1515
                                        if (skinExts[j] != null) {
1516
                                                Menu[] menu = skinExts[j].getMenu();
1517

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

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

    
1529
                                                        orderedMenus.add(sm);
1530
                                                }
1531
                                        }
1532
                                }
1533

    
1534
                        } catch (Throwable e) {
1535
                                addError("Error initializing menus of plugin '" + pName + "'",
1536
                                                e);
1537
                        }
1538

    
1539
                }
1540

    
1541
                return orderedMenus;
1542
        }
1543

    
1544
        private void installPluginsMenus() {
1545
                logger.info("installPluginsMenus");
1546

    
1547
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1548

    
1549
                // Se itera por los menus ordenados
1550
                Iterator<SortableMenu> e = orderedMenus.iterator();
1551

    
1552
                // Se ordenan los menues
1553
                while (e.hasNext()) {
1554
                        try {
1555
                                SortableMenu sm = e.next();
1556

    
1557
                                logger.info(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1558
                                
1559
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1560

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

    
1583
        public class PluginMenuItem {
1584
                private Menu menu;
1585
                private PluginClassLoader loader;
1586
                private SkinExtensionType extension;
1587

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

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

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

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

    
1661
                Iterator<String> i = pluginsConfig.keySet().iterator();
1662

    
1663
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1664
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1665
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1666
                                new ExtensionComparator());
1667

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

    
1678
                                Extension[] exts = pc.getExtensions().getExtension();
1679

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

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

    
1710
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1711
                                new ToolComparator());
1712
                Iterator<Extension> e = orderedExtensions.iterator();
1713

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

    
1724
                                // get tools from toolbars
1725
                                for (int k = 0; k < toolbars.length; k++) {
1726
                                        ActionTool[] tools = toolbars[k].getActionTool();
1727

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

    
1736
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1737

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

    
1747
                                // get controls for statusBar
1748
                                PluginServices ps = extensionPluginServices.get(ext);
1749
                                PluginClassLoader loader = ps.getClassLoader();
1750

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

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

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

    
1854
                                SkinExtension[] skinExts = pc.getExtensions()
1855
                                                .getSkinExtension();
1856
                                for (int j = 0; j < skinExts.length; j++) {
1857

    
1858
                                        if (skinExts[j] != null) {
1859
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1860

    
1861
                                                for (int k = 0; k < toolbars.length; k++) {
1862
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1863

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

    
1871
                                                        SelectableTool[] sTools = toolbars[k]
1872
                                                                        .getSelectableTool();
1873

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

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

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

    
1935
                Plugin[] plugins = andamiConfig.getPlugin();
1936

    
1937
                for (int i = 0; i < plugins.length; i++) {
1938
                        olds.add(plugins[i].getName());
1939
                }
1940

    
1941
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1942

    
1943
                while (i.hasNext()) {
1944
                        PluginServices ps = i.next();
1945

    
1946
                        if (!olds.contains(ps.getPluginName())) {
1947
                                Plugin p = new Plugin();
1948
                                p.setName(ps.getPluginName());
1949
                                p.setUpdate(false);
1950

    
1951
                                andamiConfig.addPlugin(p);
1952
                        }
1953
                }
1954
        }
1955

    
1956
        private void pluginsClassLoaders() {
1957
                Set<String> installed = new HashSet<String>();
1958

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

    
1963
                        // Hacemos una pasada por todos los plugins
1964
                        Iterator<String> i = pluginsConfig.keySet().iterator();
1965

    
1966
                        while (i.hasNext()) {
1967
                                String pluginName = i.next();
1968
                                PluginConfig config = (PluginConfig) pluginsConfig
1969
                                                .get(pluginName);
1970

    
1971
                                if (installed.contains(pluginName)) {
1972
                                        continue;
1973
                                }
1974

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

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

    
1990
                                                continue;
1991
                                        }
1992

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

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

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

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

    
2021
                                URL[] urls = new URL[jarFiles.length];
2022

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

    
2033
                                PluginClassLoader loader;
2034

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

    
2041
                                        PluginServices ps = new PluginServices(loader);
2042

    
2043
                                        pluginsServices.put(ps.getPluginName(), ps);
2044

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

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

    
2063
                        if (circle) {
2064
                                this.addError(Messages
2065
                                                .getString("Launcher.Hay_dependencias_circulares"));
2066

    
2067
                                break;
2068
                        }
2069
                }
2070

    
2071
                // Se eliminan los plugins que no fueron instalados
2072
                Iterator<String> i = pluginsConfig.keySet().iterator();
2073

    
2074
                while (i.hasNext()) {
2075
                        String pluginName = i.next();
2076
                        PluginServices ps = (PluginServices) pluginsServices
2077
                                        .get(pluginName);
2078

    
2079
                        if (ps == null) {
2080
                                pluginsConfig.remove(pluginName);
2081
                                i = pluginsConfig.keySet().iterator();
2082
                        }
2083
                }
2084
                registerActions();
2085
        }
2086

    
2087
        private void pluginsMessages() {
2088
                Iterator<String> iterator = pluginsOrdered.iterator();
2089
                PluginConfig config;
2090
                PluginServices ps;
2091

    
2092
                while (iterator.hasNext()) {
2093
                        String pluginName = iterator.next();
2094
                        config = pluginsConfig.get(pluginName);
2095
                        ps = pluginsServices.get(pluginName);
2096

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

    
2107
        static public PluginServices getPluginServices(String name) {
2108
                return (PluginServices) pluginsServices.get(name);
2109
        }
2110

    
2111
        static String getPluginsDir() {
2112
                return andamiConfig.getPluginsDirectory();
2113
        }
2114

    
2115
        static void setPluginsDir(String s) {
2116
                andamiConfig.setPluginsDirectory(s);
2117
        }
2118

    
2119
        static MDIFrame getMDIFrame() {
2120
                return frame;
2121
        }
2122

    
2123
        private void loadPlugins(String pluginsDirectory) {
2124
                File pDir = new File(pluginsDirectory);
2125

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

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

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

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

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

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

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

    
2209
                BufferedOutputStream os = new BufferedOutputStream(
2210
                                new FileOutputStream(tmpFile));
2211
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2212
                andamiConfig.marshal(writer);
2213
                writer.close();
2214

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

    
2231
        private static void andamiConfigFromXML(String file)
2232
                        throws ConfigurationException {
2233
                File xml = new File(file);
2234

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

    
2267
        private static AndamiConfig getDefaultAndamiConfig() {
2268
                AndamiConfig andamiConfig = new AndamiConfig();
2269

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

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

    
2288
                andamiConfig.setPlugin(new Plugin[0]);
2289
                return andamiConfig;
2290
        }
2291

    
2292
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2293
                File xml = getPluginsPersistenceFile(true);
2294

    
2295
                if (xml.exists()) {
2296
                        InputStreamReader reader = null;
2297

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

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

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

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

    
2362
        }
2363

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

    
2371
                File xml = getPluginsPersistenceFile(false);
2372
                OutputStreamWriter writer = null;
2373

    
2374
                try {
2375
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2376
                                        CASTORENCODING);
2377
                        entity.getXmlTag().marshal(writer);
2378
                        writer.close();
2379

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

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

    
2412
        static MDIFrame getFrame() {
2413
                return frame;
2414
        }
2415

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

    
2426
        static HashMap getClassesExtensions() {
2427
                return classesExtensions;
2428
        }
2429

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

    
2434
                while (iter.hasNext()) {
2435
                        array.add(iter.next().getExtensions());
2436
                }
2437

    
2438
                return array.toArray(new Extensions[array.size()]);
2439
        }
2440

    
2441
        public static Iterator getExtensionIterator() {
2442
                return extensions.iterator();
2443
        }
2444

    
2445
        public static HashMap getPluginConfig() {
2446
                return pluginsConfig;
2447
        }
2448

    
2449
        public static Extension getExtension(String s) {
2450
                Extensions[] exts = getExtensions();
2451

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

    
2460
                return null;
2461
        }
2462

    
2463
        public static AndamiConfig getAndamiConfig() {
2464
                return andamiConfig;
2465
        }
2466

    
2467
        private static class ExtensionComparator implements Comparator {
2468

    
2469
                public int compare(Object o1, Object o2) {
2470
                        Extension e1 = (Extension) o1;
2471
                        Extension e2 = (Extension) o2;
2472

    
2473
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2474
                                return -1;
2475
                        }
2476

    
2477
                        if (e1.hasPriority() && !e2.hasPriority()) {
2478
                                return Integer.MIN_VALUE;
2479
                        }
2480

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

    
2485
                        if (e1.getPriority() != e2.getPriority()) {
2486
                                return e2.getPriority() - e1.getPriority();
2487
                        } else {
2488
                                return (e2.toString().compareTo(e1.toString()));
2489
                        }
2490
                }
2491
        }
2492

    
2493
        private static class MenuComparator implements Comparator<SortableMenu> {
2494

    
2495
                private static ExtensionComparator extComp = new ExtensionComparator();
2496

    
2497
                public int compare(SortableMenu e1, SortableMenu e2) {
2498

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

    
2509
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2510
                                return Integer.MIN_VALUE;
2511
                        }
2512

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

    
2530
        private static class SortableMenu {
2531

    
2532
                public PluginClassLoader loader;
2533
                public Menu menu;
2534
                public SkinExtensionType extension;
2535

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

    
2545
        private static class SortableTool {
2546

    
2547
                public PluginClassLoader loader;
2548
                public ToolBar toolbar;
2549
                public ActionTool actiontool;
2550
                public SelectableTool selectabletool;
2551
                public SkinExtensionType extension;
2552

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

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

    
2572
        private static class ToolBarComparator implements Comparator<SortableTool> {
2573

    
2574
                private static ExtensionComparator extComp = new ExtensionComparator();
2575

    
2576
                public int compare(SortableTool e1, SortableTool e2) {
2577

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

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

    
2594
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2595
                                return Integer.MIN_VALUE;
2596
                        }
2597

    
2598
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2599
                                return Integer.MAX_VALUE;
2600
                        }
2601
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2602
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2603
                        }
2604

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

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

    
2637
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2638

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

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

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

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

    
2686
        /**
2687
         * validates the user before starting gvsig
2688
         * 
2689
         */
2690
        private static void validate() {
2691

    
2692
                IAuthentication session = null;
2693
                try {
2694
                        session = (IAuthentication) Class.forName(
2695
                                        "com.iver.andami.authentication.Session").newInstance();
2696

    
2697
                } catch (ClassNotFoundException e) {
2698
                        return;
2699
                } catch (InstantiationException e) {
2700
                        return;
2701
                } catch (IllegalAccessException e) {
2702
                        return;
2703
                }
2704

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

    
2717
        public static String getDefaultLookAndFeel() {
2718
                String osName = (String) System.getProperty("os.name");
2719

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

    
2728
                return UIManager.getSystemLookAndFeelClassName();
2729
        }
2730

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

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

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

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

    
2839
        logger.info("Loading i18n resources from the application and user "
2840
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2841

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

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

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

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

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

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

    
2927
                logger
2928
                                .error(Messages
2929
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2930
                                                + " '" + name + "'");
2931
        }
2932

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

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

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

    
2999
                private boolean proceed = false;
3000
                private UnsavedDataPanel panel = null;
3001

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

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

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

    
3042
                        // Finalize all the extensions
3043
                        finalizeExtensions();
3044

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

    
3055
                        logger.info("Quiting application.");
3056

    
3057
                        // Para la depuraci?n de memory leaks
3058
                        System.gc();
3059

    
3060
                        System.exit(0);
3061
                }
3062

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

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

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

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

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

    
3164
                public UnsavedDataPanel getUnsavedDataPanel() {
3165
                        if (panel == null) {
3166
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3167
                        }
3168
                        return panel;
3169
                }
3170

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

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

    
3191
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3192
                        panel.setUnsavedDataArray(unsavedData);
3193

    
3194
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3195

    
3196
                                public void cancel(UnsavedDataPanel panel) {
3197
                                        proceed(false);
3198
                                        PluginServices.getMDIManager().closeWindow(panel);
3199

    
3200
                                }
3201

    
3202
                                public void discard(UnsavedDataPanel panel) {
3203
                                        proceed(true);
3204
                                        PluginServices.getMDIManager().closeWindow(panel);
3205

    
3206
                                }
3207

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

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

    
3253
                        PluginServices.getMDIManager().addWindow(panel);
3254
                        if (proceed) {
3255
                                return JOptionPane.YES_OPTION;
3256
                        } else {
3257
                                return JOptionPane.NO_OPTION;
3258
                        }
3259
                }
3260

    
3261
                private void proceed(boolean proceed) {
3262
                        this.proceed = proceed;
3263
                }
3264

    
3265
        }
3266

    
3267
        public static TerminationProcess getTerminationProcess() {
3268
                return (new Launcher()).new TerminationProcess();
3269
        }
3270

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

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

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

    
3334
                initializeApp(myArgs);
3335
                initializeLibraries();
3336
                AndamiConfig config = getAndamiConfig();
3337
                config.setLocaleLanguage(locale.getLanguage());
3338
                config.setLocaleCountry(locale.getCountry());
3339
                config.setLocaleVariant(locale.getVariant());
3340
                
3341
                InstallerManager installerManager = InstallerLocator
3342
                                .getInstallerManager();
3343
                // set the gvSIG version to the install manager, to compose the download
3344
                // URL:
3345
                installerManager.setVersion(gvSIGVersion);
3346

    
3347

    
3348
                // Configure default index download URL
3349
                if (installURL != null) {
3350
                        SwingInstallerLocator.getSwingInstallerManager()
3351
                                        .setDefaultDownloadURL(installURL);
3352
                }
3353

    
3354
                if (installURLFile != null) {
3355
                        // TODO: Convertir a File y pasarlo
3356
                        SwingInstallerLocator.getSwingInstallerManager()
3357
                                        .setDefaultDownloadURL(new File(installURLFile));
3358
                }
3359

    
3360
                // Launch installer
3361
                PluginsManager manager = PluginsLocator.getManager();
3362

    
3363
                File defaultAddonsRepository = PluginsLocator.getManager()
3364
                                .getPluginsFolder();
3365
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3366
                installerManager
3367
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3368

    
3369
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3370
                                .getSwingInstallerManager().createInstallPackageWizard(
3371
                                                manager.getApplicationFolder(),
3372
                                                manager.getInstallFolder());
3373
                installPackageWizard
3374
                                .setWizardActionListener(new InstallerWizardActionListener() {
3375

    
3376
                                        public void finish(InstallerWizardPanel installerWizard) {
3377
                                                System.exit(0);
3378
                                        }
3379

    
3380
                                        public void cancel(InstallerWizardPanel installerWizard) {
3381
                                                System.exit(0);
3382
                                        }
3383
                                });
3384

    
3385
                // the wizard will show the Typical or Advanced mode option.
3386
                installPackageWizard.setAskTypicalOrCustom(true);
3387
                // default packages will be selected.
3388
                installPackageWizard.setSelectDefaultPackages(true);
3389

    
3390

    
3391
                // 1. Create the frame.
3392
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3393

    
3394
                // 2. What happens when the frame closes?
3395
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3396
                Runtime.getRuntime().addShutdownHook(new Thread() {
3397

    
3398
                        @Override
3399
                        public void run() {
3400
                                getTerminationProcess().saveAndamiConfig();
3401
                        }
3402
                });
3403

    
3404
                // 3. Add the installer panel to the frame
3405
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3406

    
3407
                // 4. Size the frame and center on the screen
3408
                frame.pack();
3409
                frame.setLocationRelativeTo(null);
3410

    
3411
                // 5. Show it.
3412
                frame.setVisible(true);
3413
        }
3414

    
3415
        public static String getInformation() {
3416
                PluginsManager pluginmgr = PluginsLocator.getManager();
3417
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3418

    
3419
                StringWriter writer = new StringWriter();
3420

    
3421
                Properties props = System.getProperties();
3422

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

    
3446
                // JRE information
3447
                writer.write("JRE\n");
3448
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3449
                writer.write("    version: " + props.get("java.version") + "\n");
3450
                writer.write("    home   : " + props.get("java.home") + "\n");
3451

    
3452
                writer.write("HTTP Proxy\n");
3453
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3454
                                + "\n");
3455
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3456
                                + "\n");
3457
                writer.write("    http.proxyUserName : "
3458
                                + props.get("http.proxyUserName") + "\n");
3459
                writer.write("    http.proxyPassword : "
3460
                                + props.get("http.proxyPassword") + "\n");
3461

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

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

    
3498
        private void logger_info(String msg) {
3499
                String info[] = msg.split("\n");
3500
                for (int i = 0; i < info.length; i++) {
3501
                        logger.info(info[i]);
3502
                }
3503
        }
3504

    
3505
}