Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 33300

History | View | Annotate | Download (76.9 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 com.iver.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.Locale;
81
import java.util.Properties;
82
import java.util.TreeMap;
83
import java.util.prefs.Preferences;
84

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

    
96
import org.apache.log4j.Logger;
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

    
103
import com.iver.andami.authentication.IAuthentication;
104
import com.iver.andami.authentication.LoginUI;
105
import com.iver.andami.config.generate.Andami;
106
import com.iver.andami.config.generate.AndamiConfig;
107
import com.iver.andami.config.generate.Plugin;
108
import com.iver.andami.iconthemes.IIconTheme;
109
import com.iver.andami.iconthemes.IconThemeManager;
110
import com.iver.andami.messages.Messages;
111
import com.iver.andami.messages.NotificationManager;
112
import com.iver.andami.plugins.ExclusiveUIExtension;
113
import com.iver.andami.plugins.ExtensionDecorator;
114
import com.iver.andami.plugins.IExtension;
115
import com.iver.andami.plugins.PluginClassLoader;
116
import com.iver.andami.plugins.config.generate.ActionTool;
117
import com.iver.andami.plugins.config.generate.ComboButton;
118
import com.iver.andami.plugins.config.generate.ComboButtonElement;
119
import com.iver.andami.plugins.config.generate.ComboScale;
120
import com.iver.andami.plugins.config.generate.Depends;
121
import com.iver.andami.plugins.config.generate.Extension;
122
import com.iver.andami.plugins.config.generate.Extensions;
123
import com.iver.andami.plugins.config.generate.LabelSet;
124
import com.iver.andami.plugins.config.generate.Menu;
125
import com.iver.andami.plugins.config.generate.PluginConfig;
126
import com.iver.andami.plugins.config.generate.PopupMenu;
127
import com.iver.andami.plugins.config.generate.PopupMenus;
128
import com.iver.andami.plugins.config.generate.SelectableTool;
129
import com.iver.andami.plugins.config.generate.SkinExtension;
130
import com.iver.andami.plugins.config.generate.SkinExtensionType;
131
import com.iver.andami.plugins.config.generate.ToolBar;
132
import com.iver.andami.plugins.status.IExtensionStatus;
133
import com.iver.andami.plugins.status.IUnsavedData;
134
import com.iver.andami.ui.AndamiEventQueue;
135
import com.iver.andami.ui.MDIManagerLoadException;
136
import com.iver.andami.ui.fonts.FontUtils;
137
import com.iver.andami.ui.mdiFrame.MDIFrame;
138
import com.iver.andami.ui.mdiFrame.NewStatusBar;
139
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
140
import com.iver.andami.ui.splash.MultiSplashWindow;
141
import com.iver.andami.ui.theme.Theme;
142
import com.iver.andami.ui.wizard.UnsavedDataPanel;
143
import com.iver.utiles.DateTime;
144
import com.iver.utiles.FileUtils;
145
import com.iver.utiles.XMLEntity;
146
import com.iver.utiles.xml.XMLEncodingUtils;
147
import com.iver.utiles.xmlEntity.generate.XmlTag;
148

    
149

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

    
183
    private static ArrayList pluginsOrdered = new ArrayList();
184
    private static ArrayList extensions=new ArrayList();
185
    private static String appHomeDir = null;
186
    // it seems castor uses this encoding
187
    private static final String CASTORENCODING = "UTF8";
188

    
189
        private static final class ProxyAuth extends Authenticator {
190
                private PasswordAuthentication auth;
191

    
192
                private ProxyAuth(String user, String pass) {
193
                        auth = new PasswordAuthentication(user, pass.toCharArray());
194
                }
195

    
196
                protected PasswordAuthentication getPasswordAuthentication() {
197
                        return auth;
198
                }
199
        }
200

    
201
    public static void main(String[] args) throws Exception {
202
            try{
203

    
204
                    if (!validJVM()){
205
                            System.exit(-1);
206
                    }
207

    
208
                    if (args.length < 1) {
209
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
210
                    }
211

    
212
                    //  Clean temporal files
213
                    Utilities.cleanUpTempFiles();
214

    
215
                    appName = args[0];
216

    
217
                    appHomeDir = System.getProperty(args[0]+".home");
218
                    if (appHomeDir == null)
219
                            appHomeDir = System.getProperty("user.home");
220

    
221
                    appHomeDir += File.separator + args[0] + File.separator;
222

    
223
                    // If gvSIG.confDir exists, then it will override any other setting for
224
                    // the configuration file path.
225
                    // This is a Java property, which means it has to be passed to the
226
                    // VM like this: java -DgvSIG.confDir=<path>
227
                    String gvsig_conf_dir = System.getProperty("gvSIG.confDir");            
228
                    if ( gvsig_conf_dir != null ) {
229
                            gvsig_conf_dir = gvsig_conf_dir.trim();
230
                            if ( gvsig_conf_dir.length() > 0 ) {
231
                                    if ( gvsig_conf_dir.endsWith(File.separator) ) {
232
                                            appHomeDir = gvsig_conf_dir;
233
                                    } else {
234
                                            appHomeDir = gvsig_conf_dir + File.separator;
235
                                    }
236
                            }
237
                    }
238
                    
239
                    FileUtils.setAppHomeDir(appHomeDir);
240
                    logger.debug("User settings will be stored in: " + appHomeDir );
241
                    
242
                    File parent = new File( appHomeDir );
243
                    parent.mkdirs();                    
244

    
245
                    
246
                    andamiConfigPath = appHomeDir + "andami-config.xml";
247
                    pluginsPersistencePath = appHomeDir + "plugins-persistence.xml";
248

    
249
                    
250
                    // Configurar el log4j
251
                    Launcher.class.getClassLoader()
252
                        .getResource(".");
253
                    PropertyConfigurator.configure("log4j.properties");
254

    
255
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
256
                    
257
                    RollingFileAppender fa = new RollingFileAppender(l,
258
                                    appHomeDir + args[0] + ".log", false);
259

    
260
                    fa.setMaxFileSize("512KB");
261
                    fa.setMaxBackupIndex(3);
262
                    Logger.getRootLogger().addAppender(fa);
263

    
264
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
265
                    // locale
266
                    // Buscar actualizaci?nes al comenzar
267
                    //  Andami
268
                    //  Plugins
269
                    // Directorio de las extensiones
270
                    andamiConfigFromXML(andamiConfigPath);
271
                    andamiConfig.setPluginsDirectory(args[1]);
272

    
273
                    // Hacemos visibles los argumentos como una propiedad est?tica
274
                    // de plugin services para quien lo quiera usar (por ejemplo, para
275
                    // cargar un proyecto por l?nea de comandos)
276
                    PluginServices.setArguments(args);
277

    
278
                    configureLocales(args);
279

    
280
                    //Se pone el lookAndFeel
281
                    try {
282
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
283
                            if (lookAndFeel == null)
284
                                    lookAndFeel = getDefaultLookAndFeel();
285
                            UIManager.setLookAndFeel(lookAndFeel);
286
                    } catch (Exception e) {
287
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
288
                    }
289
                    FontUtils.initFonts();
290

    
291
                    // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
292
                    // System.setSecurityManager(null);
293
                    Policy.setPolicy(new Policy() {
294
                            public PermissionCollection getPermissions(CodeSource codesource) {
295
                                    Permissions perms = new Permissions();
296
                                    perms.add(new AllPermission());
297
                                    return (perms);
298
                            }
299
                            public void
300
                            refresh() {}
301
                    });
302

    
303
                    initIconThemes();
304
//                    Registramos los iconos base
305
                    registerIcons();
306
                    validate();
307

    
308
                    // Obtener la personalizaci?n de la aplicaci?n.
309
                    Theme theme=getTheme();
310

    
311
                    // Mostrar la ventana de inicio
312
                    Frame f=new Frame();
313
                    splashWindow=new MultiSplashWindow(f,theme, 190);
314

    
315
                    // 1. Ponemos los datos del proxy
316
                    splashWindow.process(10,
317
                                    PluginServices.getText(Launcher.class, "SplashWindow.configuring_proxy"));
318
                    configureProxy();
319

    
320
                    // 2. TODO Buscar actualizaciones de los plugins
321
                    splashWindow.process(20,
322
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_updates"));
323
                    downloadExtensions(andamiConfig.getPluginsDirectory());
324

    
325
                    // 3. Se leen los config.xml de los plugins -----++++
326
                    splashWindow.process(30,
327
                                    PluginServices.getText(Launcher.class, "SplashWindow.reading_plugins_config.xml"));
328
                    loadPlugins(andamiConfig.getPluginsDirectory());
329

    
330
                    // 4. Se configura el classloader del plugin
331
                    splashWindow.process(40,
332
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_class_loaders"));
333
                    pluginsClassLoaders();
334

    
335
                    // 5. Se carga un Skin si alguno de los plugins trae informaci?n para ello
336
                    splashWindow.process(50,
337
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
338
//                    skinPlugin(        "com.iver.core.mdiManager.NewSkin");
339
                    skinPlugin(null);
340

    
341
                    // 6. Se configura la cola de eventos
342
                    splashWindow.process(60,
343
                                    PluginServices.getText(Launcher.class, "setting_up_event_queue"));
344
                    EventQueue waitQueue = new AndamiEventQueue();
345
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
346

    
347
                    // 7. Se configura la mensajer?a del plugin
348
                    splashWindow.process(70,
349
                                    PluginServices.getText(Launcher.class, "SplashWindow.starting_plugin_internationalization_system"));
350
                    pluginsMessages();
351

    
352
                    // 8. Se modifica el andami-config con los plugins nuevos
353
                    splashWindow.process(80,
354
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
355
                    updateAndamiConfig();
356

    
357

    
358
                    frame = new MDIFrame();
359
                    // 9. Se configura el nombre e icono de la aplicaci?n
360
                    splashWindow.process(90,
361
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_applications_name_and_icons"));
362
                    frameIcon(theme);
363

    
364
                    // 10. Se prepara el MainFrame para albergar las extensiones
365
                    splashWindow.process(100,
366
                                    PluginServices.getText(Launcher.class, "SplashWindow.preparing_workbench"));
367
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
368

    
369
                    SwingUtilities.invokeAndWait(new Runnable() {
370
                            public void run() {
371
                                    frame.init();
372
                            }
373
                    });
374

    
375

    
376

    
377
                    // 11. Leer el fichero de persistencia
378
                    //  info de los plugins
379
                    //  bookmarks de los plugins
380
                    splashWindow.process(110,
381
                                    PluginServices.getText(Launcher.class, "SplashWindow.loading_plugin_settings"));
382
                    loadPluginsPersistence();
383

    
384

    
385

    
386
                    // Se instalan los controles del skin
387
                    // 12. Se inicializan todas las extensiones de todos los plugins
388
                    splashWindow.process(120,
389
                                        PluginServices.getText(Launcher.class, "SplashWindow.initializing_extensions"));
390
                    SwingUtilities.invokeAndWait(new Runnable() {
391
                            public void run() {
392
                                    initializeExtensions();
393
                            }
394
                    });
395

    
396
                    // 13. Se inicializan la extensi?n exclusiva
397
                        splashWindow.process(130,
398
                                        PluginServices.getText(Launcher.class, "SplashWindow.setting_up_master_extension"));
399
                        SwingUtilities.invokeAndWait(new Runnable() {
400
                            public void run() {
401
                                    initializeExclusiveUIExtension();
402
                            }
403
                    });
404
                    frame.setClassesExtensions(classesExtensions);
405

    
406

    
407

    
408

    
409

    
410
                    // 14. Se instalan los controles de las extensiones de los plugins
411
                    splashWindow.process(140,
412
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_controls"));
413
                    SwingUtilities.invokeAndWait(new Runnable() {
414
                            public void run() {
415
                                    installPluginsControls();
416

    
417
                            }
418
                    });
419

    
420
                    // 15. Se instalan los menus de las extensiones de los plugins
421
                    splashWindow.process(150,
422
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_menus"));
423
                    SwingUtilities.invokeAndWait(new Runnable() {
424
                            public void run() {
425
                                    installPluginsMenus();
426

    
427
                            }
428
                    });
429

    
430
                    // 16. Se instalan las etiquetas de las extensiones de los plugins
431
                    splashWindow.process(160,
432
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_labels"));
433
                    SwingUtilities.invokeAndWait(new Runnable() {
434
                            public void run() {
435
                                    installPluginsLabels();
436

    
437
                            }
438
                    });
439

    
440

    
441
                    // 17. Se instalan los bookmarks de los plugins
442

    
443
                    // 18. Se muestra el frame principal
444
                    splashWindow.process(180,
445
                                    PluginServices.getText(Launcher.class, "creating_main_window"));
446
                    frame.setVisible(true);
447

    
448
                    // 19. Se ejecuta el postInitialize
449
                        splashWindow.process(190,
450
                                        PluginServices.getText(Launcher.class, "SplashWindow.post_initializing_extensions"));
451
                    SwingUtilities.invokeAndWait(new Runnable() {
452
                            public void run() {
453
                                    postInitializeExtensions();
454

    
455
                            }
456
                    });
457

    
458

    
459
                    // Definimos un KeyEventDispatcher global para que las extensiones
460
                    // puedan registrar sus "teclas r?pidas".
461
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
462
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
463

    
464
                    SwingUtilities.invokeAndWait(new Runnable() {
465
                            public void run() {
466
                                    frame.enableControls();
467
                            }
468
                    });
469
                    splashWindow.close();
470
            }catch(Exception e){
471
                    logger.error("excepci?n al arrancar", e);
472
                    System.exit(-1);
473
            }
474

    
475
    }
476

    
477
    private static void registerIcons(){
478
            PluginServices.getIconTheme().registerDefault(
479
                            "login-gvsig",
480
                            LoginUI.class.getClassLoader().getResource("images/login_gvsig.png")
481
                    );
482
            PluginServices.getIconTheme().registerDefault(
483
                            "splash-gvsig",
484
                            MultiSplashWindow.class.getClassLoader().getResource("images/splash.png")
485
                    );
486
            PluginServices.getIconTheme().registerDefault(
487
                            "info-icon",
488
                            NewStatusBar.class.getClassLoader().getResource("images/info.gif")
489
                    );
490
            PluginServices.getIconTheme().registerDefault(
491
                            "error-icon",
492
                            NewStatusBar.class.getClassLoader().getResource("images/error.gif")
493
                    );
494
            PluginServices.getIconTheme().registerDefault(
495
                            "warning-icon",
496
                            NewStatusBar.class.getClassLoader().getResource("images/warning.gif")
497
                    );
498
            PluginServices.getIconTheme().registerDefault(
499
                            "no-icon",
500
                            NewStatusBar.class.getClassLoader().getResource("images/no_icon.png")
501
                    );
502
    }
503

    
504
    /**
505
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
506
     * la aplicaci?n.
507
     *
508
     * @return Theme
509
     */
510
    private static Theme getTheme() {
511
            Theme theme=new Theme();
512
            String name=PluginServices.getArgumentByName("andamiTheme");
513
                //File file=new File("theme/andami-theme.xml");
514
            File file;
515
            if (name==null){
516
                    file=new File("theme/andami-theme.xml");
517
            }else{
518
                    file=new File(name);
519
            }
520

    
521
            if (file.exists()) {
522
                        theme.readTheme(file);
523
                }
524
                return theme;
525
        }
526
        /**
527
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
528
     *del proxy.
529
     */
530
        private static void configureProxy() {
531
                String host = prefs.get("firewall.http.host", "");
532
                String port = prefs.get("firewall.http.port", "");
533

    
534
                System.getProperties().put("http.proxyHost", host);
535
                System.getProperties().put("http.proxyPort", port);
536

    
537
                // Ponemos el usuario y clave del proxy, si existe
538
                String proxyUser = prefs.get("firewall.http.user",null);
539
                String proxyPassword = prefs.get("firewall.http.password", null);
540
                if (proxyUser != null )
541
                {
542
                        System.getProperties().put("http.proxyUserName", proxyUser);
543
                        System.getProperties().put("http.proxyPassword", proxyPassword);
544

    
545
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
546
                                                        proxyPassword));
547
                } else {
548
                        Authenticator.setDefault(new ProxyAuth("", ""));
549
                }
550
        }
551

    
552
        /**
553
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal de Andami.
554
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
555
         * @author LWS
556
         */
557
        private static void restoreMDIStatus(XMLEntity xml) {
558
                if (xml == null) xml = new XMLEntity();
559
                //  restore frame size
560
                Dimension sz = new Dimension(700,580);
561
                if (xml.contains("MDIFrameSize")) {
562
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
563
                        sz = new Dimension(wh[0], wh[1]);
564
                }
565
                frame.setSize(sz);
566
                //  restore frame location
567
                Point pos = new Point(10,10);
568
                if (xml.contains("MDIFramePos")) {
569
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
570
                        pos = new Point(xy[0], xy[1]);
571
                }
572
                frame.setLocation(pos);
573

    
574
                //  restore frame status (Maximized, minimized, etc);
575
                int state = java.awt.Frame.MAXIMIZED_BOTH;
576
                if (xml.contains("MDIFrameState")) {
577
                        state = xml.getIntProperty("MDIFrameState");
578
                }
579
                frame.setExtendedState(state);
580
        }
581

    
582
        private static XMLEntity saveMDIStatus() {
583
                XMLEntity xml = new XMLEntity();
584
                // save frame size
585
                int [] wh = new int[2];
586
                wh[0] = frame.getWidth();
587
                wh[1] = frame.getHeight();
588
                xml.putProperty("MDIFrameSize", wh);
589
                // save frame location
590
                int [] xy = new int[2];
591
                xy[0] = frame.getX();
592
                xy[1] = frame.getY();
593
                xml.putProperty("MDIFramePos", xy);
594
                // save frame status
595
                xml.putProperty("MDIFrameState", frame.getExtendedState());
596
                return xml;
597
        }
598

    
599
    private static boolean validJVM() {
600
        char thirdCharacter = System.getProperty("java.version").charAt(2);
601
        if (thirdCharacter < '4'){
602
            return false;
603
            }else{
604
                return true;
605
            }
606
    }
607

    
608
        private static void loadPluginsPersistence() throws ConfigurationException {
609
                XMLEntity entity = persistenceFromXML();
610

    
611
                for (int i = 0; i < entity.getChildrenCount(); i++) {
612
                        XMLEntity plugin = entity.getChild(i);
613
                        String pName = plugin.getStringProperty(
614
                                        "com.iver.andami.pluginName");
615
                        if (pluginsServices.get(pName)!= null){
616
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
617
                        } else {
618
                                if (pName.startsWith("Andami.Launcher"))
619
                                        restoreMDIStatus(plugin);
620
                        }
621
                }
622
        }
623

    
624
        /**
625
         * Salva la persistencia de los plugins.
626
         * @author LWS
627
         */
628
        private static void savePluginPersistence() {
629
                Iterator i = pluginsConfig.keySet().iterator();
630

    
631
                XMLEntity entity = new XMLEntity();
632

    
633
                while (i.hasNext()) {
634
                        String pName = (String) i.next();
635
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
636
                        XMLEntity ent = ps.getPersistentXML();
637

    
638
                        if (ent != null) {
639
                                ent.putProperty("com.iver.andami.pluginName", pName);
640
                                entity.addChild(ent);
641
                        }
642
                }
643
                XMLEntity ent = saveMDIStatus();
644
                if (ent != null) {
645
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
646
                        entity.addChild(ent);
647
                }
648
                try {
649
                        persistenceToXML(entity);
650
                } catch (ConfigurationException e1) {
651
                        logger.error(Messages.getString(
652
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
653
                                e1);
654
                }
655
        }
656

    
657
        private static void installPluginsLabels() {
658
                Iterator i = pluginsConfig.keySet().iterator();
659

    
660
                while (i.hasNext()) {
661
                        String name = (String) i.next();
662
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
663
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
664

    
665
                        LabelSet[] ls = pc.getLabelSet();
666

    
667
                        for (int j = 0; j < ls.length; j++) {
668
                                PluginClassLoader loader = ps.getClassLoader();
669

    
670
                                try {
671
                                        Class clase = loader.loadClass(ls[j].getClassName());
672
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
673
                                } catch (ClassNotFoundException e) {
674
                                        logger.error(Messages.getString("Launcher.labelset_class"),
675
                                                e);
676
                                }
677
                        }
678
                }
679
        }
680

    
681
        private static String configureSkin(XMLEntity xml,String defaultSkin) {
682
                if (defaultSkin == null){
683
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
684
                                if (xml.getChild(i).contains("Skin-Selected")) {
685
                                        String className = xml.getChild(i).getStringProperty(
686
                                        "Skin-Selected");
687
                                        return className;
688
                                }
689
                        }
690
                }
691
//                return "com.iver.core.mdiManager.NewSkin";
692
                return  defaultSkin;
693
        }
694

    
695
        private static void fixSkin(SkinExtension skinExtension,PluginClassLoader pluginClassLoader) throws MDIManagerLoadException{
696
                // now insert the skin selected.
697
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
698
                // MDIManagerFactory.setSkinExtension(se,
699
                // ps.getClassLoader());
700

    
701
                Class skinClass;
702

    
703
                try {
704
                        skinClass = pluginClassLoader.loadClass(
705
                                        skinExtension.getClassName());
706

    
707
                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass
708
                        .newInstance();
709
                        // classesExtensions.put(skinClass, skinInstance);
710
                        // jaume
711
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
712
                                        skinInstance, ExtensionDecorator.INACTIVE);
713
                        classesExtensions.put(skinClass, newExtensionDecorator);
714
                } catch (ClassNotFoundException e) {
715
                        logger
716
                        .error(
717
                                        Messages
718
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
719
                                        e);
720
                        throw new MDIManagerLoadException(e);
721
                } catch (InstantiationException e) {
722
                        logger
723
                        .error(
724
                                        Messages
725
                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
726
                                        e);
727
                        throw new MDIManagerLoadException(e);
728
                } catch (IllegalAccessException e) {
729
                        logger
730
                        .error(
731
                                        Messages
732
                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
733
                                        e);
734
                        throw new MDIManagerLoadException(e);
735
                }
736

    
737
        }
738
        /**
739
         * DOCUMENT ME!
740
         *
741
         * @throws MDIManagerLoadException
742
         */
743
        private static void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
744
                XMLEntity entity =null;
745
                try {
746
                        entity = persistenceFromXML();
747
                } catch (ConfigurationException e1) {
748
                        // TODO Auto-generated catch block
749
                        e1.printStackTrace();
750
                }
751
                Iterator i = pluginsConfig.keySet().iterator();
752

    
753
                SkinExtension skinExtension = null;
754
                PluginClassLoader pluginClassLoader = null;
755
                ArrayList skinExtensions = new ArrayList();
756
                while (i.hasNext()) {
757
                        String name = (String) i.next();
758
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
759
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
760

    
761
                        if (pc.getExtensions().getSkinExtension() != null) {
762
//                                if (MDIManagerFactory.getSkinExtension() != null) {
763
//                                        logger.warn(Messages.getString(
764
//                                                        "Launcher.Dos_skin_extension"));
765
//                                }
766

    
767
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
768
                                for (int numExten=0; numExten<se.length; numExten++) {
769
                                        skinExtensions.add(se[numExten]);
770
                                }
771
                                for (int j=0;j<se.length;j++){
772
                                        String configuredSkin = Launcher.configureSkin(entity,defaultSkin);
773
                                        if (configuredSkin!=null && configuredSkin.equals(se[j].getClassName())) {
774
                                                skinExtension = se[j];
775
                                                pluginClassLoader = ps.getClassLoader();
776
                                        }
777
                                }
778
                        }
779
                }
780

    
781
                if ((skinExtension != null) && (pluginClassLoader != null)) {
782
                        // configured skin was found
783
                        fixSkin(skinExtension, pluginClassLoader);
784
                } else {
785
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
786
                                // try first NewSkin (from CorePlugin)
787
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
788
                        }
789
                        else if (skinExtensions.size()>0){
790
                                // try to load the first skin found
791
                                SkinExtension se =  (SkinExtension)skinExtensions.get(0);
792
                                skinPlugin((String)se.getClassName());
793
                        }
794
                        else {
795
                                throw new MDIManagerLoadException("No Skin-Extension installed");
796
                        }
797
                }
798

    
799
        }
800

    
801
        private static void frameIcon(Theme theme) {
802
                Iterator i = pluginsConfig.keySet().iterator();
803

    
804
                while (i.hasNext()) {
805
                        String pName = (String) i.next();
806
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
807
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
808
                        if (pc.getIcon() != null) {
809
                                if (theme.getIcon() != null) {
810
                                        frame.setIconImage(theme.getIcon().getImage());
811
                                } else {
812

    
813
                                        ImageIcon icon = PluginServices.getIconTheme().get(pc.getIcon().getSrc());
814
                                        frame.setIconImage(icon.getImage());
815

    
816
                                }
817
                                if (theme.getName() != null) {
818
                                        frame.setTitlePrefix(theme.getName());
819
                                } else {
820
                                        frame.setTitlePrefix(pc.getIcon().getText());
821
                                }
822
                                if (theme.getBackgroundImage() != null) {
823

    
824
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
825
                                }
826
                        }
827
                }
828
        }
829

    
830
        private static void initializeExtensions() {
831
                Iterator i = pluginsOrdered.iterator();
832

    
833
                while (i.hasNext()) {
834
                        String pName = (String) i.next();
835
            logger.debug("Initializing extensions from " + pName);
836
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
837
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
838

    
839
                        Extension[] exts = pc.getExtensions().getExtension();
840

    
841
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
842

    
843
                        for (int j = 0; j < exts.length; j++) {
844
                                if (!exts[j].getActive()) {
845
                                        continue;
846
                                }
847

    
848
                                if (orderedExtensions.containsKey(exts[j])) {
849
                                        logger.warn(Messages.getString(
850
                                                        "Launcher.Two_extensions_with_the_same_priority") +
851
                                                exts[j].getClassName());
852
                                }
853

    
854
                                orderedExtensions.put(exts[j], null);
855
                        }
856

    
857
                        Iterator e = orderedExtensions.keySet().iterator();
858

    
859
                        while (e.hasNext()) {
860
                                Extension extension = (Extension) e.next();
861
                                com.iver.andami.plugins.IExtension extensionInstance;
862

    
863
                                try {
864
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
865
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
866

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

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

    
905
        private static void postInitializeExtensions() {
906
                for (int i=0;i<extensions.size();i++) {
907
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
908
                        extensionInstance.postInitialize();
909
                }
910
        }
911

    
912
        private static void installPluginsMenus() {
913
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
914

    
915
                Iterator i = pluginsConfig.keySet().iterator();
916

    
917
                while (i.hasNext()) {
918
                        String pName = (String) i.next();
919
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
920
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
921

    
922
                        Extension[] exts = pc.getExtensions().getExtension();
923

    
924
                        for (int j = 0; j < exts.length; j++) {
925
                                if (!exts[j].getActive()) {
926
                                        continue;
927
                                }
928

    
929
                                Menu[] menus = exts[j].getMenu();
930

    
931
                                for (int k = 0; k < menus.length; k++) {
932
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
933
                                                        exts[j], menus[k]);
934

    
935
                                        if (orderedMenus.containsKey(sm)) {
936
                                                logger.error(Messages.getString(
937
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
938
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
939
                                        }
940

    
941
                                        orderedMenus.put(sm, null);
942
                                }
943
                        }
944

    
945
                        // Se instalan las extensiones de MDI
946
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
947
                        for (int j = 0; j < skinExts.length; j++) {
948

    
949

    
950
                        if (skinExts[j] != null) {
951
                                Menu[] menu = skinExts[j].getMenu();
952

    
953
                                for (int k = 0; k < menu.length; k++) {
954
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
955
                                                        skinExts[j], menu[k]);
956

    
957
                                        if (orderedMenus.containsKey(sm)) {
958
                                                logger.error(Messages.getString(
959
                                                                "Launcher.Two_menus_with_the_same_position") +
960
                                                        skinExts[j].getClassName());
961
                                        }
962

    
963
                                        orderedMenus.put(sm, null);
964
                                }
965
                        }
966
                        }
967
                }
968

    
969
                //Se itera por los menus ordenados
970
                Iterator e = orderedMenus.keySet().iterator();
971

    
972
                // Se ordenan los menues
973
                while (e.hasNext()) {
974
                        try {
975
                                SortableMenu sm = (SortableMenu) e.next();
976

    
977
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
978
                        } catch (ClassNotFoundException ex) {
979
                                logger.error(Messages.getString(
980
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
981
                        }
982
                }
983
        }
984

    
985
        /**
986
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
987
         * The order in which they are shown is determined here.
988
         */
989
        private static void installPluginsControls() {
990
                Iterator i = pluginsConfig.keySet().iterator();
991

    
992
                HashMap extensionPluginServices = new HashMap();
993
                HashMap extensionPluginConfig = new HashMap();
994
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
995

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

    
1004
                        Extension[] exts = pc.getExtensions().getExtension();
1005

    
1006
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
1007
                                if (exts[j].getActive()) {
1008
                                        if (orderedExtensions.containsKey(exts[j])) {
1009
                                                logger.error(Messages.getString(
1010
                                                "Launcher.Two_extensions_with_the_same_priority") +
1011
                                                exts[j].getClassName());
1012
                                        }
1013

    
1014
                                        orderedExtensions.put(exts[j], null);
1015
                                        extensionPluginServices.put(exts[j], ps);
1016
                                        extensionPluginConfig.put(exts[j], pc);
1017
                                }
1018
                        }
1019
                }
1020

    
1021
                TreeMap orderedTools = new TreeMap(new ToolComparator());
1022
                Iterator e = orderedExtensions.keySet().iterator();
1023

    
1024
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
1025
                // and load the  combo-scales and combo-buttons for the status bar
1026
                while (e.hasNext()) {
1027
                        Extension ext = (Extension) e.next();
1028

    
1029
                        ToolBar[] toolbars = ext.getToolBar();
1030

    
1031
                        // get tools from toolbars
1032
                        for (int k = 0; k < toolbars.length; k++) {
1033
                                ActionTool[] tools = toolbars[k].getActionTool();
1034

    
1035
                                for (int t = 0; t < tools.length; t++) {
1036
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1037
                                                        toolbars[k], tools[t]);
1038
                                        orderedTools.put(sm, null);
1039
                                }
1040

    
1041
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
1042

    
1043
                                for (int t = 0; t < sTools.length; t++) {
1044
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1045
                                                        toolbars[k], sTools[t]);
1046
                                        orderedTools.put(sm, null);
1047
                                }
1048
                        }
1049

    
1050
                        // get controls for statusBar
1051
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
1052
                        PluginClassLoader loader = ps.getClassLoader();
1053

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

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

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

    
1125
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
1126
                        for (int j = 0; j < skinExts.length; j++) {
1127

    
1128

    
1129
                        if (skinExts[j] != null) {
1130
                                ToolBar[] toolbars = skinExts[j].getToolBar();
1131

    
1132
                                for (int k = 0; k < toolbars.length; k++) {
1133
                                        ActionTool[] tools = toolbars[k].getActionTool();
1134

    
1135
                                        for (int t = 0; t < tools.length; t++) {
1136
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1137
                                                                toolbars[k], tools[t]);
1138
                                                orderedTools.put(stb,null);
1139
                                        }
1140

    
1141
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1142

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

    
1154
                        if (pus != null) {
1155
                                PopupMenu[] menus = pus.getPopupMenu();
1156

    
1157
                                for (int j = 0; j < menus.length; j++) {
1158
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1159
                                }
1160
                        }
1161
                }
1162

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

    
1179
        /**
1180
         * Adds new plugins to the the andami-config file.
1181
         */
1182
        private static void updateAndamiConfig() {
1183
                HashSet olds = new HashSet();
1184

    
1185
                Plugin[] plugins = andamiConfig.getPlugin();
1186

    
1187
                for (int i = 0; i < plugins.length; i++) {
1188
                        olds.add(plugins[i].getName());
1189
                }
1190

    
1191
                Iterator i = pluginsServices.values().iterator();
1192

    
1193
                while (i.hasNext()) {
1194
                        PluginServices ps = (PluginServices) i.next();
1195

    
1196
                        if (!olds.contains(ps.getPluginName())) {
1197
                                Plugin p = new Plugin();
1198
                                p.setName(ps.getPluginName());
1199
                                p.setUpdate(false);
1200

    
1201
                                andamiConfig.addPlugin(p);
1202
                        }
1203
                }
1204
        }
1205

    
1206
        private static void pluginsClassLoaders() {
1207
                HashSet instalados = new HashSet();
1208

    
1209
                // Se itera hasta que est?n todos instalados
1210
                while (instalados.size() != pluginsConfig.size()) {
1211
                        boolean circle = true;
1212

    
1213
                        //Hacemos una pasada por todos los plugins
1214
                        Iterator i = pluginsConfig.keySet().iterator();
1215

    
1216
                        while (i.hasNext()) {
1217
                                String pluginName = (String) i.next();
1218
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1219

    
1220
                                if (instalados.contains(pluginName)) {
1221
                                        continue;
1222
                                }
1223

    
1224
                                //Se obtienen las dependencias y sus class loaders
1225
                                boolean ready = true;
1226
                                Depends[] dependencies = config.getDepends();
1227
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1228

    
1229
                                for (int j = 0; j < dependencies.length; j++) {
1230
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1231
                                                logger.error(Messages.getString(
1232
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1233
                                                        pluginName + ": " +
1234
                                                        dependencies[j].getPluginName());
1235

    
1236
                                                continue;
1237
                                        }
1238

    
1239
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1240
                                                ready = false;
1241
                                        } else {
1242
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1243
                                        }
1244
                                }
1245

    
1246
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1247
                                if (!ready) {
1248
                                        continue;
1249
                                }
1250

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

    
1263
                                URL[] urls = new URL[jarFiles.length];
1264

    
1265
                                for (int j = 0; j < jarFiles.length; j++) {
1266
                                        try {
1267
                                                urls[j] = new URL("file:" + jarFiles[j]);
1268
                                        } catch (MalformedURLException e) {
1269
                                                logger.error(Messages.getString(
1270
                                                                "Launcher.No_se_puede_acceder_a") +
1271
                                                        jarFiles[j]);
1272
                                        }
1273
                                }
1274

    
1275
                                PluginClassLoader loader;
1276

    
1277
                                try {
1278
                                        loader = new PluginClassLoader(urls,
1279
                                                        andamiConfig.getPluginsDirectory() +
1280
                                                        File.separator + pluginName,
1281
                                                        Launcher.class.getClassLoader(), loaders);
1282

    
1283
                                        PluginServices ps = new PluginServices(loader);
1284

    
1285
                                        pluginsServices.put(ps.getPluginName(), ps);
1286

    
1287
                                        instalados.add(pluginName);
1288
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1289
                    // inicializar los plugins
1290
                    pluginsOrdered.add(pluginName);
1291

    
1292
                                        circle = false;
1293
                                } catch (IOException e) {
1294
                                        logger.error(Messages.getString(
1295
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1296
                                        pluginsConfig.remove(pluginName);
1297
                                        i = pluginsConfig.keySet().iterator();
1298
                                }
1299
                        }
1300

    
1301
                        if (circle) {
1302
                                logger.error(Messages.getString(
1303
                                                "Launcher.Hay_dependencias_circulares"));
1304

    
1305
                                break;
1306
                        }
1307
                }
1308

    
1309
                //Se eliminan los plugins que no fueron instalados
1310
                Iterator i = pluginsConfig.keySet().iterator();
1311

    
1312
                while (i.hasNext()) {
1313
                        String pluginName = (String) i.next();
1314
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1315
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1316

    
1317
                        if (ps == null) {
1318
                                pluginsConfig.remove(pluginName);
1319
                                i = pluginsConfig.keySet().iterator();
1320
                        }
1321
                }
1322
        }
1323

    
1324
        private static void pluginsMessages() {
1325
                Iterator iterator = pluginsOrdered.iterator();
1326
                PluginConfig config;
1327
                PluginServices ps;
1328

    
1329
                while (iterator.hasNext()) {
1330
                        String pluginName = (String) iterator.next();
1331
                        config = (PluginConfig) pluginsConfig.get(pluginName);
1332
                        ps = (PluginServices) pluginsServices.get(pluginName);
1333

    
1334
                        if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1335
                                // add the locale files associated with the plugin
1336
                                org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1337
                        }
1338
                }
1339
        }
1340

    
1341
        static PluginServices getPluginServices(String name) {
1342
                return (PluginServices) pluginsServices.get(name);
1343
        }
1344

    
1345
        static String getPluginsDir() {
1346
                return andamiConfig.getPluginsDirectory();
1347
        }
1348

    
1349
        static void setPluginsDir(String s) {
1350
                andamiConfig.setPluginsDirectory(s);
1351
        }
1352

    
1353
        static MDIFrame getMDIFrame() {
1354
                return frame;
1355
        }
1356

    
1357
        private static void loadPlugins(String pluginsDirectory) {
1358
                File pDir = new File(pluginsDirectory);
1359

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

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

    
1373
                for (int i = 0; i < pluginDirs.length; i++) {
1374
                        if (pluginDirs[i].isDirectory()) {
1375
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1376
                                                File.separator + "config.xml");
1377

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

    
1410
                if (pluginsConfig.size()==0) {
1411
                        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...");
1412
                        System.exit(-1);
1413
                        return;
1414
                }
1415
        }
1416

    
1417
        private static Locale getLocale(String language, String country,
1418
                String variant) {
1419
                if (variant != null) {
1420
                        return new Locale(language, country, variant);
1421
                } else if (country != null) {
1422
                        return new Locale(language, country);
1423
                } else if (language != null) {
1424
                        return new Locale(language);
1425
                } else {
1426
                        return new Locale("es");
1427
                }
1428
        }
1429

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

    
1438
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile));
1439
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
1440
                andamiConfig.marshal(writer);
1441
                writer.close();
1442

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

    
1455
        private static void andamiConfigFromXML(String file)
1456
                throws ConfigurationException {
1457
                File xml = new File(file);
1458

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

    
1482
        private static AndamiConfig getDefaultAndamiConfig() {
1483
                AndamiConfig andamiConfig = new AndamiConfig();
1484

    
1485
                Andami andami = new Andami();
1486
                andami.setUpdate(true);
1487
                andamiConfig.setAndami(andami);
1488
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1489
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1490
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1491

    
1492
                if (System.getProperty("javawebstart.version") != null) // Es java web start)
1493
                 {
1494
                        andamiConfig.setPluginsDirectory(new File(appHomeDir
1495
                                        + "extensiones").getAbsolutePath());
1496
                } else {
1497
                        andamiConfig.setPluginsDirectory(new File(appName +
1498
                                        File.separator + "extensiones").getAbsolutePath());
1499
                }
1500

    
1501
                andamiConfig.setPlugin(new Plugin[0]);
1502
                return andamiConfig;
1503
        }
1504

    
1505
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1506
                File xml = new File(pluginsPersistencePath);
1507

    
1508
                if (xml.exists()) {
1509
                        InputStreamReader reader = null;
1510

    
1511
                        try {
1512
                                reader = XMLEncodingUtils.getReader(xml);
1513
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1514
                                return new XMLEntity(tag);
1515
                        } catch (FileNotFoundException e) {
1516
                                throw new ConfigurationException(e);
1517
                        } catch (MarshalException e) {
1518

    
1519
                                // try to reopen with default encoding (for backward compatibility)
1520
                                try {
1521
                                        reader = new FileReader(xml);
1522
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1523
                                        return new XMLEntity(tag);
1524

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

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

    
1555
                File xml = new File(pluginsPersistencePath);
1556
                OutputStreamWriter writer = null;
1557

    
1558
                try {
1559
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile), CASTORENCODING);
1560
                        entity.getXmlTag().marshal(writer);
1561
                        writer.close();
1562

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

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

    
1588
        static MDIFrame getFrame() {
1589
                return frame;
1590
        }
1591

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

    
1602
        static HashMap getClassesExtensions() {
1603
                return classesExtensions;
1604
        }
1605

    
1606
        private static void downloadExtensions(String extDir) {
1607
                java.util.Date fechaActual = null;
1608

    
1609
                try {
1610
                        if (System.getProperty("javawebstart.version") != null) {
1611
                                //Obtenemos la URL del servidor
1612
                                BasicService bs = (BasicService) ServiceManager.lookup(
1613
                                                "javax.jnlp.BasicService");
1614
                                URL baseURL = bs.getCodeBase();
1615

    
1616
                                //Se descargan las extensiones
1617
                                splashWindow.process(5,
1618
                                        "Descargando las extensiones desde " + baseURL + " a " +
1619
                                        extDir);
1620

    
1621
                                URL url = new URL(baseURL + "extensiones.zip");
1622
                                URLConnection connection = url.openConnection();
1623

    
1624
                                System.out.println(url.toExternalForm() + ":");
1625
                                System.out.println("  Content Type: " +
1626
                                        connection.getContentType());
1627
                                System.out.println("  Content Length: " +
1628
                                        connection.getContentLength());
1629
                                System.out.println("  Last Modified: " +
1630
                                        new Date(connection.getLastModified()));
1631
                                System.out.println("  Expiration: " +
1632
                                        connection.getExpiration());
1633
                                System.out.println("  Content Encoding: " +
1634
                                        connection.getContentEncoding());
1635

    
1636
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1637
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1638
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1639
                                // nos bajamos nada.
1640
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1641

    
1642
                                File destDir = new File(extDir);
1643

    
1644
                                if (!destDir.exists()) {
1645
                                        // Creamos gvSIG
1646
                                        destDir.getParentFile().mkdir();
1647

    
1648
                                        if (!destDir.mkdir()) {
1649
                                                System.err.println("Imposible crear el directorio " +
1650
                                                        destDir.getAbsolutePath());
1651
                                        }
1652
                                }
1653

    
1654
                                File timeFile = new File(destDir.getParent() + File.separator +
1655
                                                "timeStamp.properties");
1656

    
1657
                                if (!timeFile.exists()) {
1658
                                        timeFile.createNewFile();
1659
                                }
1660

    
1661
                                FileInputStream inAux = new FileInputStream(timeFile);
1662
                                Properties prop = new Properties();
1663
                                prop.load(inAux);
1664
                                inAux.close();
1665

    
1666
                                if (prop.getProperty("timestamp") != null) {
1667
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1668
                                                                "timestamp"));
1669

    
1670
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1671
                                                System.out.println("No hay nueva actualizaci?n");
1672
                        logger.debug("No hay nueva actualizaci?n -> Return");
1673
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1674
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1675

    
1676
                                                return;
1677
                                        }
1678

    
1679
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1680
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1681
                                } else {
1682
                                        System.out.println("El timeStamp no est? escrito en " +
1683
                                                timeFile.getAbsolutePath());
1684
                                }
1685

    
1686
                                InputStream stream = url.openStream();
1687
                File temp = File.createTempFile("gvsig", ".zip");
1688

    
1689
                logger.debug(temp.getAbsolutePath());
1690

    
1691
                temp.deleteOnExit();
1692
                FileOutputStream file = new FileOutputStream(temp);
1693

    
1694
                byte[] lt_read = new byte[1];
1695

    
1696
                while (stream.read(lt_read) > 0)
1697
                  file.write(lt_read);
1698

    
1699
                                stream.close();
1700
                stream = null;
1701
                file.close();
1702
                file = null;
1703

    
1704
                System.gc();
1705

    
1706
                logger.debug("Ha creado el fichero ZIP");
1707
                                //Se extrae el zip
1708
                splashWindow.process(5, "Extensiones descargadas.");
1709

    
1710
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1711

    
1712
                                Date fechaDir = new Date(destDir.lastModified());
1713
                                System.out.println("Fecha del directorio " + extDir + " = " +
1714
                                        fechaDir.toString());
1715
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1716

    
1717
                                // Si todo ha ido bien, guardamos el timestamp.
1718
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1719
                                // XMLEntity xml=ps.getPersistentXML();
1720
                                fechaActual = new java.util.Date();
1721

    
1722
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1723
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1724
                                prop.store(outAux, "last download");
1725
                                outAux.close();
1726
                                System.out.println("Fecha actual guardada: " +
1727
                                        fechaActual.toGMTString());
1728

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

    
1743
        private static Extensions[] getExtensions() {
1744
                ArrayList array = new ArrayList();
1745
                Iterator iter = pluginsConfig.values().iterator();
1746

    
1747
                while (iter.hasNext()) {
1748
                        array.add(((PluginConfig) iter.next()).getExtensions());
1749
                }
1750

    
1751
                return (Extensions[]) array.toArray(new Extensions[0]);
1752
        }
1753

    
1754
        public static Iterator getExtensionIterator() {
1755
                return extensions.iterator();
1756
        }
1757

    
1758
        public static HashMap getPluginConfig() {
1759
                return pluginsConfig;
1760
        }
1761

    
1762
        public static Extension getExtension(String s) {
1763
                Extensions[] exts = getExtensions();
1764

    
1765
                for (int i = 0; i < exts.length; i++) {
1766
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1767
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1768
                                        return exts[i].getExtension(j);
1769
                                }
1770
                        }
1771
                }
1772

    
1773
                return null;
1774
        }
1775

    
1776
        public static AndamiConfig getAndamiConfig() {
1777
                return andamiConfig;
1778
        }
1779

    
1780
        private static class ExtensionComparator implements Comparator {
1781
                public int compare(Object o1, Object o2) {
1782
                        Extension e1 = (Extension) o1;
1783
                        Extension e2 = (Extension) o2;
1784

    
1785
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1786
                                return -1;
1787
                        }
1788

    
1789
                        if (e1.hasPriority() && !e2.hasPriority()) {
1790
                                return Integer.MIN_VALUE;
1791
                        }
1792

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

    
1797
                        if (e1.getPriority() != e2.getPriority()){
1798
                                return e2.getPriority() - e1.getPriority();
1799
                        }else{
1800
                                return (e2.toString().compareTo(e1.toString()));
1801
                        }
1802
                }
1803
        }
1804

    
1805
        private static class MenuComparator implements Comparator {
1806
                private static ExtensionComparator extComp = new ExtensionComparator();
1807

    
1808
                public int compare(Object o1, Object o2) {
1809
                        SortableMenu e1 = (SortableMenu) o1;
1810
                        SortableMenu e2 = (SortableMenu) o2;
1811

    
1812
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1813
                                if (e1.extension instanceof SkinExtensionType) {
1814
                                        return 1;
1815
                                } else if (e2.extension instanceof SkinExtensionType) {
1816
                                        return -1;
1817
                                } else {
1818
                                        return extComp.compare(e1.extension, e2.extension);
1819
                                }
1820
                        }
1821

    
1822
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1823
                                return Integer.MIN_VALUE;
1824
                        }
1825

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

    
1838
        private static class SortableMenu {
1839
                public PluginClassLoader loader;
1840
                public Menu menu;
1841
                public SkinExtensionType extension;
1842

    
1843
                public SortableMenu(PluginClassLoader loader,
1844
                        SkinExtensionType skinExt, Menu menu2) {
1845
                        extension = skinExt;
1846
                        menu = menu2;
1847
                        this.loader = loader;
1848
                }
1849
        }
1850

    
1851
        private static class SortableTool {
1852
                public PluginClassLoader loader;
1853
                public ToolBar toolbar;
1854
                public ActionTool actiontool;
1855
                public SelectableTool selectabletool;
1856
                public SkinExtensionType extension;
1857

    
1858
                public SortableTool(PluginClassLoader loader,
1859
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1860
                        extension = skinExt;
1861
                        toolbar = toolbar2;
1862
                        actiontool=actiontool2;
1863
                        this.loader = loader;
1864
                }
1865
                public SortableTool(PluginClassLoader loader,
1866
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1867
                        extension = skinExt;
1868
                        toolbar = toolbar2;
1869
                        selectabletool=selectabletool2;
1870
                        this.loader = loader;
1871
                }
1872
        }
1873

    
1874
        private static class ToolBarComparator implements Comparator {
1875
                private static ExtensionComparator extComp = new ExtensionComparator();
1876

    
1877
                public int compare(Object o1, Object o2) {
1878
                        SortableTool e1 = (SortableTool) o1;
1879
                        SortableTool e2 = (SortableTool) o2;
1880

    
1881
                        // if the toolbars have the same name, they are considered to be
1882
                        // the same toolbar, so we don't need to do further comparing
1883
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1884
                                return 0;
1885

    
1886
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1887
                                if (e1.extension instanceof SkinExtensionType) {
1888
                                        return 1;
1889
                                } else if (e2.extension instanceof SkinExtensionType) {
1890
                                        return -1;
1891
                                } else {
1892
                                        return extComp.compare(e1.extension, e2.extension);
1893
                                }
1894
                        }
1895

    
1896
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1897
                                return Integer.MIN_VALUE;
1898
                        }
1899

    
1900
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1901
                                return Integer.MAX_VALUE;
1902
                        }
1903
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1904
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1905

    
1906
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1907
                                return 0;
1908
                        }
1909
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1910
                }
1911
        }
1912

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

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

    
1944
                        if (e1.actiontool!=null) {
1945
                                if (e1.actiontool.hasPosition())
1946
                                        e1Position = e1.actiontool.getPosition();
1947
                        }
1948
                        else if (e1.selectabletool!=null) {
1949
                                if (e1.selectabletool.hasPosition())
1950
                                        e1Position = e1.selectabletool.getPosition();
1951
                        }
1952

    
1953
                        if (e2.actiontool!=null) {
1954
                                if (e2.actiontool.hasPosition())
1955
                                        e2Position = e2.actiontool.getPosition();
1956
                        }
1957
                        else if (e2.selectabletool!=null){
1958
                                if (e2.selectabletool.hasPosition())
1959
                                        e2Position = e2.selectabletool.getPosition();
1960
                        }
1961

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

    
1977

    
1978
        /**
1979
         * validates the user before starting gvsig
1980
         *
1981
         */
1982
        private static void validate(){
1983

    
1984
                IAuthentication session =  null;
1985
                try {
1986
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1987

    
1988
                } catch (ClassNotFoundException e) {
1989
                        return;
1990
                } catch (InstantiationException e) {
1991
                        return;
1992
                } catch (IllegalAccessException e) {
1993
                        return;
1994
                }
1995

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

    
2010
        public static String getDefaultLookAndFeel() {
2011
                String osName = (String) System.getProperty("os.name");
2012

    
2013
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2014
                        return nonWinDefaultLookAndFeel;
2015
                if (osName.toLowerCase().startsWith("mac os x"))
2016
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2017

    
2018

    
2019
                return UIManager.getSystemLookAndFeelClassName();
2020
        }
2021

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

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

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

    
2121
        }
2122

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

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

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

    
2164

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

    
2182
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2183
        }
2184

    
2185

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

    
2223
        public static void initIconThemes(){
2224
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2225
                IIconTheme icontheme= iconManager.getIconThemeFromConfig();
2226
                if (icontheme!=null){
2227
                        iconManager.setCurrent(icontheme);
2228
                }
2229
        }
2230

    
2231
        /**
2232
         * Manages Andami termination process
2233
         *
2234
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2235
         */
2236
        public class TerminationProcess {
2237
                private boolean proceed = false;
2238
                private UnsavedDataPanel panel = null;
2239

    
2240
                public void run() {
2241
                        int exit = manageUnsavedData();
2242
                        if (exit==JOptionPane.NO_OPTION || exit == JOptionPane.CLOSED_OPTION) {
2243
                                // the user doesn't want to exit
2244
                                return;
2245
                        }
2246

    
2247
                        closeAndami();
2248
                }
2249

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

    
2268
                        //Persistencia de los plugins
2269
                        savePluginPersistence();
2270

    
2271
                        //Finalize all the extensions
2272
                        finalizeExtensions();
2273

    
2274
                        // Clean any temp data created
2275
                        Utilities.cleanUpTempFiles();
2276

    
2277
                        //Para la depuraci?n de memory leaks
2278
                        System.gc();
2279

    
2280
                        System.exit(0);
2281
                }
2282

    
2283
                /**
2284
                 * Exectutes the terminate method for all the extensions, in the reverse
2285
                 * order they were initialized
2286
                 *
2287
                 */
2288
                private void finalizeExtensions() {
2289
                        for (int i=extensions.size()-1; i>=0; i--) {
2290
                                com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
2291
                                extensionInstance.terminate();
2292
                        }
2293
                }
2294

    
2295

    
2296
                private ArrayList getUnsavedData() {
2297
                        ArrayList unsavedDataList = new ArrayList();
2298
                        IExtension exclusiveExtension=PluginServices.getExclusiveUIExtension();
2299

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

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

    
2335
                        // there was no unsaved data
2336
                        if (unsavedDataList.size()==0) {
2337
                                int option = JOptionPane.showConfirmDialog(frame,
2338
                                                Messages.getString("MDIFrame.quiere_salir"),
2339
                                                Messages.getString("MDIFrame.salir"),
2340
                                                JOptionPane.YES_NO_OPTION);
2341
                                return option;
2342
                        }
2343

    
2344
                        // it does not work if we directly cast the array
2345
                        IUnsavedData[] unsavedDataArray;
2346
                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2347
                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2348

    
2349
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2350
                        panel.setUnsavedDataArray(unsavedDataArray);
2351

    
2352

    
2353
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2354
                                public void cancel(UnsavedDataPanel panel){
2355
                                        proceed(false);
2356
                                        PluginServices.getMDIManager().closeWindow(panel);
2357

    
2358
                                }
2359

    
2360
                                public void discard(UnsavedDataPanel panel){
2361
                                        proceed(true);
2362
                                        PluginServices.getMDIManager().closeWindow(panel);
2363

    
2364
                                }
2365

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

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

    
2399
                        PluginServices.getMDIManager().addWindow(panel);
2400
                        if (proceed) {
2401
                                return JOptionPane.YES_OPTION;
2402
                        }
2403
                        else {
2404
                                return JOptionPane.NO_OPTION;
2405
                        }
2406
                }
2407

    
2408
                private void proceed(boolean proceed) {
2409
                        this.proceed = proceed;
2410
                }
2411

    
2412

    
2413
        }
2414

    
2415
        public static TerminationProcess getTerminationProcess() {
2416
                return (new Launcher()).new TerminationProcess();
2417
        }
2418
}