Statistics
| Revision:

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

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

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

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

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

    
215
        protected static ListBaseException launcherrors = null;
216

    
217
        protected static Theme theme = null;
218

    
219
        private static final class ProxyAuth extends Authenticator {
220

    
221
                private PasswordAuthentication auth;
222

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

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

    
232
        private static Launcher launcherInstance;
233

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

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

    
265
        public static class LaunchException extends ListBaseException {
266

    
267
                private static final long serialVersionUID = 4541192746962684705L;
268

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

    
275
        }
276

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

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

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

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

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

    
300
                initializeApp(args);
301

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

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

    
313
                        public void refresh() {
314
                        }
315
                });
316
                
317
                new PluginsLibrary().initialize();
318

    
319
                try {
320
                        initIconThemes();
321
                } catch (Exception ex) {
322
                        this.addError("Can't initialize icon theme", ex);
323
                }
324
                // Registramos los iconos base
325
                try {
326
                        registerIcons();
327
                } catch (Exception ex) {
328
                        this.addError("Can't register icons", ex);
329
                }
330
                validate();
331

    
332
                // Obtener la personalizaci?n de la aplicaci?n.
333
                try {
334
                        logger.info("Initialize andami theme");
335
                        theme = getTheme(andamiConfig.getPluginsDirectory());
336
                } catch (Exception ex) {
337
                        this.addError("Can't get personalized theme for the application",
338
                                        ex);
339
                }
340

    
341
                // Mostrar la ventana de inicio
342
                Frame f = new Frame();
343
                splashWindow = new MultiSplashWindow(f, theme, 190);
344

    
345
                // 1. Ponemos los datos del proxy
346
                splashWindow.process(10, PluginServices.getText(Launcher.class,
347
                                "SplashWindow.configuring_proxy"));
348
                logger.info("Configute http proxy");
349
                configureProxy();
350

    
351
                // 2. TODO Buscar actualizaciones de los plugins
352
//                splashWindow.process(20, PluginServices.getText(Launcher.class,
353
//                                "SplashWindow.looking_for_updates"));
354
//                try {
355
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
356
//                } catch (Exception ex) {
357
//                        this.addError("Can't downloads plugins", ex);
358
//                }
359

    
360
                // 2.5. Initialize andami libraries
361
                splashWindow.process(25, PluginServices.getText(Launcher.class,
362
                                "SplashWindow.initialize_andami_libraries"));
363
                new DefaultLibrariesInitializer().fullInitialize(true);
364
                
365
                File defaultAddonsRepository = PluginsLocator.getManager()
366
                                .getPluginsFolder();
367
                InstallerManager installerManager = InstallerLocator
368
                                .getInstallerManager();
369
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
370
                installerManager
371
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
372
        
373
                logger.info("Dump system information");
374
                logger_info(getInformation());
375

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

    
386
                // 4. Se configura el classloader del plugin
387
                splashWindow.process(40, PluginServices.getText(Launcher.class,
388
                                "SplashWindow.setting_up_class_loaders"));
389
                try {
390
                        logger.info("Configure plugins class loader");
391
                        this.pluginsClassLoaders();
392
                } catch (Exception ex) {
393
                        this.addError("Can't initialize plugin's classloaders  ", ex);
394
                }
395

    
396
                // 5. Initialize libraries
397
                splashWindow.process(50, PluginServices.getText(Launcher.class,
398
                                "SplashWindow.initialize_libraries"));
399
                initializeLibraries();
400

    
401
                // 6. Se carga un Skin si alguno ide los plugins trae informaci?n
402
                // para ello
403
                splashWindow.process(60, PluginServices.getText(Launcher.class,
404
                                "SplashWindow.looking_for_a_skin"));
405
                // skinPlugin( "com.iver.core.mdiManager.NewSkin");
406
                logger.info("Initialize skin");
407
                skinPlugin(null);
408

    
409
                // 7. Se configura la cola de eventos
410
                splashWindow.process(70, PluginServices.getText(Launcher.class,
411
                                "setting_up_event_queue"));
412
                EventQueue waitQueue = new AndamiEventQueue();
413
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
414

    
415
                // 8. Se configura la mensajer?a del plugin
416
                splashWindow.process(80, PluginServices.getText(Launcher.class,
417
                                "SplashWindow.starting_plugin_internationalization_system"));
418
                pluginsMessages();
419

    
420
                // 9. Se modifica el andami-config con los plugins nuevos
421
                splashWindow.process(90, PluginServices.getText(Launcher.class,
422
                                "SplashWindow.looking_for_a_skin"));
423
                updateAndamiConfig();
424

    
425
                frame = new MDIFrame();
426
                // 10. Se configura el nombre e icono de la aplicaci?n
427
                splashWindow.process(100, PluginServices.getText(Launcher.class,
428
                                "SplashWindow.setting_up_applications_name_and_icons"));
429
                frameIcon(theme);
430

    
431
                // 11. Se prepara el MainFrame para albergar las extensiones
432
                splashWindow.process(110, PluginServices.getText(Launcher.class,
433
                                "SplashWindow.preparing_workbench"));
434
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
435

    
436
                SwingUtilities.invokeAndWait(new Runnable() {
437

    
438
                        public void run() {
439
                                frame.init();
440
                        }
441
                });
442
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
443

    
444
                // 12. Leer el fichero de persistencia
445
                // info de los plugins
446
                // bookmarks de los plugins
447
                splashWindow.process(120, PluginServices.getText(Launcher.class,
448
                                "SplashWindow.loading_plugin_settings"));
449
                loadPluginsPersistence();
450

    
451
                // Se instalan los controles del skin
452
                // 13. Se inicializan todas las extensiones de todos los plugins
453
                splashWindow.process(130, PluginServices.getText(Launcher.class,
454
                                "SplashWindow.initializing_extensions"));
455
                SwingUtilities.invokeAndWait(new Runnable() {
456

    
457
                        public void run() {
458
                                initializeExtensions();
459
                        }
460
                });
461

    
462
                // 14. Se inicializan la extensi?n exclusiva
463
                splashWindow.process(140, PluginServices.getText(Launcher.class,
464
                                "SplashWindow.setting_up_master_extension"));
465
                SwingUtilities.invokeAndWait(new Runnable() {
466

    
467
                        public void run() {
468
                                initializeExclusiveUIExtension();
469
                        }
470
                });
471
                frame.setClassesExtensions(classesExtensions);
472

    
473
                // 15. Se instalan los controles de las extensiones de los plugins
474
                splashWindow.process(150, PluginServices.getText(Launcher.class,
475
                                "SplashWindow.installing_extensions_controls"));
476
                SwingUtilities.invokeAndWait(new Runnable() {
477

    
478
                        public void run() {
479
                                installPluginsControls();
480

    
481
                        }
482
                });
483

    
484
                // 16. Se instalan los menus de las extensiones de los plugins
485
                splashWindow.process(160, PluginServices.getText(Launcher.class,
486
                                "SplashWindow.installing_extensions_menus"));
487
                SwingUtilities.invokeAndWait(new Runnable() {
488

    
489
                        public void run() {
490
                                installPluginsMenus();
491

    
492
                        }
493
                });
494

    
495
                // 17. Se instalan las etiquetas de las extensiones de los plugins
496
                splashWindow.process(170, PluginServices.getText(Launcher.class,
497
                                "SplashWindow.installing_extensions_labels"));
498
                SwingUtilities.invokeAndWait(new Runnable() {
499

    
500
                        public void run() {
501
                                installPluginsLabels();
502

    
503
                        }
504
                });
505

    
506
                // 18. Se instalan los bookmarks de los plugins
507

    
508
                // 19. Se muestra el frame principal
509
                splashWindow.process(180, PluginServices.getText(Launcher.class,
510
                                "creating_main_window"));
511
                frame.setVisible(true);
512

    
513
                /* 
514
                 * Initialize installer local repository folders 
515
                 */
516
                initializeLocalAddOnRepositoryFolders();
517

    
518
                // 19. Se ejecuta el postInitialize
519
                splashWindow.process(190, PluginServices.getText(Launcher.class,
520
                                "SplashWindow.post_initializing_extensions"));
521
                SwingUtilities.invokeAndWait(new Runnable() {
522

    
523
                        public void run() {
524
                                postInitializeExtensions();
525

    
526
                        }
527
                });
528

    
529
                // Definimos un KeyEventDispatcher global para que las extensiones
530
                // puedan registrar sus "teclas r?pidas".
531
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
532
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
533

    
534
                SwingUtilities.invokeAndWait(new Runnable() {
535

    
536
                        public void run() {
537
                                frame.enableControls();
538
                        }
539
                });
540

    
541
                createDefaultIconTheme();
542

    
543
                splashWindow.close();
544
                if (launcherrors != null) {
545
                        NotificationManager.addError(launcherrors);
546
                }
547

    
548
                org.apache.log4j.Logger.getRootLogger().addAppender(
549
                                new NotificationAppender());
550

    
551
        }
552

    
553
        private void initializeLocalAddOnRepositoryFolders() {
554
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
555

    
556
                File defaultAddonsRepository = PluginsLocator.getManager().getPluginsFolder();
557

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

    
595
                logger.debug("Initializing plugins libraries: ");
596
                while (iter.hasNext()) {
597
                        String pName = (String) iter.next();
598
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
599
                        classLoaders.add(ps.getClassLoader());
600
                }
601

    
602
                // Create the libraries initializer and
603
                // initialize the plugin libraries
604
                new DefaultLibrariesInitializer(classLoaders
605
                                .toArray(new ClassLoader[classLoaders.size()]))
606
                                .fullInitialize(true);
607

    
608
                // Remove them all, we don't need them anymore
609
                classLoaders.clear();
610
                classLoaders = null;
611
        }
612

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

    
624
                // Clean temporal files
625
                Utilities.cleanUpTempFiles();
626

    
627
                appName = args[0];
628

    
629
                getOrCreateConfigFolder();
630

    
631
                configureLogging(appName);
632

    
633
                loadAndamiConfig(args[1]);
634

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

    
640
                configureLocales(args);
641

    
642
                logger.info("Load and initialize andami and plugins libraries");
643
                // LibrariesInitializer libsInitializer =
644
                // new DefaultLibrariesInitializer();
645
                // libsInitializer.initialize(true);
646
                // libsInitializer.postInitialize(true);
647

    
648
                logger.info("Configure LookAndFeel");
649
                configureLookAndFeel();
650
        }
651

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

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

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

    
696
                appHomeDir += File.separator + appName;
697
                File parent = new File(appHomeDir);
698
                parent.mkdirs();
699
        }
700

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

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

    
718
        private class NotificationAppender extends AppenderSkeleton {
719

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

    
735
                @Override
736
                public void close() {
737
                        // TODO Auto-generated method stub
738

    
739
                }
740

    
741
                @Override
742
                public boolean requiresLayout() {
743
                        // TODO Auto-generated method stub
744
                        return false;
745
                }
746

    
747
        }
748

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

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

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

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

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

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

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

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

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

    
878
                System.getProperties().put("http.proxyHost", host);
879
                System.getProperties().put("http.proxyPort", port);
880

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

    
888
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
889
                } else {
890
                        Authenticator.setDefault(new ProxyAuth("", ""));
891
                }
892
        }
893

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

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

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

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

    
954
        private void loadPluginsPersistence() throws ConfigurationException {
955
                XMLEntity entity = persistenceFromXML();
956

    
957
                for (int i = 0; i < entity.getChildrenCount(); i++) {
958
                        XMLEntity plugin = entity.getChild(i);
959
                        String pName = plugin
960
                                        .getStringProperty("com.iver.andami.pluginName");
961

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

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

    
984
                XMLEntity entity = new XMLEntity();
985

    
986
                while (i.hasNext()) {
987
                        String pName = i.next();
988
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
989
                        XMLEntity ent = ps.getPersistentXML();
990

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

    
1012
        private void installPluginsLabels() {
1013
                Iterator<String> i = pluginsConfig.keySet().iterator();
1014

    
1015
                while (i.hasNext()) {
1016
                        String name = i.next();
1017
                        PluginConfig pc = pluginsConfig.get(name);
1018
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1019

    
1020
                        LabelSet[] ls = pc.getLabelSet();
1021

    
1022
                        for (int j = 0; j < ls.length; j++) {
1023
                                PluginClassLoader loader = ps.getClassLoader();
1024

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

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

    
1050
        private void fixSkin(SkinExtension skinExtension,
1051
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1052
                // now insert the skin selected.
1053
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1054
                // MDIManagerFactory.setSkinExtension(se,
1055
                // ps.getClassLoader());
1056

    
1057
                Class<? extends IExtension> skinClass;
1058

    
1059
                try {
1060
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1061
                                        .loadClass(skinExtension.getClassName());
1062

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

    
1088
        }
1089

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

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

    
1113
                        if (pc.getExtensions().getSkinExtension() != null) {
1114
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1115
                                // logger.warn(Messages.getString(
1116
                                // "Launcher.Dos_skin_extension"));
1117
                                // }
1118

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

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

    
1151
        }
1152

    
1153
        private static void frameIcon(Theme theme) {
1154
                Iterator<String> i = pluginsConfig.keySet().iterator();
1155

    
1156
                while (i.hasNext()) {
1157
                        String pName = i.next();
1158
                        PluginConfig pc = pluginsConfig.get(pName);
1159
                        if (pc.getIcon() != null) {
1160
                                if (theme.getIcon() != null) {
1161
                                        frame.setIconImage(theme.getIcon().getImage());
1162
                                } else {
1163

    
1164
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1165
                                                        pc.getIcon().getSrc());
1166
                                        frame.setIconImage(icon.getImage());
1167

    
1168
                                }
1169
                                if (theme.getName() != null) {
1170
                                        frame.setTitlePrefix(theme.getName());
1171
                                } else {
1172
                                        frame.setTitlePrefix(pc.getIcon().getText());
1173
                                }
1174
                                if (theme.getBackgroundImage() != null) {
1175

    
1176
                                        PluginServices.getMDIManager().setBackgroundImage(
1177
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1178
                                }
1179
                        }
1180
                }
1181
        }
1182

    
1183
        private void initializeExtensions() {
1184

    
1185
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1186
                                pluginsOrdered.size());
1187
                classLoaders.add(getClass().getClassLoader());
1188
                Iterator<String> iter = pluginsOrdered.iterator();
1189

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

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

    
1215
                        Extension[] exts = pc.getExtensions().getExtension();
1216

    
1217
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1218
                                        new ExtensionComparator());
1219

    
1220
                        for (int j = 0; j < exts.length; j++) {
1221
                                if (!exts[j].getActive()) {
1222
                                        continue;
1223
                                }
1224

    
1225
                                if (orderedExtensions.contains(exts[j])) {
1226
                                        logger.warn("Two extensions with the same priority ("
1227
                                                        + exts[j].getClassName() + ")");
1228
                                }
1229

    
1230
                                orderedExtensions.add(exts[j]);
1231
                        }
1232

    
1233
                        Iterator<Extension> e = orderedExtensions.iterator();
1234

    
1235
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1236
                        while (e.hasNext()) {
1237
                                Extension extension = e.next();
1238
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1239

    
1240
                                try {
1241
                                        logger.info("Initializing " + extension.getClassName()
1242
                                                        + "...");
1243
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1244
                                                        .getClassLoader().loadClass(
1245
                                                                        extension.getClassName());
1246
                                        extensionInstance = extensionClass.newInstance();
1247

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

    
1266
                                        extensionInstance.initialize();
1267
                                        extensions.add(extensionInstance);
1268

    
1269
                                } catch (NoClassDefFoundError e1) {
1270
                                        this.addError("Can't find class extension ("
1271
                                                        + extension.getClassName() + ")", e1);
1272
                                } catch (Throwable e1) {
1273
                                        this.addError("Can't initialize extension '"
1274
                                                        + extension.getClassName() + "'.", e1);
1275
                                }
1276
                        }
1277
                }
1278
        }
1279

    
1280
        private void postInitializeExtensions() {
1281
                logger.info("PostInitializing extensions: ");
1282

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

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

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

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

    
1351
                                }
1352
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1353
                                while (toolBars.hasMoreElements()) {
1354
                                        ToolBar toolBar = toolBars.nextElement();
1355

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

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

    
1413
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1414
                Iterator<String> it = pluginsConfig.keySet().iterator();
1415

    
1416
                while (it.hasNext()) {
1417
                        String pluginName = it.next();
1418
                        PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1419
                        PluginServices pluginService = pluginsServices.get(pluginName);
1420
                        PluginClassLoader loader =  pluginService.getClassLoader();
1421

    
1422
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1423

    
1424
                        Extensions extensionConfig = pluginConfig.getExtensions();
1425
                        
1426
                        
1427
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1428
                        registerActionOfExtensions(actionManager, extensiones, loader);
1429

    
1430
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1431
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1432

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

    
1461
                }
1462
        }
1463
        
1464

    
1465
        private TreeSet<SortableMenu> getOrderedMenus() { 
1466

    
1467
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1468
                                new MenuComparator());
1469

    
1470
                Iterator<String> i = pluginsConfig.keySet().iterator();
1471

    
1472
                while (i.hasNext()) {
1473
                        String pName = i.next();
1474
                        try {
1475
                                PluginServices ps = pluginsServices.get(pName);
1476
                                PluginConfig pc = pluginsConfig.get(pName);
1477

    
1478
                                Extension[] exts = pc.getExtensions().getExtension();
1479

    
1480
                                for (int j = 0; j < exts.length; j++) {
1481
                                        if (!exts[j].getActive()) {
1482
                                                continue;
1483
                                        }
1484

    
1485
                                        Menu[] menus = exts[j].getMenu();
1486

    
1487
                                        for (int k = 0; k < menus.length; k++) {
1488
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1489
                                                                exts[j], menus[k]);
1490

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

    
1500
                                                orderedMenus.add(sm);
1501
                                        }
1502
                                }
1503

    
1504
                                // Se instalan las extensiones de MDI
1505
                                SkinExtension[] skinExts = pc.getExtensions()
1506
                                                .getSkinExtension();
1507
                                for (int j = 0; j < skinExts.length; j++) {
1508

    
1509
                                        if (skinExts[j] != null) {
1510
                                                Menu[] menu = skinExts[j].getMenu();
1511

    
1512
                                                for (int k = 0; k < menu.length; k++) {
1513
                                                        SortableMenu sm = new SortableMenu(ps
1514
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1515

    
1516
                                                        if (orderedMenus.contains(sm)) {
1517
                                                                this
1518
                                                                                .addError(Messages
1519
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1520
                                                                                                + skinExts[j].getClassName());
1521
                                                        }
1522

    
1523
                                                        orderedMenus.add(sm);
1524
                                                }
1525
                                        }
1526
                                }
1527

    
1528
                        } catch (Throwable e) {
1529
                                addError("Error initializing menus of plugin '" + pName + "'",
1530
                                                e);
1531
                        }
1532

    
1533
                }
1534

    
1535
                return orderedMenus;
1536
        }
1537

    
1538
        private void installPluginsMenus() {
1539
                logger.info("installPluginsMenus");
1540

    
1541
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1542

    
1543
                // Se itera por los menus ordenados
1544
                Iterator<SortableMenu> e = orderedMenus.iterator();
1545

    
1546
                // Se ordenan los menues
1547
                while (e.hasNext()) {
1548
                        try {
1549
                                SortableMenu sm = e.next();
1550

    
1551
                                logger.info(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1552
                                
1553
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1554

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

    
1577
        public class PluginMenuItem {
1578
                private Menu menu;
1579
                private PluginClassLoader loader;
1580
                private SkinExtensionType extension;
1581

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

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

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

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

    
1655
                Iterator<String> i = pluginsConfig.keySet().iterator();
1656

    
1657
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1658
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1659
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1660
                                new ExtensionComparator());
1661

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

    
1672
                                Extension[] exts = pc.getExtensions().getExtension();
1673

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

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

    
1704
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1705
                                new ToolComparator());
1706
                Iterator<Extension> e = orderedExtensions.iterator();
1707

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

    
1718
                                // get tools from toolbars
1719
                                for (int k = 0; k < toolbars.length; k++) {
1720
                                        ActionTool[] tools = toolbars[k].getActionTool();
1721

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

    
1730
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1731

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

    
1741
                                // get controls for statusBar
1742
                                PluginServices ps = extensionPluginServices.get(ext);
1743
                                PluginClassLoader loader = ps.getClassLoader();
1744

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

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

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

    
1848
                                SkinExtension[] skinExts = pc.getExtensions()
1849
                                                .getSkinExtension();
1850
                                for (int j = 0; j < skinExts.length; j++) {
1851

    
1852
                                        if (skinExts[j] != null) {
1853
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1854

    
1855
                                                for (int k = 0; k < toolbars.length; k++) {
1856
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1857

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

    
1865
                                                        SelectableTool[] sTools = toolbars[k]
1866
                                                                        .getSelectableTool();
1867

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

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

    
1923
        /**
1924
         * Adds new plugins to the the andami-config file.
1925
         */
1926
        private void updateAndamiConfig() {
1927
                Set<String> olds = new HashSet<String>();
1928

    
1929
                Plugin[] plugins = andamiConfig.getPlugin();
1930

    
1931
                for (int i = 0; i < plugins.length; i++) {
1932
                        olds.add(plugins[i].getName());
1933
                }
1934

    
1935
                Iterator<PluginServices> i = pluginsServices.values().iterator();
1936

    
1937
                while (i.hasNext()) {
1938
                        PluginServices ps = i.next();
1939

    
1940
                        if (!olds.contains(ps.getPluginName())) {
1941
                                Plugin p = new Plugin();
1942
                                p.setName(ps.getPluginName());
1943
                                p.setUpdate(false);
1944

    
1945
                                andamiConfig.addPlugin(p);
1946
                        }
1947
                }
1948
        }
1949

    
1950
        private void pluginsClassLoaders() {
1951
                Set<String> installed = new HashSet<String>();
1952

    
1953
                // Se itera hasta que est?n todos instalados
1954
                while (installed.size() != pluginsConfig.size()) {
1955
                        boolean circle = true;
1956

    
1957
                        // Hacemos una pasada por todos los plugins
1958
                        Iterator<String> i = pluginsConfig.keySet().iterator();
1959

    
1960
                        while (i.hasNext()) {
1961
                                String pluginName = i.next();
1962
                                PluginConfig config = (PluginConfig) pluginsConfig
1963
                                                .get(pluginName);
1964

    
1965
                                if (installed.contains(pluginName)) {
1966
                                        continue;
1967
                                }
1968

    
1969
                                // Se obtienen las dependencias y sus class loaders
1970
                                boolean ready = true;
1971
                                Depends[] dependencies = config.getDepends();
1972
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1973

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

    
1984
                                                continue;
1985
                                        }
1986

    
1987
                                        if (!installed.contains(dependencies[j].getPluginName())) {
1988
                                                ready = false;
1989
                                        } else {
1990
                                                loaders[j] = (pluginsServices.get(dependencies[j]
1991
                                                                .getPluginName())).getClassLoader();
1992
                                        }
1993
                                }
1994

    
1995
                                // Si no est?n sus dependencias satisfechas se aborta la
1996
                                // instalaci?n
1997
                                if (!ready) {
1998
                                        continue;
1999
                                }
2000

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

    
2007
                                        public boolean accept(File pathname) {
2008
                                                return (pathname.getName().toUpperCase()
2009
                                                                .endsWith(".JAR"))
2010
                                                                || (pathname.getName().toUpperCase()
2011
                                                                                .endsWith(".ZIP"));
2012
                                        }
2013
                                });
2014

    
2015
                                URL[] urls = new URL[jarFiles.length];
2016

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

    
2027
                                PluginClassLoader loader;
2028

    
2029
                                try {
2030
                                        loader = new PluginClassLoader(urls, andamiConfig
2031
                                                        .getPluginsDirectory()
2032
                                                        + File.separator + pluginName, Launcher.class
2033
                                                        .getClassLoader(), loaders);
2034

    
2035
                                        PluginServices ps = new PluginServices(loader);
2036

    
2037
                                        pluginsServices.put(ps.getPluginName(), ps);
2038

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

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

    
2057
                        if (circle) {
2058
                                this.addError(Messages
2059
                                                .getString("Launcher.Hay_dependencias_circulares"));
2060

    
2061
                                break;
2062
                        }
2063
                }
2064

    
2065
                // Se eliminan los plugins que no fueron instalados
2066
                Iterator<String> i = pluginsConfig.keySet().iterator();
2067

    
2068
                while (i.hasNext()) {
2069
                        String pluginName = i.next();
2070
                        PluginServices ps = (PluginServices) pluginsServices
2071
                                        .get(pluginName);
2072

    
2073
                        if (ps == null) {
2074
                                pluginsConfig.remove(pluginName);
2075
                                i = pluginsConfig.keySet().iterator();
2076
                        }
2077
                }
2078
                registerActions();
2079
        }
2080

    
2081
        private void pluginsMessages() {
2082
                Iterator<String> iterator = pluginsOrdered.iterator();
2083
                PluginConfig config;
2084
                PluginServices ps;
2085

    
2086
                while (iterator.hasNext()) {
2087
                        String pluginName = iterator.next();
2088
                        config = pluginsConfig.get(pluginName);
2089
                        ps = pluginsServices.get(pluginName);
2090

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

    
2101
        static public PluginServices getPluginServices(String name) {
2102
                return (PluginServices) pluginsServices.get(name);
2103
        }
2104

    
2105
        static String getPluginsDir() {
2106
                return andamiConfig.getPluginsDirectory();
2107
        }
2108

    
2109
        static void setPluginsDir(String s) {
2110
                andamiConfig.setPluginsDirectory(s);
2111
        }
2112

    
2113
        static MDIFrame getMDIFrame() {
2114
                return frame;
2115
        }
2116

    
2117
        private void loadPlugins(String pluginsDirectory) {
2118
                File pDir = new File(pluginsDirectory);
2119

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

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

    
2139
                for (int i = 0; i < pluginDirs.length; i++) {
2140
                        if (pluginDirs[i].isDirectory()) {
2141
                                String pluginName =  pluginDirs[i].getName();
2142
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2143
                                                "config.xml");
2144

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

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

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

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

    
2203
                BufferedOutputStream os = new BufferedOutputStream(
2204
                                new FileOutputStream(tmpFile));
2205
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2206
                andamiConfig.marshal(writer);
2207
                writer.close();
2208

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

    
2225
        private static void andamiConfigFromXML(String file)
2226
                        throws ConfigurationException {
2227
                File xml = new File(file);
2228

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

    
2261
        private static AndamiConfig getDefaultAndamiConfig() {
2262
                AndamiConfig andamiConfig = new AndamiConfig();
2263

    
2264
                Andami andami = new Andami();
2265
                andami.setUpdate(true);
2266
                andamiConfig.setAndami(andami);
2267
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2268
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2269
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2270

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

    
2282
                andamiConfig.setPlugin(new Plugin[0]);
2283
                return andamiConfig;
2284
        }
2285

    
2286
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2287
                File xml = getPluginsPersistenceFile(true);
2288

    
2289
                if (xml.exists()) {
2290
                        InputStreamReader reader = null;
2291

    
2292
                        try {
2293
                                reader = XMLEncodingUtils.getReader(xml);
2294
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2295
                                return new XMLEntity(tag);
2296
                        } catch (FileNotFoundException e) {
2297
                                throw new ConfigurationException(e);
2298
                        } catch (MarshalException e) {
2299

    
2300
                                // try to reopen with default encoding (for backward
2301
                                // compatibility)
2302
                                try {
2303
                                        reader = new FileReader(xml);
2304
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2305
                                        return new XMLEntity(tag);
2306

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

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

    
2356
        }
2357

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

    
2365
                File xml = getPluginsPersistenceFile(false);
2366
                OutputStreamWriter writer = null;
2367

    
2368
                try {
2369
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2370
                                        CASTORENCODING);
2371
                        entity.getXmlTag().marshal(writer);
2372
                        writer.close();
2373

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

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

    
2406
        static MDIFrame getFrame() {
2407
                return frame;
2408
        }
2409

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

    
2420
        static HashMap getClassesExtensions() {
2421
                return classesExtensions;
2422
        }
2423

    
2424
        private static Extensions[] getExtensions() {
2425
                List<Extensions> array = new ArrayList<Extensions>();
2426
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2427

    
2428
                while (iter.hasNext()) {
2429
                        array.add(iter.next().getExtensions());
2430
                }
2431

    
2432
                return array.toArray(new Extensions[array.size()]);
2433
        }
2434

    
2435
        public static Iterator getExtensionIterator() {
2436
                return extensions.iterator();
2437
        }
2438

    
2439
        public static HashMap getPluginConfig() {
2440
                return pluginsConfig;
2441
        }
2442

    
2443
        public static Extension getExtension(String s) {
2444
                Extensions[] exts = getExtensions();
2445

    
2446
                for (int i = 0; i < exts.length; i++) {
2447
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2448
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2449
                                        return exts[i].getExtension(j);
2450
                                }
2451
                        }
2452
                }
2453

    
2454
                return null;
2455
        }
2456

    
2457
        public static AndamiConfig getAndamiConfig() {
2458
                return andamiConfig;
2459
        }
2460

    
2461
        private static class ExtensionComparator implements Comparator {
2462

    
2463
                public int compare(Object o1, Object o2) {
2464
                        Extension e1 = (Extension) o1;
2465
                        Extension e2 = (Extension) o2;
2466

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

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

    
2475
                        if (e2.hasPriority() && !e1.hasPriority()) {
2476
                                return Integer.MAX_VALUE;
2477
                        }
2478

    
2479
                        if (e1.getPriority() != e2.getPriority()) {
2480
                                return e2.getPriority() - e1.getPriority();
2481
                        } else {
2482
                                return (e2.toString().compareTo(e1.toString()));
2483
                        }
2484
                }
2485
        }
2486

    
2487
        private static class MenuComparator implements Comparator<SortableMenu> {
2488

    
2489
                private static ExtensionComparator extComp = new ExtensionComparator();
2490

    
2491
                public int compare(SortableMenu e1, SortableMenu e2) {
2492

    
2493
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2494
                                if (e1.extension instanceof SkinExtensionType) {
2495
                                        return 1;
2496
                                } else if (e2.extension instanceof SkinExtensionType) {
2497
                                        return -1;
2498
                                } else {
2499
                                        return extComp.compare(e1.extension, e2.extension);
2500
                                }
2501
                        }
2502

    
2503
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2504
                                return Integer.MIN_VALUE;
2505
                        }
2506

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

    
2524
        private static class SortableMenu {
2525

    
2526
                public PluginClassLoader loader;
2527
                public Menu menu;
2528
                public SkinExtensionType extension;
2529

    
2530
                public SortableMenu(PluginClassLoader loader,
2531
                                SkinExtensionType skinExt, Menu menu2) {
2532
                        extension = skinExt;
2533
                        menu = menu2;
2534
                        this.loader = loader;
2535
                }
2536
                
2537
        }
2538

    
2539
        private static class SortableTool {
2540

    
2541
                public PluginClassLoader loader;
2542
                public ToolBar toolbar;
2543
                public ActionTool actiontool;
2544
                public SelectableTool selectabletool;
2545
                public SkinExtensionType extension;
2546

    
2547
                public SortableTool(PluginClassLoader loader,
2548
                                SkinExtensionType skinExt, ToolBar toolbar2,
2549
                                ActionTool actiontool2) {
2550
                        extension = skinExt;
2551
                        toolbar = toolbar2;
2552
                        actiontool = actiontool2;
2553
                        this.loader = loader;
2554
                }
2555

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

    
2566
        private static class ToolBarComparator implements Comparator<SortableTool> {
2567

    
2568
                private static ExtensionComparator extComp = new ExtensionComparator();
2569

    
2570
                public int compare(SortableTool e1, SortableTool e2) {
2571

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

    
2578
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2579
                                if (e1.extension instanceof SkinExtensionType) {
2580
                                        return 1;
2581
                                } else if (e2.extension instanceof SkinExtensionType) {
2582
                                        return -1;
2583
                                } else {
2584
                                        return extComp.compare(e1.extension, e2.extension);
2585
                                }
2586
                        }
2587

    
2588
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2589
                                return Integer.MIN_VALUE;
2590
                        }
2591

    
2592
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2593
                                return Integer.MAX_VALUE;
2594
                        }
2595
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2596
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2597
                        }
2598

    
2599
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2600
                                        && e1.toolbar.getSelectableTool().equals(
2601
                                                        e2.toolbar.getSelectableTool())) {
2602
                                return 0;
2603
                        }
2604
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2605
                }
2606
        }
2607

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

    
2631
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2632

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

    
2642
                        if (e1.actiontool != null) {
2643
                                if (e1.actiontool.hasPosition()) {
2644
                                        e1Position = e1.actiontool.getPosition();
2645
                                }
2646
                        } else if (e1.selectabletool != null) {
2647
                                if (e1.selectabletool.hasPosition()) {
2648
                                        e1Position = e1.selectabletool.getPosition();
2649
                                }
2650
                        }
2651

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

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

    
2680
        /**
2681
         * validates the user before starting gvsig
2682
         * 
2683
         */
2684
        private static void validate() {
2685

    
2686
                IAuthentication session = null;
2687
                try {
2688
                        session = (IAuthentication) Class.forName(
2689
                                        "com.iver.andami.authentication.Session").newInstance();
2690

    
2691
                } catch (ClassNotFoundException e) {
2692
                        return;
2693
                } catch (InstantiationException e) {
2694
                        return;
2695
                } catch (IllegalAccessException e) {
2696
                        return;
2697
                }
2698

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

    
2711
        public static String getDefaultLookAndFeel() {
2712
                String osName = (String) System.getProperty("os.name");
2713

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

    
2722
                return UIManager.getSystemLookAndFeelClassName();
2723
        }
2724

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

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

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

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

    
2833
        logger.info("Loading i18n resources from the application and user "
2834
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2835

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

    
2850
        // Finally load the andami own i18n resources
2851
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2852
            "Andami Launcher");
2853
        }
2854

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

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

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

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

    
2921
                logger
2922
                                .error(Messages
2923
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
2924
                                                + " '" + name + "'");
2925
        }
2926

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

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

    
2986
        /**
2987
         * Manages Andami termination process
2988
         * 
2989
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2990
         */
2991
        public class TerminationProcess {
2992

    
2993
                private boolean proceed = false;
2994
                private UnsavedDataPanel panel = null;
2995

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

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

    
3025
                        try {
3026
                                // Persistencia de los plugins
3027
                                savePluginPersistence();
3028
                                savePluginsProperties();
3029
                        } catch (Exception ex) {
3030
                                logger
3031
                                                .error(
3032
                                                                "There was an error exiting application, can't save plugins properties",
3033
                                                                ex);
3034
                        }
3035

    
3036
                        // Finalize all the extensions
3037
                        finalizeExtensions();
3038

    
3039
                        try {
3040
                                // Clean any temp data created
3041
                                Utilities.cleanUpTempFiles();
3042
                        } catch (Exception ex) {
3043
                                logger
3044
                                                .error(
3045
                                                                "There was an error exiting application, can't remove temporary files",
3046
                                                                ex);
3047
                        }
3048

    
3049
                        logger.info("Quiting application.");
3050

    
3051
                        // Para la depuraci?n de memory leaks
3052
                        System.gc();
3053

    
3054
                        System.exit(0);
3055
                }
3056

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

    
3085
                private void savePluginsProperties() {
3086
                        PluginsManager manager = PluginsLocator.getManager();
3087
                        List<PluginServices> plugins = manager.getPlugins();
3088
                        for (PluginServices plugin : plugins) {
3089
                                if (plugin != null) {
3090
                                        plugin.savePluginProperties();
3091
                                }
3092
                        }
3093
                }
3094

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

    
3116
                private IUnsavedData[] getUnsavedData() throws Exception {
3117
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3118
                        IExtension exclusiveExtension = PluginServices
3119
                                        .getExclusiveUIExtension();
3120

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

    
3158
                public UnsavedDataPanel getUnsavedDataPanel() {
3159
                        if (panel == null) {
3160
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3161
                        }
3162
                        return panel;
3163
                }
3164

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

    
3175
                        // there was no unsaved data
3176
                        if (unsavedData.length == 0) {
3177
                                int option = JOptionPane
3178
                                                .showConfirmDialog(frame, Messages
3179
                                                                .getString("MDIFrame.quiere_salir"), Messages
3180
                                                                .getString("MDIFrame.salir"),
3181
                                                                JOptionPane.YES_NO_OPTION);
3182
                                return option;
3183
                        }
3184

    
3185
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3186
                        panel.setUnsavedDataArray(unsavedData);
3187

    
3188
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3189

    
3190
                                public void cancel(UnsavedDataPanel panel) {
3191
                                        proceed(false);
3192
                                        PluginServices.getMDIManager().closeWindow(panel);
3193

    
3194
                                }
3195

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

    
3200
                                }
3201

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

    
3233
                                                        try {
3234
                                                                unsavedDataArray = getUnsavedData();
3235
                                                        } catch (Exception e) {
3236
                                                                // This exception has been registered before
3237
                                                        }
3238
                                                        panel.setUnsavedDataArray(unsavedDataArray);
3239
                                                        return;
3240
                                                }
3241
                                        }
3242
                                        proceed(true);
3243
                                        PluginServices.getMDIManager().closeWindow(panel);
3244
                                }
3245
                        });
3246

    
3247
                        PluginServices.getMDIManager().addWindow(panel);
3248
                        if (proceed) {
3249
                                return JOptionPane.YES_OPTION;
3250
                        } else {
3251
                                return JOptionPane.NO_OPTION;
3252
                        }
3253
                }
3254

    
3255
                private void proceed(boolean proceed) {
3256
                        this.proceed = proceed;
3257
                }
3258

    
3259
        }
3260

    
3261
        public static TerminationProcess getTerminationProcess() {
3262
                return (new Launcher()).new TerminationProcess();
3263
        }
3264

    
3265
        /**
3266
         * Launch the gvSIG package installer.
3267
         * 
3268
         * @throws Exception
3269
         *             if there is any error
3270
         */
3271
        private void doInstall(String[] args) throws Exception {
3272
                String installURL = null;
3273
                String installURLFile = null;
3274
                String gvSIGVersion = null;
3275
                String[] myArgs = new String[3];
3276

    
3277
                Options options = new Options();
3278
                options.addOption("i", "install", false, "install");
3279
                options.addOption("u", "installURL", true, "installURL");
3280
                options.addOption("f", "installURLFile", true, "installURLFile");
3281
                options.addOption("v", "installVersion", true, "installVersion");
3282
                options.addOption("A", "applicationName", true, "applicationName");
3283
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3284
                options.addOption("l", "language", true, "language");
3285

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

    
3328
                initializeApp(myArgs);
3329
                initializeLibraries();
3330
                AndamiConfig config = getAndamiConfig();
3331
                config.setLocaleLanguage(locale.getLanguage());
3332
                config.setLocaleCountry(locale.getCountry());
3333
                config.setLocaleVariant(locale.getVariant());
3334
                
3335
                InstallerManager installerManager = InstallerLocator
3336
                                .getInstallerManager();
3337
                // set the gvSIG version to the install manager, to compose the download
3338
                // URL:
3339
                installerManager.setVersion(gvSIGVersion);
3340

    
3341

    
3342
                // Configure default index download URL
3343
                if (installURL != null) {
3344
                        SwingInstallerLocator.getSwingInstallerManager()
3345
                                        .setDefaultDownloadURL(installURL);
3346
                }
3347

    
3348
                if (installURLFile != null) {
3349
                        // TODO: Convertir a File y pasarlo
3350
                        SwingInstallerLocator.getSwingInstallerManager()
3351
                                        .setDefaultDownloadURL(new File(installURLFile));
3352
                }
3353

    
3354
                // Launch installer
3355
                PluginsManager manager = PluginsLocator.getManager();
3356

    
3357
                File defaultAddonsRepository = PluginsLocator.getManager()
3358
                                .getPluginsFolder();
3359
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3360
                installerManager
3361
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3362

    
3363
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3364
                                .getSwingInstallerManager().createInstallPackageWizard(
3365
                                                manager.getApplicationFolder(),
3366
                                                manager.getInstallFolder());
3367
                installPackageWizard
3368
                                .setWizardActionListener(new InstallerWizardActionListener() {
3369

    
3370
                                        public void finish(InstallerWizardPanel installerWizard) {
3371
                                                System.exit(0);
3372
                                        }
3373

    
3374
                                        public void cancel(InstallerWizardPanel installerWizard) {
3375
                                                System.exit(0);
3376
                                        }
3377
                                });
3378

    
3379
                // the wizard will show the Typical or Advanced mode option.
3380
                installPackageWizard.setAskTypicalOrCustom(true);
3381
                // default packages will be selected.
3382
                installPackageWizard.setSelectDefaultPackages(true);
3383

    
3384

    
3385
                // 1. Create the frame.
3386
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3387

    
3388
                // 2. What happens when the frame closes?
3389
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3390
                Runtime.getRuntime().addShutdownHook(new Thread() {
3391

    
3392
                        @Override
3393
                        public void run() {
3394
                                getTerminationProcess().saveAndamiConfig();
3395
                        }
3396
                });
3397

    
3398
                // 3. Add the installer panel to the frame
3399
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3400

    
3401
                // 4. Size the frame and center on the screen
3402
                frame.pack();
3403
                frame.setLocationRelativeTo(null);
3404

    
3405
                // 5. Show it.
3406
                frame.setVisible(true);
3407
        }
3408

    
3409
        public static String getInformation() {
3410
                PluginsManager pluginmgr = PluginsLocator.getManager();
3411
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3412

    
3413
                StringWriter writer = new StringWriter();
3414

    
3415
                Properties props = System.getProperties();
3416

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

    
3440
                // JRE information
3441
                writer.write("JRE\n");
3442
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3443
                writer.write("    version: " + props.get("java.version") + "\n");
3444
                writer.write("    home   : " + props.get("java.home") + "\n");
3445

    
3446
                writer.write("HTTP Proxy\n");
3447
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3448
                                + "\n");
3449
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3450
                                + "\n");
3451
                writer.write("    http.proxyUserName : "
3452
                                + props.get("http.proxyUserName") + "\n");
3453
                writer.write("    http.proxyPassword : "
3454
                                + props.get("http.proxyPassword") + "\n");
3455

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

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

    
3492
        private void logger_info(String msg) {
3493
                String info[] = msg.split("\n");
3494
                for (int i = 0; i < info.length; i++) {
3495
                        logger.info(info[i]);
3496
                }
3497
        }
3498

    
3499
}