Statistics
| Revision:

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

History | View | Annotate | Download (77.1 KB)

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

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

    
86
import javax.jnlp.BasicService;
87
import javax.jnlp.ServiceManager;
88
import javax.jnlp.UnavailableServiceException;
89
import javax.swing.ImageIcon;
90
import javax.swing.JButton;
91
import javax.swing.JComponent;
92
import javax.swing.JOptionPane;
93
import javax.swing.JPopupMenu;
94
import javax.swing.SwingUtilities;
95
import javax.swing.UIManager;
96

    
97
import org.apache.log4j.PatternLayout;
98
import org.apache.log4j.PropertyConfigurator;
99
import org.apache.log4j.RollingFileAppender;
100
import org.exolab.castor.xml.MarshalException;
101
import org.exolab.castor.xml.ValidationException;
102
import org.gvsig.andami.authentication.IAuthentication;
103
import org.gvsig.andami.authentication.LoginUI;
104
import org.gvsig.andami.config.generate.Andami;
105
import org.gvsig.andami.config.generate.AndamiConfig;
106
import org.gvsig.andami.config.generate.Plugin;
107
import org.gvsig.andami.iconthemes.IIconTheme;
108
import org.gvsig.andami.iconthemes.IconThemeManager;
109
import org.gvsig.andami.messages.Messages;
110
import org.gvsig.andami.messages.NotificationManager;
111
import org.gvsig.andami.plugins.ExclusiveUIExtension;
112
import org.gvsig.andami.plugins.ExtensionDecorator;
113
import org.gvsig.andami.plugins.IExtension;
114
import org.gvsig.andami.plugins.PluginClassLoader;
115
import org.gvsig.andami.plugins.config.generate.ActionTool;
116
import org.gvsig.andami.plugins.config.generate.ComboButton;
117
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
118
import org.gvsig.andami.plugins.config.generate.ComboScale;
119
import org.gvsig.andami.plugins.config.generate.Depends;
120
import org.gvsig.andami.plugins.config.generate.Extension;
121
import org.gvsig.andami.plugins.config.generate.Extensions;
122
import org.gvsig.andami.plugins.config.generate.LabelSet;
123
import org.gvsig.andami.plugins.config.generate.Menu;
124
import org.gvsig.andami.plugins.config.generate.PluginConfig;
125
import org.gvsig.andami.plugins.config.generate.PopupMenu;
126
import org.gvsig.andami.plugins.config.generate.PopupMenus;
127
import org.gvsig.andami.plugins.config.generate.SelectableTool;
128
import org.gvsig.andami.plugins.config.generate.SkinExtension;
129
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
130
import org.gvsig.andami.plugins.config.generate.ToolBar;
131
import org.gvsig.andami.plugins.status.IExtensionStatus;
132
import org.gvsig.andami.plugins.status.IUnsavedData;
133
import org.gvsig.andami.ui.AndamiEventQueue;
134
import org.gvsig.andami.ui.MDIManagerLoadException;
135
import org.gvsig.andami.ui.fonts.FontUtils;
136
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
137
import org.gvsig.andami.ui.mdiFrame.NewStatusBar;
138
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
139
import org.gvsig.andami.ui.splash.MultiSplashWindow;
140
import org.gvsig.andami.ui.theme.Theme;
141
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
142
import org.gvsig.tools.library.LibrariesInitializer;
143
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
144
import org.gvsig.utils.DateTime;
145
import org.gvsig.utils.XMLEntity;
146
import org.gvsig.utils.xml.XMLEncodingUtils;
147
import org.gvsig.utils.xmlEntity.generate.XmlTag;
148
import org.slf4j.Logger;
149
import org.slf4j.LoggerFactory;
150

    
151

    
152

    
153
/**
154
 * <p>
155
 * Andami's launching class. This is the class used to create the Andami's plugin environment.<br>
156
 * </p>
157
 *
158
 * <p>
159
 * <b>Syntax:</b>
160
 * <br>
161
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or semicolon-separated(windows) list of files containg base library of classes}]
162
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
163
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
164
 * [{list of additional custom application arguments separated by spaces}]
165
 * </p>
166
 *
167
 *
168
 * @author $author$
169
 * @version $Revision: 30580 $
170
 */
171
public class Launcher {
172
        private static Logger logger = LoggerFactory.getLogger(Launcher.class.getName());
173
        private static Preferences prefs = Preferences.userRoot().node( "gvsig.connection" );
174
        private static AndamiConfig andamiConfig;
175
        private static MultiSplashWindow splashWindow;
176
        private static String appName;
177
        private static Locale locale;
178
        private static HashMap pluginsConfig = new HashMap();
179
        private static HashMap pluginsServices = new HashMap();
180
        private static MDIFrame frame;
181
        private static HashMap classesExtensions = new HashMap();
182
        private static List<LibrariesInitializer> libInitializers;
183
        private static String andamiConfigPath;
184
        private static String pluginsPersistencePath;
185
        private static final String nonWinDefaultLookAndFeel =  "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
186

    
187
    private static ArrayList pluginsOrdered = new ArrayList();
188
    private static ArrayList extensions=new ArrayList();
189
    private static String appHomeDir = null;
190
    // it seems castor uses this encoding
191
    private static final String CASTORENCODING = "UTF8";
192
    
193
        private static final class ProxyAuth extends Authenticator {
194
                private PasswordAuthentication auth;
195

    
196
                private ProxyAuth(String user, String pass) {
197
                        auth = new PasswordAuthentication(user, pass.toCharArray());
198
                }
199

    
200
                protected PasswordAuthentication getPasswordAuthentication() {
201
                        return auth;
202
                }
203
        }
204

    
205
    public static void main(String[] args) throws Exception {
206
            try{
207

    
208
                    if (!validJVM()){
209
                            System.exit(-1);
210
                    }
211

    
212
                    if (args.length < 1) {
213
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
214
                    }
215

    
216
                    //  Clean temporal files
217
                    Utilities.cleanUpTempFiles();
218

    
219
                    appName = args[0];
220

    
221
                    //Se crea el directorio de configuraci?n de la aplicaci?n
222
                    appHomeDir = System.getProperty(args[0]+".home");
223
                    if (appHomeDir == null)
224
                            appHomeDir = System.getProperty("user.home");
225

    
226
                    appHomeDir += File.separator + args[0] + File.separator;
227
                    File parent = new File( appHomeDir );
228
                    parent.mkdirs();
229

    
230
                    andamiConfigPath = appHomeDir + "andami-config.xml";
231
                    pluginsPersistencePath = appHomeDir +
232
                    "plugins-persistence.xml";
233

    
234
                    // Configurar el log4j
235
                    Launcher.class.getClassLoader()
236
                        .getResource(".");
237
                    PropertyConfigurator.configure("log4j.properties");
238

    
239
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
240
                    RollingFileAppender fa = new RollingFileAppender(l,
241
                                    appHomeDir + args[0] + ".log", false);
242
                    fa.setMaxFileSize("512KB");
243
                    fa.setMaxBackupIndex(3);
244
                    org.apache.log4j.Logger.getRootLogger().addAppender(fa);
245

    
246
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
247
                    // locale
248
                    // Buscar actualizaci?nes al comenzar
249
                    //  Andami
250
                    //  Plugins
251
                    // Directorio de las extensiones
252
                    andamiConfigFromXML(andamiConfigPath);
253
                    andamiConfig.setPluginsDirectory(args[1]);
254

    
255
                    // Hacemos visibles los argumentos como una propiedad est?tica
256
                    // de plugin services para quien lo quiera usar (por ejemplo, para
257
                    // cargar un proyecto por l?nea de comandos)
258
                    PluginServices.setArguments(args);
259

    
260
                    configureLocales(args);
261

    
262
                    //Se pone el lookAndFeel
263
                    try {
264
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
265
                            if (lookAndFeel == null)
266
                                    lookAndFeel = getDefaultLookAndFeel();
267
                            UIManager.setLookAndFeel(lookAndFeel);
268
                    } catch (Exception e) {
269
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
270
                    }
271
                    FontUtils.initFonts();
272

    
273
                    // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
274
                    // System.setSecurityManager(null);
275
                    Policy.setPolicy(new Policy() {
276
                            public PermissionCollection getPermissions(CodeSource codesource) {
277
                                    Permissions perms = new Permissions();
278
                                    perms.add(new AllPermission());
279
                                    return (perms);
280
                            }
281
                            public void
282
                            refresh() {}
283
                    });
284

    
285
                    initIconThemes();
286
//                    Registramos los iconos base
287
                    registerIcons();
288
                    validate();
289

    
290
                    // Obtener la personalizaci?n de la aplicaci?n.
291
                    Theme theme=getTheme();
292

    
293
                    // Mostrar la ventana de inicio
294
                    Frame f=new Frame();
295
                    splashWindow=new MultiSplashWindow(f,theme, 190);
296

    
297
                    // 1. Ponemos los datos del proxy
298
                    splashWindow.process(10,
299
                                    PluginServices.getText(Launcher.class, "SplashWindow.configuring_proxy"));
300
                    configureProxy();
301

    
302
                    // 2. TODO Buscar actualizaciones de los plugins
303
                    splashWindow.process(20,
304
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_updates"));
305
                    downloadExtensions(andamiConfig.getPluginsDirectory());
306

    
307
                    // 3. Se leen los config.xml de los plugins -----++++
308
                    splashWindow.process(30,
309
                                    PluginServices.getText(Launcher.class, "SplashWindow.reading_plugins_config.xml"));
310
                    loadPlugins(andamiConfig.getPluginsDirectory());
311

    
312
                    // 4. Se configura el classloader del plugin
313
                    splashWindow.process(40,
314
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_class_loaders"));
315
                    pluginsClassLoaders();
316

    
317
                    // 5. Se carga un Skin si alguno de los plugins trae informaci?n para ello
318
                    splashWindow.process(50,
319
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
320
//                    skinPlugin(        "com.iver.core.mdiManager.NewSkin");
321
                    skinPlugin(null);
322

    
323
                    // 6. Se configura la cola de eventos
324
                    splashWindow.process(60,
325
                                    PluginServices.getText(Launcher.class, "setting_up_event_queue"));
326
                    EventQueue waitQueue = new AndamiEventQueue();
327
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
328

    
329
                    // 7. Se configura la mensajer?a del plugin
330
                    splashWindow.process(70,
331
                                    PluginServices.getText(Launcher.class, "SplashWindow.starting_plugin_internationalization_system"));
332
                    pluginsMessages();
333

    
334
                    // 8. Se modifica el andami-config con los plugins nuevos
335
                    splashWindow.process(80,
336
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
337
                    updateAndamiConfig();
338

    
339

    
340
                    frame = new MDIFrame();
341
                    // 9. Se configura el nombre e icono de la aplicaci?n
342
                    splashWindow.process(90,
343
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_applications_name_and_icons"));
344
                    frameIcon(theme);
345

    
346
                    // 10. Se prepara el MainFrame para albergar las extensiones
347
                    splashWindow.process(100,
348
                                    PluginServices.getText(Launcher.class, "SplashWindow.preparing_workbench"));
349
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
350

    
351
                    SwingUtilities.invokeAndWait(new Runnable() {
352
                            public void run() {
353
                                    frame.init();
354
                            }
355
                    });
356

    
357

    
358

    
359
                    // 11. Leer el fichero de persistencia
360
                    //  info de los plugins
361
                    //  bookmarks de los plugins
362
                    splashWindow.process(110,
363
                                    PluginServices.getText(Launcher.class, "SplashWindow.loading_plugin_settings"));
364
                    loadPluginsPersistence();
365

    
366

    
367

    
368
                    // Se instalan los controles del skin
369
                    // 12. Se inicializan todas las extensiones de todos los plugins
370
                    splashWindow.process(120,
371
                                        PluginServices.getText(Launcher.class, "SplashWindow.initializing_extensions"));
372
                    SwingUtilities.invokeAndWait(new Runnable() {
373
                            public void run() {
374
                                    initializeExtensions();
375
                            }
376
                    });
377

    
378
                    // 13. Se inicializan la extensi?n exclusiva
379
                        splashWindow.process(130,
380
                                        PluginServices.getText(Launcher.class, "SplashWindow.setting_up_master_extension"));
381
                        SwingUtilities.invokeAndWait(new Runnable() {
382
                            public void run() {
383
                                    initializeExclusiveUIExtension();
384
                            }
385
                    });
386
                    frame.setClassesExtensions(classesExtensions);
387

    
388

    
389

    
390

    
391

    
392
                    // 14. Se instalan los controles de las extensiones de los plugins
393
                    splashWindow.process(140,
394
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_controls"));
395
                    SwingUtilities.invokeAndWait(new Runnable() {
396
                            public void run() {
397
                                    installPluginsControls();
398

    
399
                            }
400
                    });
401

    
402
                    // 15. Se instalan los menus de las extensiones de los plugins
403
                    splashWindow.process(150,
404
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_menus"));
405
                    SwingUtilities.invokeAndWait(new Runnable() {
406
                            public void run() {
407
                                    installPluginsMenus();
408

    
409
                            }
410
                    });
411

    
412
                    // 16. Se instalan las etiquetas de las extensiones de los plugins
413
                    splashWindow.process(160,
414
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_labels"));
415
                    SwingUtilities.invokeAndWait(new Runnable() {
416
                            public void run() {
417
                                    installPluginsLabels();
418

    
419
                            }
420
                    });
421

    
422

    
423
                    // 17. Se instalan los bookmarks de los plugins
424

    
425
                    // 18. Se muestra el frame principal
426
                    splashWindow.process(180,
427
                                    PluginServices.getText(Launcher.class, "creating_main_window"));
428
                    frame.setVisible(true);
429

    
430
                    // 19. Se ejecuta el postInitialize
431
                        splashWindow.process(190,
432
                                        PluginServices.getText(Launcher.class, "SplashWindow.post_initializing_extensions"));
433
                    SwingUtilities.invokeAndWait(new Runnable() {
434
                            public void run() {
435
                                    postInitializeExtensions();
436

    
437
                            }
438
                    });
439

    
440

    
441
                    // Definimos un KeyEventDispatcher global para que las extensiones
442
                    // puedan registrar sus "teclas r?pidas".
443
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
444
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
445

    
446
                    SwingUtilities.invokeAndWait(new Runnable() {
447
                            public void run() {
448
                                    frame.enableControls();
449
                            }
450
                    });
451
                    splashWindow.close();
452
            }catch(Exception e){
453
                    logger.error("excepci?n al arrancar", e);
454
                    System.exit(-1);
455
            }
456

    
457
    }
458

    
459
    private static void registerIcons(){
460
            PluginServices.getIconTheme().registerDefault(
461
                            "login-gvsig",
462
                            LoginUI.class.getClassLoader().getResource("images/login_gvsig.png")
463
                    );
464
            PluginServices.getIconTheme().registerDefault(
465
                            "splash-gvsig",
466
                            MultiSplashWindow.class.getClassLoader().getResource("images/splash.png")
467
                    );
468
            PluginServices.getIconTheme().registerDefault(
469
                            "info-icon",
470
                            NewStatusBar.class.getClassLoader().getResource("images/info.gif")
471
                    );
472
            PluginServices.getIconTheme().registerDefault(
473
                            "error-icon",
474
                            NewStatusBar.class.getClassLoader().getResource("images/error.gif")
475
                    );
476
            PluginServices.getIconTheme().registerDefault(
477
                            "warning-icon",
478
                            NewStatusBar.class.getClassLoader().getResource("images/warning.gif")
479
                    );
480
            PluginServices.getIconTheme().registerDefault(
481
                            "no-icon",
482
                            NewStatusBar.class.getClassLoader().getResource("images/no_icon.png")
483
                    );
484
    }
485

    
486
    /**
487
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
488
     * la aplicaci?n.
489
     *
490
     * @return Theme
491
     */
492
    private static Theme getTheme() {
493
            Theme theme=new Theme();
494
            String name=PluginServices.getArgumentByName("andamiTheme");
495
                //File file=new File("theme/andami-theme.xml");
496
            File file;
497
            if (name==null){
498
                    file=new File("theme/andami-theme.xml");
499
            }else{
500
                    file=new File(name);
501
            }
502

    
503
            if (file.exists()) {
504
                        theme.readTheme(file);
505
                }
506
                return theme;
507
        }
508
        /**
509
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
510
     *del proxy.
511
     */
512
        private static void configureProxy() {
513
                String host = prefs.get("firewall.http.host", "");
514
                String port = prefs.get("firewall.http.port", "");
515

    
516
                System.getProperties().put("http.proxyHost", host);
517
                System.getProperties().put("http.proxyPort", port);
518

    
519
                // Ponemos el usuario y clave del proxy, si existe
520
                String proxyUser = prefs.get("firewall.http.user",null);
521
                String proxyPassword = prefs.get("firewall.http.password", null);
522
                if (proxyUser != null )
523
                {
524
                        System.getProperties().put("http.proxyUserName", proxyUser);
525
                        System.getProperties().put("http.proxyPassword", proxyPassword);
526

    
527
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
528
                                                        proxyPassword));
529
                } else {
530
                        Authenticator.setDefault(new ProxyAuth("", ""));
531
                }
532
        }
533

    
534
        /**
535
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal de Andami.
536
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
537
         * @author LWS
538
         */
539
        private static void restoreMDIStatus(XMLEntity xml) {
540
                if (xml == null) xml = new XMLEntity();
541
                //  restore frame size
542
                Dimension sz = new Dimension(700,580);
543
                if (xml.contains("MDIFrameSize")) {
544
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
545
                        sz = new Dimension(wh[0], wh[1]);
546
                }
547
                frame.setSize(sz);
548
                //  restore frame location
549
                Point pos = new Point(10,10);
550
                if (xml.contains("MDIFramePos")) {
551
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
552
                        pos = new Point(xy[0], xy[1]);
553
                }
554
                frame.setLocation(pos);
555

    
556
                //  restore frame status (Maximized, minimized, etc);
557
                int state = java.awt.Frame.MAXIMIZED_BOTH;
558
                if (xml.contains("MDIFrameState")) {
559
                        state = xml.getIntProperty("MDIFrameState");
560
                }
561
                frame.setExtendedState(state);
562
        }
563

    
564
        private static XMLEntity saveMDIStatus() {
565
                XMLEntity xml = new XMLEntity();
566
                // save frame size
567
                int [] wh = new int[2];
568
                wh[0] = frame.getWidth();
569
                wh[1] = frame.getHeight();
570
                xml.putProperty("MDIFrameSize", wh);
571
                // save frame location
572
                int [] xy = new int[2];
573
                xy[0] = frame.getX();
574
                xy[1] = frame.getY();
575
                xml.putProperty("MDIFramePos", xy);
576
                // save frame status
577
                xml.putProperty("MDIFrameState", frame.getExtendedState());
578
                return xml;
579
        }
580

    
581
    private static boolean validJVM() {
582
        char thirdCharacter = System.getProperty("java.version").charAt(2);
583
        if (thirdCharacter < '4'){
584
            return false;
585
            }else{
586
                return true;
587
            }
588
    }
589

    
590
        private static void loadPluginsPersistence() throws ConfigurationException {
591
                XMLEntity entity = persistenceFromXML();
592

    
593
                for (int i = 0; i < entity.getChildrenCount(); i++) {
594
                        XMLEntity plugin = entity.getChild(i);
595
                        String pName = plugin.getStringProperty(
596
                                        "com.iver.andami.pluginName");
597
                        if (pluginsServices.get(pName)!= null){
598
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
599
                        } else {
600
                                if (pName.startsWith("Andami.Launcher"))
601
                                        restoreMDIStatus(plugin);
602
                        }
603
                }
604
        }
605

    
606
        /**
607
         * Salva la persistencia de los plugins.
608
         * @author LWS
609
         */
610
        private static void savePluginPersistence() {
611
                Iterator i = pluginsConfig.keySet().iterator();
612

    
613
                XMLEntity entity = new XMLEntity();
614

    
615
                while (i.hasNext()) {
616
                        String pName = (String) i.next();
617
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
618
                        XMLEntity ent = ps.getPersistentXML();
619

    
620
                        if (ent != null) {
621
                                ent.putProperty("com.iver.andami.pluginName", pName);
622
                                entity.addChild(ent);
623
                        }
624
                }
625
                XMLEntity ent = saveMDIStatus();
626
                if (ent != null) {
627
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
628
                        entity.addChild(ent);
629
                }
630
                try {
631
                        persistenceToXML(entity);
632
                } catch (ConfigurationException e1) {
633
                        logger.error(Messages.getString(
634
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
635
                                e1);
636
                }
637
        }
638

    
639
        private static void installPluginsLabels() {
640
                Iterator i = pluginsConfig.keySet().iterator();
641

    
642
                while (i.hasNext()) {
643
                        String name = (String) i.next();
644
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
645
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
646

    
647
                        LabelSet[] ls = pc.getLabelSet();
648

    
649
                        for (int j = 0; j < ls.length; j++) {
650
                                PluginClassLoader loader = ps.getClassLoader();
651

    
652
                                try {
653
                                        Class clase = loader.loadClass(ls[j].getClassName());
654
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
655
                                } catch (ClassNotFoundException e) {
656
                                        logger.error(Messages.getString("Launcher.labelset_class"),
657
                                                e);
658
                                }
659
                        }
660
                }
661
        }
662

    
663
        private static String configureSkin(XMLEntity xml,String defaultSkin) {
664
                if (defaultSkin == null){
665
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
666
                                if (xml.getChild(i).contains("Skin-Selected")) {
667
                                        String className = xml.getChild(i).getStringProperty(
668
                                        "Skin-Selected");
669
                                        return className;
670
                                }
671
                        }
672
                }
673
//                return "com.iver.core.mdiManager.NewSkin";
674
                return  defaultSkin;
675
        }
676

    
677
        private static void fixSkin(SkinExtension skinExtension,PluginClassLoader pluginClassLoader) throws MDIManagerLoadException{
678
                // now insert the skin selected.
679
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
680
                // MDIManagerFactory.setSkinExtension(se,
681
                // ps.getClassLoader());
682

    
683
                Class skinClass;
684

    
685
                try {
686
                        skinClass = pluginClassLoader.loadClass(
687
                                        skinExtension.getClassName());
688

    
689
                        org.gvsig.andami.plugins.IExtension skinInstance = (org.gvsig.andami.plugins.IExtension) skinClass
690
                        .newInstance();
691
                        // classesExtensions.put(skinClass, skinInstance);
692
                        // jaume
693
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
694
                                        skinInstance, ExtensionDecorator.INACTIVE);
695
                        classesExtensions.put(skinClass, newExtensionDecorator);
696
                } catch (ClassNotFoundException e) {
697
                        logger
698
                        .error(
699
                                        Messages
700
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
701
                                        e);
702
                        throw new MDIManagerLoadException(e);
703
                } catch (InstantiationException e) {
704
                        logger
705
                        .error(
706
                                        Messages
707
                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
708
                                        e);
709
                        throw new MDIManagerLoadException(e);
710
                } catch (IllegalAccessException e) {
711
                        logger
712
                        .error(
713
                                        Messages
714
                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
715
                                        e);
716
                        throw new MDIManagerLoadException(e);
717
                }
718

    
719
        }
720
        /**
721
         * DOCUMENT ME!
722
         *
723
         * @throws MDIManagerLoadException
724
         */
725
        private static void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
726
                XMLEntity entity =null;
727
                try {
728
                        entity = persistenceFromXML();
729
                } catch (ConfigurationException e1) {
730
                        // TODO Auto-generated catch block
731
                        e1.printStackTrace();
732
                }
733
                Iterator i = pluginsConfig.keySet().iterator();
734

    
735
                SkinExtension skinExtension = null;
736
                PluginClassLoader pluginClassLoader = null;
737
                ArrayList skinExtensions = new ArrayList();
738
                while (i.hasNext()) {
739
                        String name = (String) i.next();
740
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
741
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
742

    
743
                        if (pc.getExtensions().getSkinExtension() != null) {
744
//                                if (MDIManagerFactory.getSkinExtension() != null) {
745
//                                        logger.warn(Messages.getString(
746
//                                                        "Launcher.Dos_skin_extension"));
747
//                                }
748

    
749
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
750
                                for (int numExten=0; numExten<se.length; numExten++) {
751
                                        skinExtensions.add(se[numExten]);
752
                                }
753
                                for (int j=0;j<se.length;j++){
754
                                        String configuredSkin = Launcher.configureSkin(entity,defaultSkin);
755
                                        if (configuredSkin!=null && configuredSkin.equals(se[j].getClassName())) {
756
                                                skinExtension = se[j];
757
                                                pluginClassLoader = ps.getClassLoader();
758
                                        }
759
                                }
760
                        }
761
                }
762

    
763
                if ((skinExtension != null) && (pluginClassLoader != null)) {
764
                        // configured skin was found
765
                        fixSkin(skinExtension, pluginClassLoader);
766
                } else {
767
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
768
                                // try first NewSkin (from CorePlugin)
769
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
770
                        }
771
                        else if (skinExtensions.size()>0){
772
                                // try to load the first skin found
773
                                SkinExtension se =  (SkinExtension)skinExtensions.get(0);
774
                                skinPlugin((String)se.getClassName());
775
                        }
776
                        else {
777
                                throw new MDIManagerLoadException("No Skin-Extension installed");
778
                        }
779
                }
780

    
781
        }
782

    
783
        private static void frameIcon(Theme theme) {
784
                Iterator i = pluginsConfig.keySet().iterator();
785

    
786
                while (i.hasNext()) {
787
                        String pName = (String) i.next();
788
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
789
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
790
                        if (pc.getIcon() != null) {
791
                                if (theme.getIcon() != null) {
792
                                        frame.setIconImage(theme.getIcon().getImage());
793
                                } else {
794

    
795
                                        ImageIcon icon = PluginServices.getIconTheme().get(pc.getIcon().getSrc());
796
                                        frame.setIconImage(icon.getImage());
797

    
798
                                }
799
                                if (theme.getName() != null) {
800
                                        frame.setTitlePrefix(theme.getName());
801
                                } else {
802
                                        frame.setTitlePrefix(pc.getIcon().getText());
803
                                }
804
                                if (theme.getBackgroundImage() != null) {
805

    
806
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
807
                                }
808
                        }
809
                }
810
        }
811

    
812
        private static void initializeExtensions() {
813
                
814
                libInitializers = new ArrayList<LibrariesInitializer>(pluginsOrdered
815
                                .size());
816
                
817
                Iterator i = pluginsOrdered.iterator();
818

    
819
                while (i.hasNext()) {
820
                        String pName = (String) i.next();
821
            logger.debug("Initializing extensions from " + pName);
822
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
823
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
824
                        
825
                        // Create the libraries initializer and 
826
                        // initialize the plugin libraries
827
                        LibrariesInitializer libsInitializer = new DefaultLibrariesInitializer(
828
                                        ps.getClassLoader());
829
                        libsInitializer.initialize();
830
                        libInitializers.add(libsInitializer);
831

    
832
                        Extension[] exts = pc.getExtensions().getExtension();
833

    
834
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
835

    
836
                        for (int j = 0; j < exts.length; j++) {
837
                                if (!exts[j].getActive()) {
838
                                        continue;
839
                                }
840

    
841
                                if (orderedExtensions.containsKey(exts[j])) {
842
                                        logger.warn(Messages.getString(
843
                                                        "Launcher.Two_extensions_with_the_same_priority") +
844
                                                exts[j].getClassName());
845
                                }
846

    
847
                                orderedExtensions.put(exts[j], null);
848
                        }
849
                        
850
                        Iterator e = orderedExtensions.keySet().iterator();
851

    
852
                        while (e.hasNext()) {
853
                                Extension extension = (Extension) e.next();
854
                                org.gvsig.andami.plugins.IExtension extensionInstance;
855

    
856
                                try {
857
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
858
                                        extensionInstance = (org.gvsig.andami.plugins.IExtension) extensionClass.newInstance();
859

    
860
                                        // CON DECORATOR
861
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
862
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
863
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
864
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
865
                                        // la extensi?n original que acabamos de crear
866
                                        // 0-> Inactivo, controla la extension
867
                                        // 1-> Siempre visible
868
                                        // 2-> Invisible
869
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
870
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
871
                                        logger.info("Initializing " + extension.getClassName()+"...");
872
                    // logger.debug("Initializing " + extension.getClassName());
873
                                        
874
                                        
875
                                        // AQUI
876
                                        
877
                    extensionInstance.initialize();
878
                    extensions.add(extensionInstance);
879
                    // logger.debug(extension.getClassName() + " initialized.");
880

    
881
                                } catch (InstantiationException e1) {
882
                                        logger.error(Messages.getString(
883
                                                        "Launcher.Error_instanciando_la_extension") +
884
                                                extension.getClassName(), e1);
885
                                } catch (IllegalAccessException e1) {
886
                                        logger.error(Messages.getString(
887
                                                        "Launcher.Error_instanciando_la_extension") +
888
                                                extension.getClassName(), e1);
889
                                } catch (ClassNotFoundException e1) {
890
                                        logger.error(Messages.getString(
891
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
892
                                                extension.getClassName(), e1);
893
                                } catch (NoClassDefFoundError e1) {
894
                                        logger.error(Messages.getString(
895
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
896
                                                extension.getClassName(), e1);
897
                                }
898
                        }
899
                }
900
        }
901

    
902
        private static void postInitializeExtensions() {
903
                // Post initialize all plugin libraries
904
                for (int i = 0; i < libInitializers.size(); i++) {
905
                        libInitializers.get(i).postInitialize();
906
                }
907
                // Remove them all, we don't need them anymore
908
                libInitializers.clear();
909
                libInitializers = null;
910
                
911
                for (int i=0;i<extensions.size();i++) {
912
                        org.gvsig.andami.plugins.IExtension extensionInstance=(org.gvsig.andami.plugins.IExtension)extensions.get(i);
913
                        extensionInstance.postInitialize();
914
                }
915
        }
916

    
917
        private static void installPluginsMenus() {
918
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
919

    
920
                Iterator i = pluginsConfig.keySet().iterator();
921

    
922
                while (i.hasNext()) {
923
                        String pName = (String) i.next();
924
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
925
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
926

    
927
                        Extension[] exts = pc.getExtensions().getExtension();
928

    
929
                        for (int j = 0; j < exts.length; j++) {
930
                                if (!exts[j].getActive()) {
931
                                        continue;
932
                                }
933

    
934
                                Menu[] menus = exts[j].getMenu();
935

    
936
                                for (int k = 0; k < menus.length; k++) {
937
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
938
                                                        exts[j], menus[k]);
939

    
940
                                        if (orderedMenus.containsKey(sm)) {
941
                                                logger.error(Messages.getString(
942
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
943
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
944
                                        }
945

    
946
                                        orderedMenus.put(sm, null);
947
                                }
948
                        }
949

    
950
                        // Se instalan las extensiones de MDI
951
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
952
                        for (int j = 0; j < skinExts.length; j++) {
953

    
954

    
955
                        if (skinExts[j] != null) {
956
                                Menu[] menu = skinExts[j].getMenu();
957

    
958
                                for (int k = 0; k < menu.length; k++) {
959
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
960
                                                        skinExts[j], menu[k]);
961

    
962
                                        if (orderedMenus.containsKey(sm)) {
963
                                                logger.error(Messages.getString(
964
                                                                "Launcher.Two_menus_with_the_same_position") +
965
                                                        skinExts[j].getClassName());
966
                                        }
967

    
968
                                        orderedMenus.put(sm, null);
969
                                }
970
                        }
971
                        }
972
                }
973

    
974
                //Se itera por los menus ordenados
975
                Iterator e = orderedMenus.keySet().iterator();
976

    
977
                // Se ordenan los menues
978
                while (e.hasNext()) {
979
                        try {
980
                                SortableMenu sm = (SortableMenu) e.next();
981

    
982
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
983
                        } catch (ClassNotFoundException ex) {
984
                                logger.error(Messages.getString(
985
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
986
                        }
987
                }
988
        }
989

    
990
        /**
991
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
992
         * The order in which they are shown is determined here.
993
         */
994
        private static void installPluginsControls() {
995
                Iterator i = pluginsConfig.keySet().iterator();
996

    
997
                HashMap extensionPluginServices = new HashMap();
998
                HashMap extensionPluginConfig = new HashMap();
999
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
1000

    
1001
                // First of all, sort the extensions.
1002
                // We need to iterate on the plugins, and iterate on each plugin's extensions
1003
                // (each plugin may contain one or more extensions)
1004
                while (i.hasNext()) { // iterate on the plugins
1005
                        String pName = (String) i.next();
1006
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1007
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1008

    
1009
                        Extension[] exts = pc.getExtensions().getExtension();
1010

    
1011
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
1012
                                if (exts[j].getActive()) {
1013
                                        if (orderedExtensions.containsKey(exts[j])) {
1014
                                                logger.error(Messages.getString(
1015
                                                "Launcher.Two_extensions_with_the_same_priority") +
1016
                                                exts[j].getClassName());
1017
                                        }
1018

    
1019
                                        orderedExtensions.put(exts[j], null);
1020
                                        extensionPluginServices.put(exts[j], ps);
1021
                                        extensionPluginConfig.put(exts[j], pc);
1022
                                }
1023
                        }
1024
                }
1025

    
1026
                TreeMap orderedTools = new TreeMap(new ToolComparator());
1027
                Iterator e = orderedExtensions.keySet().iterator();
1028

    
1029
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
1030
                // and load the  combo-scales and combo-buttons for the status bar
1031
                while (e.hasNext()) {
1032
                        Extension ext = (Extension) e.next();
1033

    
1034
                        ToolBar[] toolbars = ext.getToolBar();
1035

    
1036
                        // get tools from toolbars
1037
                        for (int k = 0; k < toolbars.length; k++) {
1038
                                ActionTool[] tools = toolbars[k].getActionTool();
1039

    
1040
                                for (int t = 0; t < tools.length; t++) {
1041
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1042
                                                        toolbars[k], tools[t]);
1043
                                        orderedTools.put(sm, null);
1044
                                }
1045

    
1046
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
1047

    
1048
                                for (int t = 0; t < sTools.length; t++) {
1049
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1050
                                                        toolbars[k], sTools[t]);
1051
                                        orderedTools.put(sm, null);
1052
                                }
1053
                        }
1054

    
1055
                        // get controls for statusBar
1056
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
1057
                        PluginClassLoader loader = ps.getClassLoader();
1058

    
1059
                        //ArrayList componentList = new ArrayList();
1060
                        ComboScale[] comboScaleArray = ext.getComboScale();
1061
                        for (int k=0; k < comboScaleArray.length; k++) {
1062
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1063
                                String label = comboScaleArray[k].getLabel();
1064
                                if (label!=null)
1065
                                        combo.setLabel(label);
1066
                                String name = comboScaleArray[k].getName();
1067
                                if (name!=null)
1068
                                        combo.setName(name);
1069
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
1070
                                long[] elements = new long[elementsString.length];
1071
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
1072
                                        try {
1073
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
1074
                                        }
1075
                                        catch (NumberFormatException nfex1) {
1076
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
1077
                                                elements[currentElem] = 0;
1078
                                        }
1079
                                }
1080
                                combo.setItems(elements);
1081
                                try {
1082
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
1083
                                        combo.setScale(value);
1084
                                }
1085
                                catch (NumberFormatException nfex2) {
1086
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
1087
                                }
1088
                                try {
1089
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
1090
                                } catch (ClassNotFoundException e1) {
1091
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1092
                                }
1093
                        }
1094

    
1095
                        ComboButton[] comboButtonArray = ext.getComboButton();
1096
                        for (int k=0; k < comboButtonArray.length; k++) {
1097
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
1098
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1099
                                String name = comboButtonArray[k].getName();
1100
                                if (name!=null)
1101
                                        combo.setName(name);
1102
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
1103
                                        ComboButtonElement element = elementList[currentElement];
1104
                                        ImageIcon icon;
1105
                                        URL iconLocation = loader.getResource(element.getIcon());
1106
                                        if (iconLocation==null)
1107
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
1108
                                        else {
1109
                                                icon = new ImageIcon(iconLocation);
1110
                                                JButton button = new JButton(icon);
1111
                                                combo.addButton(button);
1112
                                                button.setActionCommand(element.getActionCommand());
1113
                                        }
1114
                                }
1115
                                try {
1116
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
1117
                                } catch (ClassNotFoundException e1) {
1118
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1119
                                }
1120
                        }
1121
                }
1122

    
1123
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
1124
                i = pluginsConfig.keySet().iterator();
1125
                while (i.hasNext()) {
1126
                        String pName = (String) i.next();
1127
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1128
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1129

    
1130
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
1131
                        for (int j = 0; j < skinExts.length; j++) {
1132

    
1133

    
1134
                        if (skinExts[j] != null) {
1135
                                ToolBar[] toolbars = skinExts[j].getToolBar();
1136

    
1137
                                for (int k = 0; k < toolbars.length; k++) {
1138
                                        ActionTool[] tools = toolbars[k].getActionTool();
1139

    
1140
                                        for (int t = 0; t < tools.length; t++) {
1141
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1142
                                                                toolbars[k], tools[t]);
1143
                                                orderedTools.put(stb,null);
1144
                                        }
1145

    
1146
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1147

    
1148
                                        for (int t = 0; t < sTools.length; t++) {
1149
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1150
                                                                toolbars[k], sTools[t]);
1151
                                                orderedTools.put(stb,null);
1152
                                        }
1153
                                }
1154
                        }
1155
                        }
1156
                        // Install popup menus
1157
                        PopupMenus pus = pc.getPopupMenus();
1158

    
1159
                        if (pus != null) {
1160
                                PopupMenu[] menus = pus.getPopupMenu();
1161

    
1162
                                for (int j = 0; j < menus.length; j++) {
1163
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1164
                                }
1165
                        }
1166
                }
1167

    
1168
                // loop on the ordered extension list, to add them to the interface in an ordered way
1169
                Iterator t = orderedTools.keySet().iterator();
1170
                while (t.hasNext()) {
1171
                        try {
1172
                                SortableTool stb = (SortableTool) t.next();
1173
                                if (stb.actiontool!=null)
1174
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
1175
                                else
1176
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
1177
                        } catch (ClassNotFoundException ex) {
1178
                                logger.error(Messages.getString(
1179
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
1180
                        }
1181
                }
1182
        }
1183

    
1184
        /**
1185
         * Adds new plugins to the the andami-config file.
1186
         */
1187
        private static void updateAndamiConfig() {
1188
                HashSet olds = new HashSet();
1189

    
1190
                Plugin[] plugins = andamiConfig.getPlugin();
1191

    
1192
                for (int i = 0; i < plugins.length; i++) {
1193
                        olds.add(plugins[i].getName());
1194
                }
1195

    
1196
                Iterator i = pluginsServices.values().iterator();
1197

    
1198
                while (i.hasNext()) {
1199
                        PluginServices ps = (PluginServices) i.next();
1200

    
1201
                        if (!olds.contains(ps.getPluginName())) {
1202
                                Plugin p = new Plugin();
1203
                                p.setName(ps.getPluginName());
1204
                                p.setUpdate(false);
1205

    
1206
                                andamiConfig.addPlugin(p);
1207
                        }
1208
                }
1209
        }
1210

    
1211
        private static void pluginsClassLoaders() {
1212
                HashSet instalados = new HashSet();
1213

    
1214
                // Se itera hasta que est?n todos instalados
1215
                while (instalados.size() != pluginsConfig.size()) {
1216
                        boolean circle = true;
1217

    
1218
                        //Hacemos una pasada por todos los plugins
1219
                        Iterator i = pluginsConfig.keySet().iterator();
1220

    
1221
                        while (i.hasNext()) {
1222
                                String pluginName = (String) i.next();
1223
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1224

    
1225
                                if (instalados.contains(pluginName)) {
1226
                                        continue;
1227
                                }
1228

    
1229
                                //Se obtienen las dependencias y sus class loaders
1230
                                boolean ready = true;
1231
                                Depends[] dependencies = config.getDepends();
1232
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1233

    
1234
                                for (int j = 0; j < dependencies.length; j++) {
1235
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1236
                                                logger.error(Messages.getString(
1237
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1238
                                                        pluginName + ": " +
1239
                                                        dependencies[j].getPluginName());
1240

    
1241
                                                continue;
1242
                                        }
1243

    
1244
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1245
                                                ready = false;
1246
                                        } else {
1247
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1248
                                        }
1249
                                }
1250

    
1251
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1252
                                if (!ready) {
1253
                                        continue;
1254
                                }
1255

    
1256
                                //Se genera el class loader
1257
                                String jardir = config.getLibraries().getLibraryDir();
1258
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1259
                                                File.separator + pluginName + File.separator + jardir);
1260
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1261
                                                        public boolean accept(File pathname) {
1262
                                                                return (pathname.getName().toUpperCase()
1263
                                                                                                .endsWith(".JAR")) ||
1264
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1265
                                                        }
1266
                                                });
1267

    
1268
                                URL[] urls = new URL[jarFiles.length];
1269

    
1270
                                for (int j = 0; j < jarFiles.length; j++) {
1271
                                        try {
1272
                                                urls[j] = new URL("file:" + jarFiles[j]);
1273
                                        } catch (MalformedURLException e) {
1274
                                                logger.error(Messages.getString(
1275
                                                                "Launcher.No_se_puede_acceder_a") +
1276
                                                        jarFiles[j]);
1277
                                        }
1278
                                }
1279

    
1280
                                PluginClassLoader loader;
1281

    
1282
                                try {
1283
                                        loader = new PluginClassLoader(urls,
1284
                                                        andamiConfig.getPluginsDirectory() +
1285
                                                        File.separator + pluginName,
1286
                                                        Launcher.class.getClassLoader(), loaders);
1287

    
1288
                                        PluginServices ps = new PluginServices(loader);
1289

    
1290
                                        pluginsServices.put(ps.getPluginName(), ps);
1291

    
1292
                                        instalados.add(pluginName);
1293
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1294
                    // inicializar los plugins
1295
                    pluginsOrdered.add(pluginName);
1296

    
1297
                                        circle = false;
1298
                                } catch (IOException e) {
1299
                                        logger.error(Messages.getString(
1300
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1301
                                        pluginsConfig.remove(pluginName);
1302
                                        i = pluginsConfig.keySet().iterator();
1303
                                }
1304
                        }
1305

    
1306
                        if (circle) {
1307
                                logger.error(Messages.getString(
1308
                                                "Launcher.Hay_dependencias_circulares"));
1309

    
1310
                                break;
1311
                        }
1312
                }
1313

    
1314
                //Se eliminan los plugins que no fueron instalados
1315
                Iterator i = pluginsConfig.keySet().iterator();
1316

    
1317
                while (i.hasNext()) {
1318
                        String pluginName = (String) i.next();
1319
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1320
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1321

    
1322
                        if (ps == null) {
1323
                                pluginsConfig.remove(pluginName);
1324
                                i = pluginsConfig.keySet().iterator();
1325
                        }
1326
                }
1327
        }
1328

    
1329
        private static void pluginsMessages() {
1330
                Iterator iterator = pluginsOrdered.iterator();
1331
                PluginConfig config;
1332
                PluginServices ps;
1333

    
1334
                while (iterator.hasNext()) {
1335
                        String pluginName = (String) iterator.next();
1336
                        config = (PluginConfig) pluginsConfig.get(pluginName);
1337
                        ps = (PluginServices) pluginsServices.get(pluginName);
1338

    
1339
                        if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1340
                                // add the locale files associated with the plugin
1341
                                org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1342
                        }
1343
                }
1344
        }
1345

    
1346
        static PluginServices getPluginServices(String name) {
1347
                return (PluginServices) pluginsServices.get(name);
1348
        }
1349

    
1350
        static String getPluginsDir() {
1351
                return andamiConfig.getPluginsDirectory();
1352
        }
1353

    
1354
        static void setPluginsDir(String s) {
1355
                andamiConfig.setPluginsDirectory(s);
1356
        }
1357

    
1358
        static MDIFrame getMDIFrame() {
1359
                return frame;
1360
        }
1361

    
1362
        private static void loadPlugins(String pluginsDirectory) {
1363
                File pDir = new File(pluginsDirectory);
1364

    
1365
                if (!pDir.exists()) {
1366
                        logger.error("\n\tPlugins directory not found: "+pDir.getAbsolutePath()+"\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1367
                        System.exit(-1);
1368
                        return;
1369
                }
1370

    
1371
                File[] pluginDirs = pDir.listFiles();
1372
                if (pluginDirs.length==0) {
1373
                        logger.error("\n\tPlugins directory is empty: "+pDir.getAbsolutePath()+"Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1374
                        System.exit(-1);
1375
                        return;
1376
                }
1377

    
1378
                for (int i = 0; i < pluginDirs.length; i++) {
1379
                        if (pluginDirs[i].isDirectory()) {
1380
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1381
                                                File.separator + "config.xml");
1382

    
1383
                                try {
1384
                                        FileInputStream is = new FileInputStream(configXml);
1385
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
1386
                                        if (xml==null) {
1387
                                                // the encoding was not correctly detected, use system default
1388
                                                xml = new FileReader(configXml);
1389
                                        }
1390
                                        else {
1391
                                                // use a buffered reader to improve performance
1392
                                                xml = new BufferedReader(xml);
1393
                                        }
1394
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1395
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1396
                                } catch (FileNotFoundException e) {
1397
                                        logger.info(Messages.getString(
1398
                                                        "Launcher.Ignorando_el_directorio") +
1399
                                                pluginDirs[i].getAbsolutePath() +
1400
                                                Messages.getString("Launcher.config_no_encontrado"));
1401
                                } catch (MarshalException e) {
1402
                                        logger.info(Messages.getString(
1403
                                                        "Launcher.Ignorando_el_directorio") +
1404
                                                pluginDirs[i].getAbsolutePath() +
1405
                                                Messages.getString("Launcher.config_mal_formado"), e);
1406
                                } catch (ValidationException e) {
1407
                                        logger.info(Messages.getString(
1408
                                                        "Launcher.Ignorando_el_directorio") +
1409
                                                pluginDirs[i].getAbsolutePath() +
1410
                                                Messages.getString("Launcher.config_mal_formado"), e);
1411
                                }
1412
                        }
1413
                }
1414

    
1415
                if (pluginsConfig.size()==0) {
1416
                        logger.error("\n\tNo valid plugin was found. The plugins directory currently is: "+pDir.getAbsolutePath()+"\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1417
                        System.exit(-1);
1418
                        return;
1419
                }
1420
        }
1421

    
1422
        private static Locale getLocale(String language, String country,
1423
                String variant) {
1424
                if (variant != null) {
1425
                        return new Locale(language, country, variant);
1426
                } else if (country != null) {
1427
                        return new Locale(language, country);
1428
                } else if (language != null) {
1429
                        return new Locale(language);
1430
                } else {
1431
                        return new Locale("es");
1432
                }
1433
        }
1434

    
1435
        private static void andamiConfigToXML(String file)
1436
                throws IOException, MarshalException, ValidationException {
1437
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1438
                File tmpFile = new File(file+"-"+DateTime.getCurrentDate().getTime());
1439
                File xml = new File(file);
1440
                File parent = xml.getParentFile();
1441
                parent.mkdirs();
1442

    
1443
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile));
1444
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
1445
                andamiConfig.marshal(writer);
1446
                writer.close();
1447

    
1448
                // if marshaling process finished correctly, move the file to the correct one
1449
                xml.delete();
1450
                if (!tmpFile.renameTo(xml)) {
1451
                        // if rename was not succesful, try copying it
1452
                        FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1453
                        FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1454
                        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1455
                        sourceChannel.close();
1456
                        destinationChannel.close();
1457
                }
1458
        }
1459

    
1460
        private static void andamiConfigFromXML(String file)
1461
                throws ConfigurationException {
1462
                File xml = new File(file);
1463

    
1464
                InputStreamReader reader = null;
1465
                try {
1466
                        //Se lee la configuraci?n
1467
                        reader = XMLEncodingUtils.getReader(xml);
1468
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1469
                } catch (FileNotFoundException e) {
1470
                        //Si no existe se ponen los valores por defecto
1471
                        andamiConfig = getDefaultAndamiConfig();
1472
                } catch (MarshalException e) {
1473
                        // try to close the stream, maybe it remains open
1474
                        if (reader!=null) {
1475
                                try { reader.close(); } catch (IOException e1) {}
1476
                        }
1477
                        // if there was a problem reading the file, backup it and create a new one with default values
1478
                        String backupFile = file+"-"+DateTime.getCurrentDate().getTime();
1479
                        NotificationManager.addError(Messages.getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1480
                        xml.renameTo(new File(backupFile));
1481
                        andamiConfig = getDefaultAndamiConfig();
1482
                } catch (ValidationException e) {
1483
                        throw new ConfigurationException(e);
1484
                }
1485
        }
1486

    
1487
        private static AndamiConfig getDefaultAndamiConfig() {
1488
                AndamiConfig andamiConfig = new AndamiConfig();
1489

    
1490
                Andami andami = new Andami();
1491
                andami.setUpdate(true);
1492
                andamiConfig.setAndami(andami);
1493
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1494
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1495
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1496

    
1497
                if (System.getProperty("javawebstart.version") != null) // Es java web start)
1498
                 {
1499
                        andamiConfig.setPluginsDirectory(new File(appHomeDir
1500
                                        + "extensiones").getAbsolutePath());
1501
                } else {
1502
                        andamiConfig.setPluginsDirectory(new File(appName +
1503
                                        File.separator + "extensiones").getAbsolutePath());
1504
                }
1505

    
1506
                andamiConfig.setPlugin(new Plugin[0]);
1507
                return andamiConfig;
1508
        }
1509

    
1510
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1511
                File xml = new File(pluginsPersistencePath);
1512

    
1513
                if (xml.exists()) {
1514
                        InputStreamReader reader = null;
1515

    
1516
                        try {
1517
                                reader = XMLEncodingUtils.getReader(xml);
1518
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1519
                                return new XMLEntity(tag);
1520
                        } catch (FileNotFoundException e) {
1521
                                throw new ConfigurationException(e);
1522
                        } catch (MarshalException e) {
1523

    
1524
                                // try to reopen with default encoding (for backward compatibility)
1525
                                try {
1526
                                        reader = new FileReader(xml);
1527
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1528
                                        return new XMLEntity(tag);
1529

    
1530
                                } catch (MarshalException ex) {
1531
                                        // try to close the stream, maybe it remains open
1532
                                        if (reader!=null) {
1533
                                                try { reader.close(); } catch (IOException e1) {}
1534
                                        }
1535
                                        // backup the old file
1536
                                        String backupFile = pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime();
1537
                                        NotificationManager.addError(Messages.getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1538
                                        xml.renameTo(new File(backupFile));
1539
                                        // create a new, empty configuration
1540
                                        return new XMLEntity();
1541
                                }
1542
                                catch (FileNotFoundException ex) {
1543
                                        return new XMLEntity();
1544
                                } catch (ValidationException ex) {
1545
                                        throw new ConfigurationException(e);
1546
                                }
1547
                        } catch (ValidationException e) {
1548
                                throw new ConfigurationException(e);
1549
                        }
1550
                } else {
1551
                        return new XMLEntity();
1552
                }
1553
        }
1554

    
1555
        private static void persistenceToXML(XMLEntity entity)
1556
                throws ConfigurationException {
1557
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1558
                File tmpFile = new File(pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime());
1559

    
1560
                File xml = new File(pluginsPersistencePath);
1561
                OutputStreamWriter writer = null;
1562

    
1563
                try {
1564
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile), CASTORENCODING);
1565
                        entity.getXmlTag().marshal(writer);
1566
                        writer.close();
1567

    
1568
                        // if marshaling process finished correctly, move the file to the correct one
1569
                        xml.delete();
1570
                        if (!tmpFile.renameTo(xml)) {
1571
                                // if rename was not succesful, try copying it
1572
                                FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1573
                                FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1574
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1575
                                sourceChannel.close();
1576
                                destinationChannel.close();
1577

    
1578
                        }
1579
                } catch (FileNotFoundException e) {
1580
                        throw new ConfigurationException(e);
1581
                } catch (MarshalException e) {
1582
                        // try to close the stream, maybe it remains open
1583
                        if (writer!=null) {
1584
                                try { writer.close(); } catch (IOException e1) {}
1585
                        }
1586
                } catch (ValidationException e) {
1587
                        throw new ConfigurationException(e);
1588
                } catch (IOException e) {
1589
                        throw new ConfigurationException(e);
1590
                }
1591
        }
1592

    
1593
        static MDIFrame getFrame() {
1594
                return frame;
1595
        }
1596

    
1597
        /**
1598
         * Gracefully closes the application. It shows dialogs to save data,
1599
         * finish processes, etc, then it terminates the extensions, removes
1600
         * temporal files and finally exits.
1601
         */
1602
        public synchronized static void closeApplication() {
1603
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
1604
                terminationProcess.run();
1605
        }
1606

    
1607
        static HashMap getClassesExtensions() {
1608
                return classesExtensions;
1609
        }
1610

    
1611
        private static void downloadExtensions(String extDir) {
1612
                java.util.Date fechaActual = null;
1613

    
1614
                try {
1615
                        if (System.getProperty("javawebstart.version") != null) {
1616
                                //Obtenemos la URL del servidor
1617
                                BasicService bs = (BasicService) ServiceManager.lookup(
1618
                                                "javax.jnlp.BasicService");
1619
                                URL baseURL = bs.getCodeBase();
1620

    
1621
                                //Se descargan las extensiones
1622
                                splashWindow.process(5,
1623
                                        "Descargando las extensiones desde " + baseURL + " a " +
1624
                                        extDir);
1625

    
1626
                                URL url = new URL(baseURL + "extensiones.zip");
1627
                                URLConnection connection = url.openConnection();
1628

    
1629
                                System.out.println(url.toExternalForm() + ":");
1630
                                System.out.println("  Content Type: " +
1631
                                        connection.getContentType());
1632
                                System.out.println("  Content Length: " +
1633
                                        connection.getContentLength());
1634
                                System.out.println("  Last Modified: " +
1635
                                        new Date(connection.getLastModified()));
1636
                                System.out.println("  Expiration: " +
1637
                                        connection.getExpiration());
1638
                                System.out.println("  Content Encoding: " +
1639
                                        connection.getContentEncoding());
1640

    
1641
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1642
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1643
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1644
                                // nos bajamos nada.
1645
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1646

    
1647
                                File destDir = new File(extDir);
1648

    
1649
                                if (!destDir.exists()) {
1650
                                        // Creamos gvSIG
1651
                                        destDir.getParentFile().mkdir();
1652

    
1653
                                        if (!destDir.mkdir()) {
1654
                                                System.err.println("Imposible crear el directorio " +
1655
                                                        destDir.getAbsolutePath());
1656
                                        }
1657
                                }
1658

    
1659
                                File timeFile = new File(destDir.getParent() + File.separator +
1660
                                                "timeStamp.properties");
1661

    
1662
                                if (!timeFile.exists()) {
1663
                                        timeFile.createNewFile();
1664
                                }
1665

    
1666
                                FileInputStream inAux = new FileInputStream(timeFile);
1667
                                Properties prop = new Properties();
1668
                                prop.load(inAux);
1669
                                inAux.close();
1670

    
1671
                                if (prop.getProperty("timestamp") != null) {
1672
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1673
                                                                "timestamp"));
1674

    
1675
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1676
                                                System.out.println("No hay nueva actualizaci?n");
1677
                        logger.debug("No hay nueva actualizaci?n -> Return");
1678
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1679
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1680

    
1681
                                                return;
1682
                                        }
1683

    
1684
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1685
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1686
                                } else {
1687
                                        System.out.println("El timeStamp no est? escrito en " +
1688
                                                timeFile.getAbsolutePath());
1689
                                }
1690

    
1691
                                InputStream stream = url.openStream();
1692
                File temp = File.createTempFile("gvsig", ".zip");
1693

    
1694
                logger.debug(temp.getAbsolutePath());
1695

    
1696
                temp.deleteOnExit();
1697
                FileOutputStream file = new FileOutputStream(temp);
1698

    
1699
                byte[] lt_read = new byte[1];
1700

    
1701
                while (stream.read(lt_read) > 0)
1702
                  file.write(lt_read);
1703

    
1704
                                stream.close();
1705
                stream = null;
1706
                file.close();
1707
                file = null;
1708

    
1709
                System.gc();
1710

    
1711
                logger.debug("Ha creado el fichero ZIP");
1712
                                //Se extrae el zip
1713
                splashWindow.process(5, "Extensiones descargadas.");
1714

    
1715
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1716

    
1717
                                Date fechaDir = new Date(destDir.lastModified());
1718
                                System.out.println("Fecha del directorio " + extDir + " = " +
1719
                                        fechaDir.toString());
1720
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1721

    
1722
                                // Si todo ha ido bien, guardamos el timestamp.
1723
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1724
                                // XMLEntity xml=ps.getPersistentXML();
1725
                                fechaActual = new java.util.Date();
1726

    
1727
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1728
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1729
                                prop.store(outAux, "last download");
1730
                                outAux.close();
1731
                                System.out.println("Fecha actual guardada: " +
1732
                                        fechaActual.toGMTString());
1733

    
1734
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1735
                                   ps.setPresistentXML(xml); */
1736
                        }
1737
                } catch (IOException e) {
1738
                        NotificationManager.addError("", e);
1739
                } catch (UnavailableServiceException e) {
1740
                        NotificationManager.addError("", e);
1741
                } catch (SecurityException e) {
1742
                        System.err.println("No se puede escribir el timeStamp " +
1743
                                fechaActual.toGMTString());
1744
                        NotificationManager.addError("", e);
1745
                }
1746
        }
1747

    
1748
        private static Extensions[] getExtensions() {
1749
                ArrayList array = new ArrayList();
1750
                Iterator iter = pluginsConfig.values().iterator();
1751

    
1752
                while (iter.hasNext()) {
1753
                        array.add(((PluginConfig) iter.next()).getExtensions());
1754
                }
1755

    
1756
                return (Extensions[]) array.toArray(new Extensions[0]);
1757
        }
1758

    
1759
        public static Iterator getExtensionIterator() {
1760
                return extensions.iterator();
1761
        }
1762

    
1763
        public static HashMap getPluginConfig() {
1764
                return pluginsConfig;
1765
        }
1766

    
1767
        public static Extension getExtension(String s) {
1768
                Extensions[] exts = getExtensions();
1769

    
1770
                for (int i = 0; i < exts.length; i++) {
1771
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1772
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1773
                                        return exts[i].getExtension(j);
1774
                                }
1775
                        }
1776
                }
1777

    
1778
                return null;
1779
        }
1780

    
1781
        public static AndamiConfig getAndamiConfig() {
1782
                return andamiConfig;
1783
        }
1784

    
1785
        private static class ExtensionComparator implements Comparator {
1786
                public int compare(Object o1, Object o2) {
1787
                        Extension e1 = (Extension) o1;
1788
                        Extension e2 = (Extension) o2;
1789

    
1790
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1791
                                return -1;
1792
                        }
1793

    
1794
                        if (e1.hasPriority() && !e2.hasPriority()) {
1795
                                return Integer.MIN_VALUE;
1796
                        }
1797

    
1798
                        if (e2.hasPriority() && !e1.hasPriority()) {
1799
                                return Integer.MAX_VALUE;
1800
                        }
1801

    
1802
                        if (e1.getPriority() != e2.getPriority()){
1803
                                return e2.getPriority() - e1.getPriority();
1804
                        }else{
1805
                                return (e2.toString().compareTo(e1.toString()));
1806
                        }
1807
                }
1808
        }
1809

    
1810
        private static class MenuComparator implements Comparator {
1811
                private static ExtensionComparator extComp = new ExtensionComparator();
1812

    
1813
                public int compare(Object o1, Object o2) {
1814
                        SortableMenu e1 = (SortableMenu) o1;
1815
                        SortableMenu e2 = (SortableMenu) o2;
1816

    
1817
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1818
                                if (e1.extension instanceof SkinExtensionType) {
1819
                                        return 1;
1820
                                } else if (e2.extension instanceof SkinExtensionType) {
1821
                                        return -1;
1822
                                } else {
1823
                                        return extComp.compare(e1.extension, e2.extension);
1824
                                }
1825
                        }
1826

    
1827
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1828
                                return Integer.MIN_VALUE;
1829
                        }
1830

    
1831
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1832
                                return Integer.MAX_VALUE;
1833
                        }
1834
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1835
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1836
                                return e1.menu.getPosition() - e2.menu.getPosition();
1837
                        }else{
1838
                                return (e1.toString().compareTo(e2.toString()));
1839
                        }
1840
                }
1841
        }
1842

    
1843
        private static class SortableMenu {
1844
                public PluginClassLoader loader;
1845
                public Menu menu;
1846
                public SkinExtensionType extension;
1847

    
1848
                public SortableMenu(PluginClassLoader loader,
1849
                        SkinExtensionType skinExt, Menu menu2) {
1850
                        extension = skinExt;
1851
                        menu = menu2;
1852
                        this.loader = loader;
1853
                }
1854
        }
1855

    
1856
        private static class SortableTool {
1857
                public PluginClassLoader loader;
1858
                public ToolBar toolbar;
1859
                public ActionTool actiontool;
1860
                public SelectableTool selectabletool;
1861
                public SkinExtensionType extension;
1862

    
1863
                public SortableTool(PluginClassLoader loader,
1864
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1865
                        extension = skinExt;
1866
                        toolbar = toolbar2;
1867
                        actiontool=actiontool2;
1868
                        this.loader = loader;
1869
                }
1870
                public SortableTool(PluginClassLoader loader,
1871
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1872
                        extension = skinExt;
1873
                        toolbar = toolbar2;
1874
                        selectabletool=selectabletool2;
1875
                        this.loader = loader;
1876
                }
1877
        }
1878

    
1879
        private static class ToolBarComparator implements Comparator {
1880
                private static ExtensionComparator extComp = new ExtensionComparator();
1881

    
1882
                public int compare(Object o1, Object o2) {
1883
                        SortableTool e1 = (SortableTool) o1;
1884
                        SortableTool e2 = (SortableTool) o2;
1885

    
1886
                        // if the toolbars have the same name, they are considered to be
1887
                        // the same toolbar, so we don't need to do further comparing
1888
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1889
                                return 0;
1890

    
1891
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1892
                                if (e1.extension instanceof SkinExtensionType) {
1893
                                        return 1;
1894
                                } else if (e2.extension instanceof SkinExtensionType) {
1895
                                        return -1;
1896
                                } else {
1897
                                        return extComp.compare(e1.extension, e2.extension);
1898
                                }
1899
                        }
1900

    
1901
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1902
                                return Integer.MIN_VALUE;
1903
                        }
1904

    
1905
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1906
                                return Integer.MAX_VALUE;
1907
                        }
1908
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1909
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1910

    
1911
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1912
                                return 0;
1913
                        }
1914
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1915
                }
1916
        }
1917

    
1918
        /**
1919
         * <p>This class is used to compare tools (selectabletool and actiontool),
1920
         * using the "position"
1921
         * attribute.</p>
1922
         * <p>The ordering criteria are:</p>
1923
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1924
         * order.
1925
         * (using the ToolBarComparator).</li>
1926
         * <li></li>
1927
         * <li>If any of the tools has not 'position' attribute, the tool which
1928
         * <strong>has</strong> the attribute will be placed first.</li>
1929
         * <li>If both tools have the same position (or they don't have a
1930
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1931
         *
1932
         * @author cesar
1933
         * @version $Revision: 30580 $
1934
         */
1935
        private static class ToolComparator implements Comparator {
1936
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1937

    
1938
                public int compare(Object o1, Object o2) {
1939
                        // compare the toolbars which contain the tools
1940
                        int result = toolBarComp.compare(o1, o2);
1941
                        if (result != 0) { // if the toolbars are different, use their order
1942
                                return result;
1943
                        }
1944
                        // otherwise, compare the tools
1945
                        SortableTool e1 = (SortableTool) o1;
1946
                        SortableTool e2 = (SortableTool) o2;
1947
                        int e1Position=-1, e2Position=-1;
1948

    
1949
                        if (e1.actiontool!=null) {
1950
                                if (e1.actiontool.hasPosition())
1951
                                        e1Position = e1.actiontool.getPosition();
1952
                        }
1953
                        else if (e1.selectabletool!=null) {
1954
                                if (e1.selectabletool.hasPosition())
1955
                                        e1Position = e1.selectabletool.getPosition();
1956
                        }
1957

    
1958
                        if (e2.actiontool!=null) {
1959
                                if (e2.actiontool.hasPosition())
1960
                                        e2Position = e2.actiontool.getPosition();
1961
                        }
1962
                        else if (e2.selectabletool!=null){
1963
                                if (e2.selectabletool.hasPosition())
1964
                                        e2Position = e2.selectabletool.getPosition();
1965
                        }
1966

    
1967
                        if (e1Position==-1 && e2Position!=-1) {
1968
                                return 1;
1969
                        }
1970
                        if (e1Position!=-1 && e2Position==-1) {
1971
                                return -1;
1972
                        }
1973
                        if (e1Position!=-1 && e2Position!=-1) {
1974
                                result = e1Position - e2Position;
1975
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1976
                                if (result!=0) return result;
1977
                        }
1978
                        return e1.toString().compareTo(e2.toString());
1979
                }
1980
        }
1981

    
1982

    
1983
        /**
1984
         * validates the user before starting gvsig
1985
         *
1986
         */
1987
        private static void validate(){
1988

    
1989
                IAuthentication session =  null;
1990
                try {
1991
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1992

    
1993
                } catch (ClassNotFoundException e) {
1994
                        return;
1995
                } catch (InstantiationException e) {
1996
                        return;
1997
                } catch (IllegalAccessException e) {
1998
                        return;
1999
                }
2000

    
2001
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
2002
                if (session.validationRequired()){
2003
                        if(session.Login()){
2004
                                System.out.println("You are logged in");
2005
                        }
2006
                        else{
2007
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
2008
                                                 "You are not logged in");
2009
                                //System.exit(0);
2010
                        }
2011
                        PluginServices.setAuthentication(session);
2012
                }
2013
        }
2014

    
2015
        public static String getDefaultLookAndFeel() {
2016
                String osName = (String) System.getProperty("os.name");
2017

    
2018
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2019
                        return nonWinDefaultLookAndFeel;
2020
                if (osName.toLowerCase().startsWith("mac os x"))
2021
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2022

    
2023

    
2024
                return UIManager.getSystemLookAndFeelClassName();
2025
        }
2026

    
2027
        /**
2028
         * Gets the ISO 839 two-characters-long language code matching the
2029
         * provided language code (which may be an ISO 839-2/T
2030
         * three-characters-long code or an ISO 839-1 two-characters-long
2031
         * code).
2032
         *
2033
         * If the provided parameter is already two characters long, it
2034
         * returns the parameter without any modification.
2035
         *
2036
         * @param langCode A language code representing either
2037
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2038
         * @return A two-characters-long code specifying
2039
         *  an ISO 839 language code.
2040
         */
2041
        private static String normalizeLanguageCode(String langCode) {
2042
                final String fileName = "iso_639.tab";
2043
                if (langCode.length()==2)
2044
                        return langCode;
2045
                else if (langCode.length()==3) {
2046
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2047
                                return "ca";
2048
                        }
2049
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2050
                        if (isoCodes!=null) {
2051
                                try {
2052
                                        BufferedReader reader =
2053
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2054
                                                String line;
2055

    
2056
                                                while ((line = reader.readLine()) != null) {
2057
                                                        String[] language = line.split("\t");
2058
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2059
                                                                return language[2]; // third column i the two characters code
2060
                                                }
2061
                                }
2062
                                catch (IOException ex) {
2063
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2064
                                        return "es";
2065
                                }
2066
                        }
2067
                        else {
2068
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2069
                                return "es";
2070
                        }
2071
                }
2072
                return "es";
2073
        }
2074

    
2075
        /**
2076
         * Configures the locales (languages and local resources) to be used
2077
         * by the application.
2078
         *
2079
         * First it tries to get the locale from the command line parameters,
2080
         * then the andami-config file is checked.
2081
         *
2082
         * The locale name is normalized to get a two characters language code
2083
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2084
         * are also accepted from the command line or the configuration file).
2085
         *
2086
         * Finally, the gvsig-i18n library and the default locales for Java and
2087
         * Swing are configured.
2088
         *
2089
         */
2090
        private static void configureLocales(String[] args) {
2091
                //                 Configurar el locale
2092
        String localeStr = null;
2093
        /*
2094
        for (int i=2; i < args.length; i++)
2095
        {
2096
                int index = args[i].indexOf("language=");
2097
                if (index != -1)
2098
                        localeStr = args[i].substring(index+9);
2099
        }
2100
         */
2101
        localeStr = PluginServices.getArgumentByName("language");
2102
                if (localeStr == null)
2103
                {
2104
            localeStr = andamiConfig.getLocaleLanguage();
2105
                }
2106
                localeStr = normalizeLanguageCode(localeStr);
2107
                locale = getLocale(localeStr,
2108
                andamiConfig.getLocaleCountry(),
2109
                andamiConfig.getLocaleVariant());
2110
                Locale.setDefault(locale);
2111
                JComponent.setDefaultLocale(locale);
2112
        org.gvsig.i18n.Messages.addLocale(locale);
2113
                // add english and spanish as fallback languages
2114
        if (localeStr.equals("es")||localeStr.equals("ca")||localeStr.equals("gl")||localeStr.equals("eu")||localeStr.equals("va")) {
2115
                // prefer Spanish for languages spoken in Spain
2116
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2117
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2118
        }
2119
        else {
2120
                // prefer English for the rest
2121
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2122
                    org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2123
        }
2124
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2125

    
2126
        }
2127

    
2128
        /**
2129
         * Gets Home Directory location of the application.
2130
         * May be set from outside the aplication by means of
2131
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2132
         * of the application
2133
         * @return
2134
         */
2135
        public static String getAppHomeDir() {
2136
                return appHomeDir;
2137
        }
2138

    
2139
        /**
2140
         * Sets Home Directory location of the application.
2141
         * May be set from outside the aplication by means of
2142
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2143
         * of the application
2144
         * @param appHomeDir
2145
         */
2146
        public static void setAppHomeDir(String appHomeDir) {
2147
                Launcher.appHomeDir = appHomeDir;
2148
        }
2149

    
2150
        /**
2151
         * Initialize the extesion that have to take the control
2152
         *  of the state of action controls of the UI of all extensions.
2153
         * <br>
2154
         * <br>
2155
         * For use this option you have to add an argument
2156
         * to the command line like this:
2157
         * <br>
2158
         * <br>
2159
         * -exclusiveUI={pathToExtensionClass}
2160
         * <br>
2161
         *  @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
2162
         *  @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
2163
         */
2164
        private static void initializeExclusiveUIExtension(){
2165
                String name = PluginServices.getArgumentByName("exclusiveUI");
2166
                if (name == null)
2167
                        return;
2168

    
2169

    
2170
                Iterator iter  = classesExtensions.keySet().iterator();
2171
                int charIndex;
2172
                Class key;
2173
                while (iter.hasNext()) {
2174
                        key = (Class)iter.next();
2175
                        charIndex = key.getName().indexOf(name);
2176
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2177
                        if (charIndex == 0) {
2178
                                IExtension ext =(IExtension)classesExtensions.get(key);
2179
                                if (ext instanceof ExtensionDecorator)
2180
                                        ext = ((ExtensionDecorator)ext).getExtension();
2181
                                if (ext instanceof ExclusiveUIExtension)
2182
                                        PluginServices.setExclusiveUIExtension((ExclusiveUIExtension)ext);
2183
                                break;
2184
                        }
2185
                }
2186

    
2187
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2188
        }
2189

    
2190

    
2191
//        public static void initIconThemes() {
2192
//                // load the iconTheme
2193
//                IconThemeManager iconManager = new IconThemeManager();
2194
//                PluginServices.setIconThemeManager(iconManager);
2195
//                IconThemeInfo selectedTheme = iconManager.readConfig();
2196
//                if (selectedTheme!=null) {
2197
//                        iconManager.setDefault(selectedTheme);
2198
//                        logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2199
//                }
2200
//                else {
2201
//                        // set the default dir and try to load the default theme
2202
//                        try {
2203
//                                iconManager.setThemesDir(new File("iconThemes"));
2204
//                                IconThemeInfo[] list = iconManager.list();
2205
//
2206
//                                for (int i=0; i<list.length; i++) {
2207
//                                        if (list[i].getResourceName().equals("iconThemes/icons")) {
2208
//                                                iconManager.setDefault(list[i]);
2209
//                                                logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2210
//                                                return;
2211
//                                        }
2212
//                                }
2213
//                        } catch (FileNotFoundException e) {
2214
//                                logger.info("IconTheme basedir does not exist");
2215
//                        }
2216
//                        // create an empty theme
2217
//                        IconThemeInfo info = new IconThemeInfo();
2218
//                        info.setName("No theme loaded");
2219
//                        info.setResource(null); // null resource means that no real theme is loaded
2220
//                        info.setDescription("No theme loaded");
2221
//                        info.setVersion("0");
2222
//                        iconManager.setDefault(new IconTheme(info));
2223
//                        logger.info("Setting an empty icon theme");
2224
//
2225
//                }
2226
//        }
2227

    
2228
        public static void initIconThemes(){
2229
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2230
                IIconTheme icontheme= iconManager.getIconThemeFromConfig();
2231
                if (icontheme!=null){
2232
                        iconManager.setCurrent(icontheme);
2233
                }
2234
        }
2235

    
2236
        /**
2237
         * Manages Andami termination process
2238
         *
2239
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2240
         */
2241
        public class TerminationProcess {
2242
                private boolean proceed = false;
2243
                private UnsavedDataPanel panel = null;
2244

    
2245
                public void run() {
2246
                        int exit = manageUnsavedData();
2247
                        if (exit==JOptionPane.NO_OPTION || exit == JOptionPane.CLOSED_OPTION) {
2248
                                // the user doesn't want to exit
2249
                                return;
2250
                        }
2251

    
2252
                        closeAndami();
2253
                }
2254

    
2255
                /**
2256
                 * Finishes the application without asking user if want or not to save unsaved data.
2257
                 */
2258
                public void closeAndami() {
2259
                        //Configuraci?n de Andami
2260
                        try {
2261
                                andamiConfigToXML(andamiConfigPath);
2262
                        } catch (MarshalException e) {
2263
                                logger.error(Messages.getString(
2264
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2265
                        } catch (ValidationException e) {
2266
                                logger.error(Messages.getString(
2267
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2268
                        } catch (IOException e) {
2269
                                logger.error(Messages.getString(
2270
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2271
                        }
2272

    
2273
                        //Persistencia de los plugins
2274
                        savePluginPersistence();
2275

    
2276
                        //Finalize all the extensions
2277
                        finalizeExtensions();
2278

    
2279
                        // Clean any temp data created
2280
                        Utilities.cleanUpTempFiles();
2281

    
2282
                        //Para la depuraci?n de memory leaks
2283
                        System.gc();
2284

    
2285
                        System.exit(0);
2286
                }
2287

    
2288
                /**
2289
                 * Exectutes the terminate method for all the extensions, in the reverse
2290
                 * order they were initialized
2291
                 *
2292
                 */
2293
                private void finalizeExtensions() {
2294
                        for (int i=extensions.size()-1; i>=0; i--) {
2295
                                org.gvsig.andami.plugins.IExtension extensionInstance=(org.gvsig.andami.plugins.IExtension)extensions.get(i);
2296
                                extensionInstance.terminate();
2297
                        }
2298
                }
2299

    
2300

    
2301
                private ArrayList getUnsavedData() {
2302
                        ArrayList unsavedDataList = new ArrayList();
2303
                        IExtension exclusiveExtension=PluginServices.getExclusiveUIExtension();
2304

    
2305
                        for (int i=extensions.size()-1; i>=0; i--) {
2306
                                org.gvsig.andami.plugins.IExtension extensionInstance=(org.gvsig.andami.plugins.IExtension)extensions.get(i);
2307
                                IExtensionStatus status = null;
2308
                                if (exclusiveExtension!=null) {
2309
                                        status = exclusiveExtension.getStatus(extensionInstance);
2310
                                }else {
2311
                                        status = extensionInstance.getStatus();
2312
                                }
2313
                                if (status!=null) {
2314
                                        if (status.hasUnsavedData()) {
2315
                                                IUnsavedData[] array = status.getUnsavedData();
2316
                                                for (int element = 0; element<array.length; element++) {
2317
                                                        unsavedDataList.add(array[element]);
2318
                                                }
2319
                                        }
2320
                                }
2321
                        }
2322
                        return unsavedDataList;
2323
                }
2324

    
2325
                public UnsavedDataPanel getUnsavedDataPanel() {
2326
                        if (panel==null) {
2327
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
2328
                        }
2329
                        return panel;
2330
                }
2331
                /**
2332
                 * Checks if the extensions have some unsaved data, and shows a dialog
2333
                 * to allow saving it. This dialog also allows to don't exit Andami.
2334
                 *
2335
                 * @return true if the user confirmed he wishes to exit, false otherwise
2336
                 */
2337
                public int manageUnsavedData(){
2338
                        ArrayList unsavedDataList = getUnsavedData();
2339

    
2340
                        // there was no unsaved data
2341
                        if (unsavedDataList.size()==0) {
2342
                                int option = JOptionPane.showConfirmDialog(frame,
2343
                                                Messages.getString("MDIFrame.quiere_salir"),
2344
                                                Messages.getString("MDIFrame.salir"),
2345
                                                JOptionPane.YES_NO_OPTION);
2346
                                return option;
2347
                        }
2348

    
2349
                        // it does not work if we directly cast the array
2350
                        IUnsavedData[] unsavedDataArray;
2351
                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2352
                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2353

    
2354
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2355
                        panel.setUnsavedDataArray(unsavedDataArray);
2356

    
2357

    
2358
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2359
                                public void cancel(UnsavedDataPanel panel){
2360
                                        proceed(false);
2361
                                        PluginServices.getMDIManager().closeWindow(panel);
2362

    
2363
                                }
2364

    
2365
                                public void discard(UnsavedDataPanel panel){
2366
                                        proceed(true);
2367
                                        PluginServices.getMDIManager().closeWindow(panel);
2368

    
2369
                                }
2370

    
2371
                                public void accept(UnsavedDataPanel panel){
2372
                                        IUnsavedData[] unsavedDataArray = panel.getSelectedsUnsavedData();
2373
                                        boolean saved;
2374
                                        for (int i=0; i<unsavedDataArray.length; i++) {
2375
                                                try {
2376
                                                        saved = unsavedDataArray[i].saveData();
2377
                                                }
2378
                                                catch (Exception ex) {
2379
                                                        PluginServices.getLogger().error("Error saving"+unsavedDataArray[i].getResourceName() ,ex);
2380
                                                        saved = false;
2381
                                                }
2382
                                                if (!saved) {
2383
                                                        JOptionPane.showMessageDialog(
2384
                                                                        panel,
2385
                                                                        PluginServices.getText(this, "The_following_resource_could_not_be_saved_")+
2386
                                                                        "\n"+unsavedDataArray[i].getResourceName() + " -- "
2387
                                                                        + unsavedDataArray[i].getDescription(),
2388
                                                                        PluginServices.getText(this, "Resource_was_not_saved"),
2389
                                                                        JOptionPane.ERROR_MESSAGE);
2390

    
2391
                                                        ArrayList unsavedDataList = getUnsavedData();
2392
                                                        // it does not work if we directly cast the array
2393
                                                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2394
                                                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2395
                                                        panel.setUnsavedDataArray(unsavedDataArray);
2396
                                                        return;
2397
                                                }
2398
                                        }
2399
                                        proceed(true);
2400
                                        PluginServices.getMDIManager().closeWindow(panel);
2401
                                }
2402
                        });
2403

    
2404
                        PluginServices.getMDIManager().addWindow(panel);
2405
                        if (proceed) {
2406
                                return JOptionPane.YES_OPTION;
2407
                        }
2408
                        else {
2409
                                return JOptionPane.NO_OPTION;
2410
                        }
2411
                }
2412

    
2413
                private void proceed(boolean proceed) {
2414
                        this.proceed = proceed;
2415
                }
2416

    
2417

    
2418
        }
2419

    
2420
        public static TerminationProcess getTerminationProcess() {
2421
                return (new Launcher()).new TerminationProcess();
2422
        }
2423
}