Statistics
| Revision:

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

History | View | Annotate | Download (76.2 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.XMLEntity;
145
import com.iver.utiles.xml.XMLEncodingUtils;
146
import com.iver.utiles.xmlEntity.generate.XmlTag;
147

    
148

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

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

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

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

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

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

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

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

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

    
214
                    appName = args[0];
215

    
216
                    //Se crea el directorio de configuraci?n de la aplicaci?n
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
                    File parent = new File( appHomeDir );
223
                    parent.mkdirs();
224

    
225
                    andamiConfigPath = appHomeDir + "andami-config.xml";
226
                    pluginsPersistencePath = appHomeDir +
227
                    "plugins-persistence.xml";
228

    
229
                    // Configurar el log4j
230
                    Launcher.class.getClassLoader()
231
                        .getResource(".");
232
                    PropertyConfigurator.configure("log4j.properties");
233

    
234
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
235
                    RollingFileAppender fa = new RollingFileAppender(l,
236
                                    appHomeDir + args[0] + ".log", false);
237
                    fa.setMaxFileSize("512KB");
238
                    fa.setMaxBackupIndex(3);
239
                    Logger.getRootLogger().addAppender(fa);
240

    
241
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
242
                    // locale
243
                    // Buscar actualizaci?nes al comenzar
244
                    //  Andami
245
                    //  Plugins
246
                    // Directorio de las extensiones
247
                    andamiConfigFromXML(andamiConfigPath);
248
                    andamiConfig.setPluginsDirectory(args[1]);
249

    
250
                    // Hacemos visibles los argumentos como una propiedad est?tica
251
                    // de plugin services para quien lo quiera usar (por ejemplo, para
252
                    // cargar un proyecto por l?nea de comandos)
253
                    PluginServices.setArguments(args);
254

    
255
                    configureLocales(args);
256

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

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

    
280
                    initIconThemes();
281
//                    Registramos los iconos base
282
                    registerIcons();
283
                    validate();
284

    
285
                    // Obtener la personalizaci?n de la aplicaci?n.
286
                    Theme theme=getTheme();
287

    
288
                    // Mostrar la ventana de inicio
289
                    Frame f=new Frame();
290
                    splashWindow=new MultiSplashWindow(f,theme, 190);
291

    
292
                    // 1. Ponemos los datos del proxy
293
                    splashWindow.process(10,
294
                                    PluginServices.getText(Launcher.class, "SplashWindow.configuring_proxy"));
295
                    configureProxy();
296

    
297
                    // 2. TODO Buscar actualizaciones de los plugins
298
                    splashWindow.process(20,
299
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_updates"));
300
                    downloadExtensions(andamiConfig.getPluginsDirectory());
301

    
302
                    // 3. Se leen los config.xml de los plugins -----++++
303
                    splashWindow.process(30,
304
                                    PluginServices.getText(Launcher.class, "SplashWindow.reading_plugins_config.xml"));
305
                    loadPlugins(andamiConfig.getPluginsDirectory());
306

    
307
                    // 4. Se configura el classloader del plugin
308
                    splashWindow.process(40,
309
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_class_loaders"));
310
                    pluginsClassLoaders();
311

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

    
318
                    // 6. Se configura la cola de eventos
319
                    splashWindow.process(60,
320
                                    PluginServices.getText(Launcher.class, "setting_up_event_queue"));
321
                    EventQueue waitQueue = new AndamiEventQueue();
322
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
323

    
324
                    // 7. Se configura la mensajer?a del plugin
325
                    splashWindow.process(70,
326
                                    PluginServices.getText(Launcher.class, "SplashWindow.starting_plugin_internationalization_system"));
327
                    pluginsMessages();
328

    
329
                    // 8. Se modifica el andami-config con los plugins nuevos
330
                    splashWindow.process(80,
331
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
332
                    updateAndamiConfig();
333

    
334

    
335
                    frame = new MDIFrame();
336
                    // 9. Se configura el nombre e icono de la aplicaci?n
337
                    splashWindow.process(90,
338
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_applications_name_and_icons"));
339
                    frameIcon(theme);
340

    
341
                    // 10. Se prepara el MainFrame para albergar las extensiones
342
                    splashWindow.process(100,
343
                                    PluginServices.getText(Launcher.class, "SplashWindow.preparing_workbench"));
344
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
345

    
346
                    SwingUtilities.invokeAndWait(new Runnable() {
347
                            public void run() {
348
                                    frame.init();
349
                            }
350
                    });
351

    
352

    
353

    
354
                    // 11. Leer el fichero de persistencia
355
                    //  info de los plugins
356
                    //  bookmarks de los plugins
357
                    splashWindow.process(110,
358
                                    PluginServices.getText(Launcher.class, "SplashWindow.loading_plugin_settings"));
359
                    loadPluginsPersistence();
360

    
361

    
362

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

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

    
383

    
384

    
385

    
386

    
387
                    // 14. Se instalan los controles de las extensiones de los plugins
388
                    splashWindow.process(140,
389
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_controls"));
390
                    SwingUtilities.invokeAndWait(new Runnable() {
391
                            public void run() {
392
                                    installPluginsControls();
393

    
394
                            }
395
                    });
396

    
397
                    // 15. Se instalan los menus de las extensiones de los plugins
398
                    splashWindow.process(150,
399
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_menus"));
400
                    SwingUtilities.invokeAndWait(new Runnable() {
401
                            public void run() {
402
                                    installPluginsMenus();
403

    
404
                            }
405
                    });
406

    
407
                    // 16. Se instalan las etiquetas de las extensiones de los plugins
408
                    splashWindow.process(160,
409
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_labels"));
410
                    SwingUtilities.invokeAndWait(new Runnable() {
411
                            public void run() {
412
                                    installPluginsLabels();
413

    
414
                            }
415
                    });
416

    
417

    
418
                    // 17. Se instalan los bookmarks de los plugins
419

    
420
                    // 18. Se muestra el frame principal
421
                    splashWindow.process(180,
422
                                    PluginServices.getText(Launcher.class, "creating_main_window"));
423
                    frame.setVisible(true);
424

    
425
                    // 19. Se ejecuta el postInitialize
426
                        splashWindow.process(190,
427
                                        PluginServices.getText(Launcher.class, "SplashWindow.post_initializing_extensions"));
428
                    SwingUtilities.invokeAndWait(new Runnable() {
429
                            public void run() {
430
                                    postInitializeExtensions();
431

    
432
                            }
433
                    });
434

    
435

    
436
                    // Definimos un KeyEventDispatcher global para que las extensiones
437
                    // puedan registrar sus "teclas r?pidas".
438
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
439
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
440

    
441
                    SwingUtilities.invokeAndWait(new Runnable() {
442
                            public void run() {
443
                                    frame.enableControls();
444
                            }
445
                    });
446
                    splashWindow.close();
447
            }catch(Exception e){
448
                    logger.error("excepci?n al arrancar", e);
449
                    System.exit(-1);
450
            }
451

    
452
    }
453

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

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

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

    
511
                System.getProperties().put("http.proxyHost", host);
512
                System.getProperties().put("http.proxyPort", port);
513

    
514
                // Ponemos el usuario y clave del proxy, si existe
515
                String proxyUser = prefs.get("firewall.http.user",null);
516
                String proxyPassword = prefs.get("firewall.http.password", null);
517
                if (proxyUser != null )
518
                {
519
                        System.getProperties().put("http.proxyUserName", proxyUser);
520
                        System.getProperties().put("http.proxyPassword", proxyPassword);
521

    
522
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
523
                                                        proxyPassword));
524
                } else {
525
                        Authenticator.setDefault(new ProxyAuth("", ""));
526
                }
527
        }
528

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

    
551
                //  restore frame status (Maximized, minimized, etc);
552
                int state = java.awt.Frame.MAXIMIZED_BOTH;
553
                if (xml.contains("MDIFrameState")) {
554
                        state = xml.getIntProperty("MDIFrameState");
555
                }
556
                frame.setExtendedState(state);
557
        }
558

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

    
576
    private static boolean validJVM() {
577
        char thirdCharacter = System.getProperty("java.version").charAt(2);
578
        if (thirdCharacter < '4'){
579
            return false;
580
            }else{
581
                return true;
582
            }
583
    }
584

    
585
        private static void loadPluginsPersistence() throws ConfigurationException {
586
                XMLEntity entity = persistenceFromXML();
587

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

    
601
        /**
602
         * Salva la persistencia de los plugins.
603
         * @author LWS
604
         */
605
        private static void savePluginPersistence() {
606
                Iterator i = pluginsConfig.keySet().iterator();
607

    
608
                XMLEntity entity = new XMLEntity();
609

    
610
                while (i.hasNext()) {
611
                        String pName = (String) i.next();
612
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
613
                        XMLEntity ent = ps.getPersistentXML();
614

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

    
634
        private static void installPluginsLabels() {
635
                Iterator i = pluginsConfig.keySet().iterator();
636

    
637
                while (i.hasNext()) {
638
                        String name = (String) i.next();
639
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
640
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
641

    
642
                        LabelSet[] ls = pc.getLabelSet();
643

    
644
                        for (int j = 0; j < ls.length; j++) {
645
                                PluginClassLoader loader = ps.getClassLoader();
646

    
647
                                try {
648
                                        Class clase = loader.loadClass(ls[j].getClassName());
649
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
650
                                } catch (ClassNotFoundException e) {
651
                                        logger.error(Messages.getString("Launcher.labelset_class"),
652
                                                e);
653
                                }
654
                        }
655
                }
656
        }
657

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

    
672
        private static void fixSkin(SkinExtension skinExtension,PluginClassLoader pluginClassLoader) throws MDIManagerLoadException{
673
                // now insert the skin selected.
674
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
675
                // MDIManagerFactory.setSkinExtension(se,
676
                // ps.getClassLoader());
677

    
678
                Class skinClass;
679

    
680
                try {
681
                        skinClass = pluginClassLoader.loadClass(
682
                                        skinExtension.getClassName());
683

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

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

    
730
                SkinExtension skinExtension = null;
731
                PluginClassLoader pluginClassLoader = null;
732
                ArrayList skinExtensions = new ArrayList();
733
                while (i.hasNext()) {
734
                        String name = (String) i.next();
735
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
736
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
737

    
738
                        if (pc.getExtensions().getSkinExtension() != null) {
739
//                                if (MDIManagerFactory.getSkinExtension() != null) {
740
//                                        logger.warn(Messages.getString(
741
//                                                        "Launcher.Dos_skin_extension"));
742
//                                }
743

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

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

    
776
        }
777

    
778
        private static void frameIcon(Theme theme) {
779
                Iterator i = pluginsConfig.keySet().iterator();
780

    
781
                while (i.hasNext()) {
782
                        String pName = (String) i.next();
783
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
784
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
785
                        if (pc.getIcon() != null) {
786
                                if (theme.getIcon() != null) {
787
                                        frame.setIconImage(theme.getIcon().getImage());
788
                                } else {
789

    
790
                                        ImageIcon icon = PluginServices.getIconTheme().get(pc.getIcon().getSrc());
791
                                        frame.setIconImage(icon.getImage());
792

    
793
                                }
794
                                if (theme.getName() != null) {
795
                                        frame.setTitlePrefix(theme.getName());
796
                                } else {
797
                                        frame.setTitlePrefix(pc.getIcon().getText());
798
                                }
799
                                if (theme.getBackgroundImage() != null) {
800

    
801
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
802
                                }
803
                        }
804
                }
805
        }
806

    
807
        private static void initializeExtensions() {
808
                Iterator i = pluginsOrdered.iterator();
809

    
810
                while (i.hasNext()) {
811
                        String pName = (String) i.next();
812
            logger.debug("Initializing extensions from " + pName);
813
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
814
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
815

    
816
                        Extension[] exts = pc.getExtensions().getExtension();
817

    
818
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
819

    
820
                        for (int j = 0; j < exts.length; j++) {
821
                                if (!exts[j].getActive()) {
822
                                        continue;
823
                                }
824

    
825
                                if (orderedExtensions.containsKey(exts[j])) {
826
                                        logger.warn(Messages.getString(
827
                                                        "Launcher.Two_extensions_with_the_same_priority") +
828
                                                exts[j].getClassName());
829
                                }
830

    
831
                                orderedExtensions.put(exts[j], null);
832
                        }
833

    
834
                        Iterator e = orderedExtensions.keySet().iterator();
835

    
836
                        while (e.hasNext()) {
837
                                Extension extension = (Extension) e.next();
838
                                com.iver.andami.plugins.IExtension extensionInstance;
839

    
840
                                try {
841
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
842
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
843

    
844
                                        // CON DECORATOR
845
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
846
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
847
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
848
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
849
                                        // la extensi?n original que acabamos de crear
850
                                        // 0-> Inactivo, controla la extension
851
                                        // 1-> Siempre visible
852
                                        // 2-> Invisible
853
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
854
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
855
                                        logger.info("Initializing " + extension.getClassName()+"...");
856
                    // logger.debug("Initializing " + extension.getClassName());
857
                    extensionInstance.initialize();
858
                    extensions.add(extensionInstance);
859
                    // logger.debug(extension.getClassName() + " initialized.");
860

    
861
                                } catch (InstantiationException e1) {
862
                                        logger.error(Messages.getString(
863
                                                        "Launcher.Error_instanciando_la_extension") +
864
                                                extension.getClassName(), e1);
865
                                } catch (IllegalAccessException e1) {
866
                                        logger.error(Messages.getString(
867
                                                        "Launcher.Error_instanciando_la_extension") +
868
                                                extension.getClassName(), e1);
869
                                } catch (ClassNotFoundException e1) {
870
                                        logger.error(Messages.getString(
871
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
872
                                                extension.getClassName(), e1);
873
                                } catch (NoClassDefFoundError e1) {
874
                                        logger.error(Messages.getString(
875
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
876
                                                extension.getClassName(), e1);
877
                                }
878
                        }
879
                }
880
        }
881

    
882
        private static void postInitializeExtensions() {
883
                for (int i=0;i<extensions.size();i++) {
884
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
885
                        extensionInstance.postInitialize();
886
                }
887
        }
888

    
889
        private static void installPluginsMenus() {
890
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
891

    
892
                Iterator i = pluginsConfig.keySet().iterator();
893

    
894
                while (i.hasNext()) {
895
                        String pName = (String) i.next();
896
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
897
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
898

    
899
                        Extension[] exts = pc.getExtensions().getExtension();
900

    
901
                        for (int j = 0; j < exts.length; j++) {
902
                                if (!exts[j].getActive()) {
903
                                        continue;
904
                                }
905

    
906
                                Menu[] menus = exts[j].getMenu();
907

    
908
                                for (int k = 0; k < menus.length; k++) {
909
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
910
                                                        exts[j], menus[k]);
911

    
912
                                        if (orderedMenus.containsKey(sm)) {
913
                                                logger.error(Messages.getString(
914
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
915
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
916
                                        }
917

    
918
                                        orderedMenus.put(sm, null);
919
                                }
920
                        }
921

    
922
                        // Se instalan las extensiones de MDI
923
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
924
                        for (int j = 0; j < skinExts.length; j++) {
925

    
926

    
927
                        if (skinExts[j] != null) {
928
                                Menu[] menu = skinExts[j].getMenu();
929

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

    
934
                                        if (orderedMenus.containsKey(sm)) {
935
                                                logger.error(Messages.getString(
936
                                                                "Launcher.Two_menus_with_the_same_position") +
937
                                                        skinExts[j].getClassName());
938
                                        }
939

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

    
946
                //Se itera por los menus ordenados
947
                Iterator e = orderedMenus.keySet().iterator();
948

    
949
                // Se ordenan los menues
950
                while (e.hasNext()) {
951
                        try {
952
                                SortableMenu sm = (SortableMenu) e.next();
953

    
954
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
955
                        } catch (ClassNotFoundException ex) {
956
                                logger.error(Messages.getString(
957
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
958
                        }
959
                }
960
        }
961

    
962
        /**
963
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
964
         * The order in which they are shown is determined here.
965
         */
966
        private static void installPluginsControls() {
967
                Iterator i = pluginsConfig.keySet().iterator();
968

    
969
                HashMap extensionPluginServices = new HashMap();
970
                HashMap extensionPluginConfig = new HashMap();
971
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
972

    
973
                // First of all, sort the extensions.
974
                // We need to iterate on the plugins, and iterate on each plugin's extensions
975
                // (each plugin may contain one or more extensions)
976
                while (i.hasNext()) { // iterate on the plugins
977
                        String pName = (String) i.next();
978
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
979
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
980

    
981
                        Extension[] exts = pc.getExtensions().getExtension();
982

    
983
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
984
                                if (exts[j].getActive()) {
985
                                        if (orderedExtensions.containsKey(exts[j])) {
986
                                                logger.error(Messages.getString(
987
                                                "Launcher.Two_extensions_with_the_same_priority") +
988
                                                exts[j].getClassName());
989
                                        }
990

    
991
                                        orderedExtensions.put(exts[j], null);
992
                                        extensionPluginServices.put(exts[j], ps);
993
                                        extensionPluginConfig.put(exts[j], pc);
994
                                }
995
                        }
996
                }
997

    
998
                TreeMap orderedTools = new TreeMap(new ToolComparator());
999
                Iterator e = orderedExtensions.keySet().iterator();
1000

    
1001
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
1002
                // and load the  combo-scales and combo-buttons for the status bar
1003
                while (e.hasNext()) {
1004
                        Extension ext = (Extension) e.next();
1005

    
1006
                        ToolBar[] toolbars = ext.getToolBar();
1007

    
1008
                        // get tools from toolbars
1009
                        for (int k = 0; k < toolbars.length; k++) {
1010
                                ActionTool[] tools = toolbars[k].getActionTool();
1011

    
1012
                                for (int t = 0; t < tools.length; t++) {
1013
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1014
                                                        toolbars[k], tools[t]);
1015
                                        orderedTools.put(sm, null);
1016
                                }
1017

    
1018
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
1019

    
1020
                                for (int t = 0; t < sTools.length; t++) {
1021
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1022
                                                        toolbars[k], sTools[t]);
1023
                                        orderedTools.put(sm, null);
1024
                                }
1025
                        }
1026

    
1027
                        // get controls for statusBar
1028
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
1029
                        PluginClassLoader loader = ps.getClassLoader();
1030

    
1031
                        //ArrayList componentList = new ArrayList();
1032
                        ComboScale[] comboScaleArray = ext.getComboScale();
1033
                        for (int k=0; k < comboScaleArray.length; k++) {
1034
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1035
                                String label = comboScaleArray[k].getLabel();
1036
                                if (label!=null)
1037
                                        combo.setLabel(label);
1038
                                String name = comboScaleArray[k].getName();
1039
                                if (name!=null)
1040
                                        combo.setName(name);
1041
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
1042
                                long[] elements = new long[elementsString.length];
1043
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
1044
                                        try {
1045
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
1046
                                        }
1047
                                        catch (NumberFormatException nfex1) {
1048
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
1049
                                                elements[currentElem] = 0;
1050
                                        }
1051
                                }
1052
                                combo.setItems(elements);
1053
                                try {
1054
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
1055
                                        combo.setScale(value);
1056
                                }
1057
                                catch (NumberFormatException nfex2) {
1058
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
1059
                                }
1060
                                try {
1061
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
1062
                                } catch (ClassNotFoundException e1) {
1063
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1064
                                }
1065
                        }
1066

    
1067
                        ComboButton[] comboButtonArray = ext.getComboButton();
1068
                        for (int k=0; k < comboButtonArray.length; k++) {
1069
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
1070
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1071
                                String name = comboButtonArray[k].getName();
1072
                                if (name!=null)
1073
                                        combo.setName(name);
1074
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
1075
                                        ComboButtonElement element = elementList[currentElement];
1076
                                        ImageIcon icon;
1077
                                        URL iconLocation = loader.getResource(element.getIcon());
1078
                                        if (iconLocation==null)
1079
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
1080
                                        else {
1081
                                                icon = new ImageIcon(iconLocation);
1082
                                                JButton button = new JButton(icon);
1083
                                                combo.addButton(button);
1084
                                                button.setActionCommand(element.getActionCommand());
1085
                                        }
1086
                                }
1087
                                try {
1088
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
1089
                                } catch (ClassNotFoundException e1) {
1090
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1091
                                }
1092
                        }
1093
                }
1094

    
1095
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
1096
                i = pluginsConfig.keySet().iterator();
1097
                while (i.hasNext()) {
1098
                        String pName = (String) i.next();
1099
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1100
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1101

    
1102
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
1103
                        for (int j = 0; j < skinExts.length; j++) {
1104

    
1105

    
1106
                        if (skinExts[j] != null) {
1107
                                ToolBar[] toolbars = skinExts[j].getToolBar();
1108

    
1109
                                for (int k = 0; k < toolbars.length; k++) {
1110
                                        ActionTool[] tools = toolbars[k].getActionTool();
1111

    
1112
                                        for (int t = 0; t < tools.length; t++) {
1113
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1114
                                                                toolbars[k], tools[t]);
1115
                                                orderedTools.put(stb,null);
1116
                                        }
1117

    
1118
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1119

    
1120
                                        for (int t = 0; t < sTools.length; t++) {
1121
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1122
                                                                toolbars[k], sTools[t]);
1123
                                                orderedTools.put(stb,null);
1124
                                        }
1125
                                }
1126
                        }
1127
                        }
1128
                        // Install popup menus
1129
                        PopupMenus pus = pc.getPopupMenus();
1130

    
1131
                        if (pus != null) {
1132
                                PopupMenu[] menus = pus.getPopupMenu();
1133

    
1134
                                for (int j = 0; j < menus.length; j++) {
1135
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1136
                                }
1137
                        }
1138
                }
1139

    
1140
                // loop on the ordered extension list, to add them to the interface in an ordered way
1141
                Iterator t = orderedTools.keySet().iterator();
1142
                while (t.hasNext()) {
1143
                        try {
1144
                                SortableTool stb = (SortableTool) t.next();
1145
                                if (stb.actiontool!=null)
1146
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
1147
                                else
1148
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
1149
                        } catch (ClassNotFoundException ex) {
1150
                                logger.error(Messages.getString(
1151
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
1152
                        }
1153
                }
1154
        }
1155

    
1156
        /**
1157
         * Adds new plugins to the the andami-config file.
1158
         */
1159
        private static void updateAndamiConfig() {
1160
                HashSet olds = new HashSet();
1161

    
1162
                Plugin[] plugins = andamiConfig.getPlugin();
1163

    
1164
                for (int i = 0; i < plugins.length; i++) {
1165
                        olds.add(plugins[i].getName());
1166
                }
1167

    
1168
                Iterator i = pluginsServices.values().iterator();
1169

    
1170
                while (i.hasNext()) {
1171
                        PluginServices ps = (PluginServices) i.next();
1172

    
1173
                        if (!olds.contains(ps.getPluginName())) {
1174
                                Plugin p = new Plugin();
1175
                                p.setName(ps.getPluginName());
1176
                                p.setUpdate(false);
1177

    
1178
                                andamiConfig.addPlugin(p);
1179
                        }
1180
                }
1181
        }
1182

    
1183
        private static void pluginsClassLoaders() {
1184
                HashSet instalados = new HashSet();
1185

    
1186
                // Se itera hasta que est?n todos instalados
1187
                while (instalados.size() != pluginsConfig.size()) {
1188
                        boolean circle = true;
1189

    
1190
                        //Hacemos una pasada por todos los plugins
1191
                        Iterator i = pluginsConfig.keySet().iterator();
1192

    
1193
                        while (i.hasNext()) {
1194
                                String pluginName = (String) i.next();
1195
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1196

    
1197
                                if (instalados.contains(pluginName)) {
1198
                                        continue;
1199
                                }
1200

    
1201
                                //Se obtienen las dependencias y sus class loaders
1202
                                boolean ready = true;
1203
                                Depends[] dependencies = config.getDepends();
1204
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1205

    
1206
                                for (int j = 0; j < dependencies.length; j++) {
1207
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1208
                                                logger.error(Messages.getString(
1209
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1210
                                                        pluginName + ": " +
1211
                                                        dependencies[j].getPluginName());
1212

    
1213
                                                continue;
1214
                                        }
1215

    
1216
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1217
                                                ready = false;
1218
                                        } else {
1219
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1220
                                        }
1221
                                }
1222

    
1223
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1224
                                if (!ready) {
1225
                                        continue;
1226
                                }
1227

    
1228
                                //Se genera el class loader
1229
                                String jardir = config.getLibraries().getLibraryDir();
1230
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1231
                                                File.separator + pluginName + File.separator + jardir);
1232
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1233
                                                        public boolean accept(File pathname) {
1234
                                                                return (pathname.getName().toUpperCase()
1235
                                                                                                .endsWith(".JAR")) ||
1236
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1237
                                                        }
1238
                                                });
1239

    
1240
                                URL[] urls = new URL[jarFiles.length];
1241

    
1242
                                for (int j = 0; j < jarFiles.length; j++) {
1243
                                        try {
1244
                                                urls[j] = new URL("file:" + jarFiles[j]);
1245
                                        } catch (MalformedURLException e) {
1246
                                                logger.error(Messages.getString(
1247
                                                                "Launcher.No_se_puede_acceder_a") +
1248
                                                        jarFiles[j]);
1249
                                        }
1250
                                }
1251

    
1252
                                PluginClassLoader loader;
1253

    
1254
                                try {
1255
                                        loader = new PluginClassLoader(urls,
1256
                                                        andamiConfig.getPluginsDirectory() +
1257
                                                        File.separator + pluginName,
1258
                                                        Launcher.class.getClassLoader(), loaders);
1259

    
1260
                                        PluginServices ps = new PluginServices(loader);
1261

    
1262
                                        pluginsServices.put(ps.getPluginName(), ps);
1263

    
1264
                                        instalados.add(pluginName);
1265
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1266
                    // inicializar los plugins
1267
                    pluginsOrdered.add(pluginName);
1268

    
1269
                                        circle = false;
1270
                                } catch (IOException e) {
1271
                                        logger.error(Messages.getString(
1272
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1273
                                        pluginsConfig.remove(pluginName);
1274
                                        i = pluginsConfig.keySet().iterator();
1275
                                }
1276
                        }
1277

    
1278
                        if (circle) {
1279
                                logger.error(Messages.getString(
1280
                                                "Launcher.Hay_dependencias_circulares"));
1281

    
1282
                                break;
1283
                        }
1284
                }
1285

    
1286
                //Se eliminan los plugins que no fueron instalados
1287
                Iterator i = pluginsConfig.keySet().iterator();
1288

    
1289
                while (i.hasNext()) {
1290
                        String pluginName = (String) i.next();
1291
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1292
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1293

    
1294
                        if (ps == null) {
1295
                                pluginsConfig.remove(pluginName);
1296
                                i = pluginsConfig.keySet().iterator();
1297
                        }
1298
                }
1299
        }
1300

    
1301
        private static void pluginsMessages() {
1302
                Iterator iterator = pluginsOrdered.iterator();
1303
                PluginConfig config;
1304
                PluginServices ps;
1305

    
1306
                while (iterator.hasNext()) {
1307
                        String pluginName = (String) iterator.next();
1308
                        config = (PluginConfig) pluginsConfig.get(pluginName);
1309
                        ps = (PluginServices) pluginsServices.get(pluginName);
1310

    
1311
                        if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1312
                                // add the locale files associated with the plugin
1313
                                org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1314
                        }
1315
                }
1316
        }
1317

    
1318
        static PluginServices getPluginServices(String name) {
1319
                return (PluginServices) pluginsServices.get(name);
1320
        }
1321

    
1322
        static String getPluginsDir() {
1323
                return andamiConfig.getPluginsDirectory();
1324
        }
1325

    
1326
        static void setPluginsDir(String s) {
1327
                andamiConfig.setPluginsDirectory(s);
1328
        }
1329

    
1330
        static MDIFrame getMDIFrame() {
1331
                return frame;
1332
        }
1333

    
1334
        private static void loadPlugins(String pluginsDirectory) {
1335
                File pDir = new File(pluginsDirectory);
1336

    
1337
                if (!pDir.exists()) {
1338
                        logger.error("\n\tPlugins directory not found: "+pDir.getAbsolutePath()+"\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1339
                        System.exit(-1);
1340
                        return;
1341
                }
1342

    
1343
                File[] pluginDirs = pDir.listFiles();
1344
                if (pluginDirs.length==0) {
1345
                        logger.error("\n\tPlugins directory is empty: "+pDir.getAbsolutePath()+"Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1346
                        System.exit(-1);
1347
                        return;
1348
                }
1349

    
1350
                for (int i = 0; i < pluginDirs.length; i++) {
1351
                        if (pluginDirs[i].isDirectory()) {
1352
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1353
                                                File.separator + "config.xml");
1354

    
1355
                                try {
1356
                                        FileInputStream is = new FileInputStream(configXml);
1357
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1358
                                        if (xml==null) {
1359
                                                // the encoding was not correctly detected, use system default
1360
                                                xml = new FileReader(configXml);
1361
                                        }
1362
                                        else {
1363
                                                // use a buffered reader to improve performance
1364
                                                xml = new BufferedReader(xml);
1365
                                        }
1366
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1367
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1368
                                } catch (FileNotFoundException e) {
1369
                                        logger.info(Messages.getString(
1370
                                                        "Launcher.Ignorando_el_directorio") +
1371
                                                pluginDirs[i].getAbsolutePath() +
1372
                                                Messages.getString("Launcher.config_no_encontrado"));
1373
                                } catch (MarshalException e) {
1374
                                        logger.info(Messages.getString(
1375
                                                        "Launcher.Ignorando_el_directorio") +
1376
                                                pluginDirs[i].getAbsolutePath() +
1377
                                                Messages.getString("Launcher.config_mal_formado"), e);
1378
                                } catch (ValidationException e) {
1379
                                        logger.info(Messages.getString(
1380
                                                        "Launcher.Ignorando_el_directorio") +
1381
                                                pluginDirs[i].getAbsolutePath() +
1382
                                                Messages.getString("Launcher.config_mal_formado"), e);
1383
                                }
1384
                        }
1385
                }
1386

    
1387
                if (pluginsConfig.size()==0) {
1388
                        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...");
1389
                        System.exit(-1);
1390
                        return;
1391
                }
1392
        }
1393

    
1394
        private static Locale getLocale(String language, String country,
1395
                String variant) {
1396
                if (variant != null) {
1397
                        return new Locale(language, country, variant);
1398
                } else if (country != null) {
1399
                        return new Locale(language, country);
1400
                } else if (language != null) {
1401
                        return new Locale(language);
1402
                } else {
1403
                        return new Locale("es");
1404
                }
1405
        }
1406

    
1407
        private static void andamiConfigToXML(String file)
1408
                throws IOException, MarshalException, ValidationException {
1409
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1410
                File tmpFile = new File(file+"-"+DateTime.getCurrentDate().getTime());
1411
                File xml = new File(file);
1412
                File parent = xml.getParentFile();
1413
                parent.mkdirs();
1414

    
1415
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile));
1416
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
1417
                andamiConfig.marshal(writer);
1418
                writer.close();
1419

    
1420
                // if marshaling process finished correctly, move the file to the correct one
1421
                xml.delete();
1422
                if (!tmpFile.renameTo(xml)) {
1423
                        // if rename was not succesful, try copying it
1424
                        FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1425
                        FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1426
                        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1427
                        sourceChannel.close();
1428
                        destinationChannel.close();
1429
                }
1430
        }
1431

    
1432
        private static void andamiConfigFromXML(String file)
1433
                throws ConfigurationException {
1434
                File xml = new File(file);
1435

    
1436
                InputStreamReader reader = null;
1437
                try {
1438
                        //Se lee la configuraci?n
1439
                        reader = XMLEncodingUtils.getReader(xml);
1440
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1441
                } catch (FileNotFoundException e) {
1442
                        //Si no existe se ponen los valores por defecto
1443
                        andamiConfig = getDefaultAndamiConfig();
1444
                } catch (MarshalException e) {
1445
                        // try to close the stream, maybe it remains open
1446
                        if (reader!=null) {
1447
                                try { reader.close(); } catch (IOException e1) {}
1448
                        }
1449
                        // if there was a problem reading the file, backup it and create a new one with default values
1450
                        String backupFile = file+"-"+DateTime.getCurrentDate().getTime();
1451
                        NotificationManager.addError(Messages.getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1452
                        xml.renameTo(new File(backupFile));
1453
                        andamiConfig = getDefaultAndamiConfig();
1454
                } catch (ValidationException e) {
1455
                        throw new ConfigurationException(e);
1456
                }
1457
        }
1458

    
1459
        private static AndamiConfig getDefaultAndamiConfig() {
1460
                AndamiConfig andamiConfig = new AndamiConfig();
1461

    
1462
                Andami andami = new Andami();
1463
                andami.setUpdate(true);
1464
                andamiConfig.setAndami(andami);
1465
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1466
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1467
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1468

    
1469
                if (System.getProperty("javawebstart.version") != null) // Es java web start)
1470
                 {
1471
                        andamiConfig.setPluginsDirectory(new File(appHomeDir
1472
                                        + "extensiones").getAbsolutePath());
1473
                } else {
1474
                        andamiConfig.setPluginsDirectory(new File(appName +
1475
                                        File.separator + "extensiones").getAbsolutePath());
1476
                }
1477

    
1478
                andamiConfig.setPlugin(new Plugin[0]);
1479
                return andamiConfig;
1480
        }
1481

    
1482
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1483
                File xml = new File(pluginsPersistencePath);
1484

    
1485
                if (xml.exists()) {
1486
                        InputStreamReader reader = null;
1487

    
1488
                        try {
1489
                                reader = XMLEncodingUtils.getReader(xml);
1490
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1491
                                return new XMLEntity(tag);
1492
                        } catch (FileNotFoundException e) {
1493
                                throw new ConfigurationException(e);
1494
                        } catch (MarshalException e) {
1495

    
1496
                                // try to reopen with default encoding (for backward compatibility)
1497
                                try {
1498
                                        reader = new FileReader(xml);
1499
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1500
                                        return new XMLEntity(tag);
1501

    
1502
                                } catch (MarshalException ex) {
1503
                                        // try to close the stream, maybe it remains open
1504
                                        if (reader!=null) {
1505
                                                try { reader.close(); } catch (IOException e1) {}
1506
                                        }
1507
                                        // backup the old file
1508
                                        String backupFile = pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime();
1509
                                        NotificationManager.addError(Messages.getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1510
                                        xml.renameTo(new File(backupFile));
1511
                                        // create a new, empty configuration
1512
                                        return new XMLEntity();
1513
                                }
1514
                                catch (FileNotFoundException ex) {
1515
                                        return new XMLEntity();
1516
                                } catch (ValidationException ex) {
1517
                                        throw new ConfigurationException(e);
1518
                                }
1519
                        } catch (ValidationException e) {
1520
                                throw new ConfigurationException(e);
1521
                        }
1522
                } else {
1523
                        return new XMLEntity();
1524
                }
1525
        }
1526

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

    
1532
                File xml = new File(pluginsPersistencePath);
1533
                OutputStreamWriter writer = null;
1534

    
1535
                try {
1536
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile), CASTORENCODING);
1537
                        entity.getXmlTag().marshal(writer);
1538
                        writer.close();
1539

    
1540
                        // if marshaling process finished correctly, move the file to the correct one
1541
                        xml.delete();
1542
                        if (!tmpFile.renameTo(xml)) {
1543
                                // if rename was not succesful, try copying it
1544
                                FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1545
                                FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1546
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1547
                                sourceChannel.close();
1548
                                destinationChannel.close();
1549

    
1550
                        }
1551
                } catch (FileNotFoundException e) {
1552
                        throw new ConfigurationException(e);
1553
                } catch (MarshalException e) {
1554
                        // try to close the stream, maybe it remains open
1555
                        if (writer!=null) {
1556
                                try { writer.close(); } catch (IOException e1) {}
1557
                        }
1558
                } catch (ValidationException e) {
1559
                        throw new ConfigurationException(e);
1560
                } catch (IOException e) {
1561
                        throw new ConfigurationException(e);
1562
                }
1563
        }
1564

    
1565
        static MDIFrame getFrame() {
1566
                return frame;
1567
        }
1568

    
1569
        /**
1570
         * Gracefully closes the application. It shows dialogs to save data,
1571
         * finish processes, etc, then it terminates the extensions, removes
1572
         * temporal files and finally exits.
1573
         */
1574
        public synchronized static void closeApplication() {
1575
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
1576
                terminationProcess.run();
1577
        }
1578

    
1579
        static HashMap getClassesExtensions() {
1580
                return classesExtensions;
1581
        }
1582

    
1583
        private static void downloadExtensions(String extDir) {
1584
                java.util.Date fechaActual = null;
1585

    
1586
                try {
1587
                        if (System.getProperty("javawebstart.version") != null) {
1588
                                //Obtenemos la URL del servidor
1589
                                BasicService bs = (BasicService) ServiceManager.lookup(
1590
                                                "javax.jnlp.BasicService");
1591
                                URL baseURL = bs.getCodeBase();
1592

    
1593
                                //Se descargan las extensiones
1594
                                splashWindow.process(5,
1595
                                        "Descargando las extensiones desde " + baseURL + " a " +
1596
                                        extDir);
1597

    
1598
                                URL url = new URL(baseURL + "extensiones.zip");
1599
                                URLConnection connection = url.openConnection();
1600

    
1601
                                System.out.println(url.toExternalForm() + ":");
1602
                                System.out.println("  Content Type: " +
1603
                                        connection.getContentType());
1604
                                System.out.println("  Content Length: " +
1605
                                        connection.getContentLength());
1606
                                System.out.println("  Last Modified: " +
1607
                                        new Date(connection.getLastModified()));
1608
                                System.out.println("  Expiration: " +
1609
                                        connection.getExpiration());
1610
                                System.out.println("  Content Encoding: " +
1611
                                        connection.getContentEncoding());
1612

    
1613
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1614
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1615
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1616
                                // nos bajamos nada.
1617
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1618

    
1619
                                File destDir = new File(extDir);
1620

    
1621
                                if (!destDir.exists()) {
1622
                                        // Creamos gvSIG
1623
                                        destDir.getParentFile().mkdir();
1624

    
1625
                                        if (!destDir.mkdir()) {
1626
                                                System.err.println("Imposible crear el directorio " +
1627
                                                        destDir.getAbsolutePath());
1628
                                        }
1629
                                }
1630

    
1631
                                File timeFile = new File(destDir.getParent() + File.separator +
1632
                                                "timeStamp.properties");
1633

    
1634
                                if (!timeFile.exists()) {
1635
                                        timeFile.createNewFile();
1636
                                }
1637

    
1638
                                FileInputStream inAux = new FileInputStream(timeFile);
1639
                                Properties prop = new Properties();
1640
                                prop.load(inAux);
1641
                                inAux.close();
1642

    
1643
                                if (prop.getProperty("timestamp") != null) {
1644
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1645
                                                                "timestamp"));
1646

    
1647
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1648
                                                System.out.println("No hay nueva actualizaci?n");
1649
                        logger.debug("No hay nueva actualizaci?n -> Return");
1650
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1651
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1652

    
1653
                                                return;
1654
                                        }
1655

    
1656
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1657
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1658
                                } else {
1659
                                        System.out.println("El timeStamp no est? escrito en " +
1660
                                                timeFile.getAbsolutePath());
1661
                                }
1662

    
1663
                                InputStream stream = url.openStream();
1664
                File temp = File.createTempFile("gvsig", ".zip");
1665

    
1666
                logger.debug(temp.getAbsolutePath());
1667

    
1668
                temp.deleteOnExit();
1669
                FileOutputStream file = new FileOutputStream(temp);
1670

    
1671
                byte[] lt_read = new byte[1];
1672

    
1673
                while (stream.read(lt_read) > 0)
1674
                  file.write(lt_read);
1675

    
1676
                                stream.close();
1677
                stream = null;
1678
                file.close();
1679
                file = null;
1680

    
1681
                System.gc();
1682

    
1683
                logger.debug("Ha creado el fichero ZIP");
1684
                                //Se extrae el zip
1685
                splashWindow.process(5, "Extensiones descargadas.");
1686

    
1687
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1688

    
1689
                                Date fechaDir = new Date(destDir.lastModified());
1690
                                System.out.println("Fecha del directorio " + extDir + " = " +
1691
                                        fechaDir.toString());
1692
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1693

    
1694
                                // Si todo ha ido bien, guardamos el timestamp.
1695
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1696
                                // XMLEntity xml=ps.getPersistentXML();
1697
                                fechaActual = new java.util.Date();
1698

    
1699
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1700
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1701
                                prop.store(outAux, "last download");
1702
                                outAux.close();
1703
                                System.out.println("Fecha actual guardada: " +
1704
                                        fechaActual.toGMTString());
1705

    
1706
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1707
                                   ps.setPresistentXML(xml); */
1708
                        }
1709
                } catch (IOException e) {
1710
                        NotificationManager.addError("", e);
1711
                } catch (UnavailableServiceException e) {
1712
                        NotificationManager.addError("", e);
1713
                } catch (SecurityException e) {
1714
                        System.err.println("No se puede escribir el timeStamp " +
1715
                                fechaActual.toGMTString());
1716
                        NotificationManager.addError("", e);
1717
                }
1718
        }
1719

    
1720
        private static Extensions[] getExtensions() {
1721
                ArrayList array = new ArrayList();
1722
                Iterator iter = pluginsConfig.values().iterator();
1723

    
1724
                while (iter.hasNext()) {
1725
                        array.add(((PluginConfig) iter.next()).getExtensions());
1726
                }
1727

    
1728
                return (Extensions[]) array.toArray(new Extensions[0]);
1729
        }
1730

    
1731
        public static Iterator getExtensionIterator() {
1732
                return extensions.iterator();
1733
        }
1734

    
1735
        public static HashMap getPluginConfig() {
1736
                return pluginsConfig;
1737
        }
1738

    
1739
        public static Extension getExtension(String s) {
1740
                Extensions[] exts = getExtensions();
1741

    
1742
                for (int i = 0; i < exts.length; i++) {
1743
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1744
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1745
                                        return exts[i].getExtension(j);
1746
                                }
1747
                        }
1748
                }
1749

    
1750
                return null;
1751
        }
1752

    
1753
        public static AndamiConfig getAndamiConfig() {
1754
                return andamiConfig;
1755
        }
1756

    
1757
        private static class ExtensionComparator implements Comparator {
1758
                public int compare(Object o1, Object o2) {
1759
                        Extension e1 = (Extension) o1;
1760
                        Extension e2 = (Extension) o2;
1761

    
1762
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1763
                                return -1;
1764
                        }
1765

    
1766
                        if (e1.hasPriority() && !e2.hasPriority()) {
1767
                                return Integer.MIN_VALUE;
1768
                        }
1769

    
1770
                        if (e2.hasPriority() && !e1.hasPriority()) {
1771
                                return Integer.MAX_VALUE;
1772
                        }
1773

    
1774
                        if (e1.getPriority() != e2.getPriority()){
1775
                                return e2.getPriority() - e1.getPriority();
1776
                        }else{
1777
                                return (e2.toString().compareTo(e1.toString()));
1778
                        }
1779
                }
1780
        }
1781

    
1782
        private static class MenuComparator implements Comparator {
1783
                private static ExtensionComparator extComp = new ExtensionComparator();
1784

    
1785
                public int compare(Object o1, Object o2) {
1786
                        SortableMenu e1 = (SortableMenu) o1;
1787
                        SortableMenu e2 = (SortableMenu) o2;
1788

    
1789
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1790
                                if (e1.extension instanceof SkinExtensionType) {
1791
                                        return 1;
1792
                                } else if (e2.extension instanceof SkinExtensionType) {
1793
                                        return -1;
1794
                                } else {
1795
                                        return extComp.compare(e1.extension, e2.extension);
1796
                                }
1797
                        }
1798

    
1799
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1800
                                return Integer.MIN_VALUE;
1801
                        }
1802

    
1803
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1804
                                return Integer.MAX_VALUE;
1805
                        }
1806
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1807
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1808
                                return e1.menu.getPosition() - e2.menu.getPosition();
1809
                        }else{
1810
                                return (e1.toString().compareTo(e2.toString()));
1811
                        }
1812
                }
1813
        }
1814

    
1815
        private static class SortableMenu {
1816
                public PluginClassLoader loader;
1817
                public Menu menu;
1818
                public SkinExtensionType extension;
1819

    
1820
                public SortableMenu(PluginClassLoader loader,
1821
                        SkinExtensionType skinExt, Menu menu2) {
1822
                        extension = skinExt;
1823
                        menu = menu2;
1824
                        this.loader = loader;
1825
                }
1826
        }
1827

    
1828
        private static class SortableTool {
1829
                public PluginClassLoader loader;
1830
                public ToolBar toolbar;
1831
                public ActionTool actiontool;
1832
                public SelectableTool selectabletool;
1833
                public SkinExtensionType extension;
1834

    
1835
                public SortableTool(PluginClassLoader loader,
1836
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1837
                        extension = skinExt;
1838
                        toolbar = toolbar2;
1839
                        actiontool=actiontool2;
1840
                        this.loader = loader;
1841
                }
1842
                public SortableTool(PluginClassLoader loader,
1843
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1844
                        extension = skinExt;
1845
                        toolbar = toolbar2;
1846
                        selectabletool=selectabletool2;
1847
                        this.loader = loader;
1848
                }
1849
        }
1850

    
1851
        private static class ToolBarComparator implements Comparator {
1852
                private static ExtensionComparator extComp = new ExtensionComparator();
1853

    
1854
                public int compare(Object o1, Object o2) {
1855
                        SortableTool e1 = (SortableTool) o1;
1856
                        SortableTool e2 = (SortableTool) o2;
1857

    
1858
                        // if the toolbars have the same name, they are considered to be
1859
                        // the same toolbar, so we don't need to do further comparing
1860
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1861
                                return 0;
1862

    
1863
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1864
                                if (e1.extension instanceof SkinExtensionType) {
1865
                                        return 1;
1866
                                } else if (e2.extension instanceof SkinExtensionType) {
1867
                                        return -1;
1868
                                } else {
1869
                                        return extComp.compare(e1.extension, e2.extension);
1870
                                }
1871
                        }
1872

    
1873
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1874
                                return Integer.MIN_VALUE;
1875
                        }
1876

    
1877
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1878
                                return Integer.MAX_VALUE;
1879
                        }
1880
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1881
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1882

    
1883
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1884
                                return 0;
1885
                        }
1886
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1887
                }
1888
        }
1889

    
1890
        /**
1891
         * <p>This class is used to compare tools (selectabletool and actiontool),
1892
         * using the "position"
1893
         * attribute.</p>
1894
         * <p>The ordering criteria are:</p>
1895
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1896
         * order.
1897
         * (using the ToolBarComparator).</li>
1898
         * <li></li>
1899
         * <li>If any of the tools has not 'position' attribute, the tool which
1900
         * <strong>has</strong> the attribute will be placed first.</li>
1901
         * <li>If both tools have the same position (or they don't have a
1902
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1903
         *
1904
         * @author cesar
1905
         * @version $Revision: 28941 $
1906
         */
1907
        private static class ToolComparator implements Comparator {
1908
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1909

    
1910
                public int compare(Object o1, Object o2) {
1911
                        // compare the toolbars which contain the tools
1912
                        int result = toolBarComp.compare(o1, o2);
1913
                        if (result != 0) { // if the toolbars are different, use their order
1914
                                return result;
1915
                        }
1916
                        // otherwise, compare the tools
1917
                        SortableTool e1 = (SortableTool) o1;
1918
                        SortableTool e2 = (SortableTool) o2;
1919
                        int e1Position=-1, e2Position=-1;
1920

    
1921
                        if (e1.actiontool!=null) {
1922
                                if (e1.actiontool.hasPosition())
1923
                                        e1Position = e1.actiontool.getPosition();
1924
                        }
1925
                        else if (e1.selectabletool!=null) {
1926
                                if (e1.selectabletool.hasPosition())
1927
                                        e1Position = e1.selectabletool.getPosition();
1928
                        }
1929

    
1930
                        if (e2.actiontool!=null) {
1931
                                if (e2.actiontool.hasPosition())
1932
                                        e2Position = e2.actiontool.getPosition();
1933
                        }
1934
                        else if (e2.selectabletool!=null){
1935
                                if (e2.selectabletool.hasPosition())
1936
                                        e2Position = e2.selectabletool.getPosition();
1937
                        }
1938

    
1939
                        if (e1Position==-1 && e2Position!=-1) {
1940
                                return 1;
1941
                        }
1942
                        if (e1Position!=-1 && e2Position==-1) {
1943
                                return -1;
1944
                        }
1945
                        if (e1Position!=-1 && e2Position!=-1) {
1946
                                result = e1Position - e2Position;
1947
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1948
                                if (result!=0) return result;
1949
                        }
1950
                        return e1.toString().compareTo(e2.toString());
1951
                }
1952
        }
1953

    
1954

    
1955
        /**
1956
         * validates the user before starting gvsig
1957
         *
1958
         */
1959
        private static void validate(){
1960

    
1961
                IAuthentication session =  null;
1962
                try {
1963
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1964

    
1965
                } catch (ClassNotFoundException e) {
1966
                        return;
1967
                } catch (InstantiationException e) {
1968
                        return;
1969
                } catch (IllegalAccessException e) {
1970
                        return;
1971
                }
1972

    
1973
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1974
                if (session.validationRequired()){
1975
                        if(session.Login()){
1976
                                System.out.println("You are logged in");
1977
                        }
1978
                        else{
1979
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1980
                                                 "You are not logged in");
1981
                                //System.exit(0);
1982
                        }
1983
                        PluginServices.setAuthentication(session);
1984
                }
1985
        }
1986

    
1987
        public static String getDefaultLookAndFeel() {
1988
                String osName = (String) System.getProperty("os.name");
1989

    
1990
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
1991
                        return nonWinDefaultLookAndFeel;
1992
                if (osName.toLowerCase().startsWith("mac os x"))
1993
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
1994

    
1995

    
1996
                return UIManager.getSystemLookAndFeelClassName();
1997
        }
1998

    
1999
        /**
2000
         * Gets the ISO 839 two-characters-long language code matching the
2001
         * provided language code (which may be an ISO 839-2/T
2002
         * three-characters-long code or an ISO 839-1 two-characters-long
2003
         * code).
2004
         *
2005
         * If the provided parameter is already two characters long, it
2006
         * returns the parameter without any modification.
2007
         *
2008
         * @param langCode A language code representing either
2009
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2010
         * @return A two-characters-long code specifying
2011
         *  an ISO 839 language code.
2012
         */
2013
        private static String normalizeLanguageCode(String langCode) {
2014
                final String fileName = "iso_639.tab";
2015
                if (langCode.length()==2)
2016
                        return langCode;
2017
                else if (langCode.length()==3) {
2018
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2019
                                return "ca";
2020
                        }
2021
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2022
                        if (isoCodes!=null) {
2023
                                try {
2024
                                        BufferedReader reader =
2025
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2026
                                                String line;
2027

    
2028
                                                while ((line = reader.readLine()) != null) {
2029
                                                        String[] language = line.split("\t");
2030
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2031
                                                                return language[2]; // third column i the two characters code
2032
                                                }
2033
                                }
2034
                                catch (IOException ex) {
2035
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2036
                                        return "es";
2037
                                }
2038
                        }
2039
                        else {
2040
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2041
                                return "es";
2042
                        }
2043
                }
2044
                return "es";
2045
        }
2046

    
2047
        /**
2048
         * Configures the locales (languages and local resources) to be used
2049
         * by the application.
2050
         *
2051
         * First it tries to get the locale from the command line parameters,
2052
         * then the andami-config file is checked.
2053
         *
2054
         * The locale name is normalized to get a two characters language code
2055
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2056
         * are also accepted from the command line or the configuration file).
2057
         *
2058
         * Finally, the gvsig-i18n library and the default locales for Java and
2059
         * Swing are configured.
2060
         *
2061
         */
2062
        private static void configureLocales(String[] args) {
2063
                //                 Configurar el locale
2064
        String localeStr = null;
2065
        /*
2066
        for (int i=2; i < args.length; i++)
2067
        {
2068
                int index = args[i].indexOf("language=");
2069
                if (index != -1)
2070
                        localeStr = args[i].substring(index+9);
2071
        }
2072
         */
2073
        localeStr = PluginServices.getArgumentByName("language");
2074
                if (localeStr == null)
2075
                {
2076
            localeStr = andamiConfig.getLocaleLanguage();
2077
                }
2078
                localeStr = normalizeLanguageCode(localeStr);
2079
                locale = getLocale(localeStr,
2080
                andamiConfig.getLocaleCountry(),
2081
                andamiConfig.getLocaleVariant());
2082
                Locale.setDefault(locale);
2083
                JComponent.setDefaultLocale(locale);
2084
        org.gvsig.i18n.Messages.addLocale(locale);
2085
                // add english and spanish as fallback languages
2086
        if (localeStr.equals("es")||localeStr.equals("ca")||localeStr.equals("gl")||localeStr.equals("eu")||localeStr.equals("va")) {
2087
                // prefer Spanish for languages spoken in Spain
2088
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2089
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2090
        }
2091
        else {
2092
                // prefer English for the rest
2093
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2094
                    org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2095
        }
2096
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2097

    
2098
        }
2099

    
2100
        /**
2101
         * Gets Home Directory location of the application.
2102
         * May be set from outside the aplication by means of
2103
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2104
         * of the application
2105
         * @return
2106
         */
2107
        public static String getAppHomeDir() {
2108
                return appHomeDir;
2109
        }
2110

    
2111
        /**
2112
         * Sets Home Directory location of the application.
2113
         * May be set from outside the aplication by means of
2114
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2115
         * of the application
2116
         * @param appHomeDir
2117
         */
2118
        public static void setAppHomeDir(String appHomeDir) {
2119
                Launcher.appHomeDir = appHomeDir;
2120
        }
2121

    
2122
        /**
2123
         * Initialize the extesion that have to take the control
2124
         *  of the state of action controls of the UI of all extensions.
2125
         * <br>
2126
         * <br>
2127
         * For use this option you have to add an argument
2128
         * to the command line like this:
2129
         * <br>
2130
         * <br>
2131
         * -exclusiveUI={pathToExtensionClass}
2132
         * <br>
2133
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
2134
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
2135
         */
2136
        private static void initializeExclusiveUIExtension(){
2137
                String name = PluginServices.getArgumentByName("exclusiveUI");
2138
                if (name == null)
2139
                        return;
2140

    
2141

    
2142
                Iterator iter  = classesExtensions.keySet().iterator();
2143
                int charIndex;
2144
                Class key;
2145
                while (iter.hasNext()) {
2146
                        key = (Class)iter.next();
2147
                        charIndex = key.getName().indexOf(name);
2148
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2149
                        if (charIndex == 0) {
2150
                                IExtension ext =(IExtension)classesExtensions.get(key);
2151
                                if (ext instanceof ExtensionDecorator)
2152
                                        ext = ((ExtensionDecorator)ext).getExtension();
2153
                                if (ext instanceof ExclusiveUIExtension)
2154
                                        PluginServices.setExclusiveUIExtension((ExclusiveUIExtension)ext);
2155
                                break;
2156
                        }
2157
                }
2158

    
2159
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2160
        }
2161

    
2162

    
2163
//        public static void initIconThemes() {
2164
//                // load the iconTheme
2165
//                IconThemeManager iconManager = new IconThemeManager();
2166
//                PluginServices.setIconThemeManager(iconManager);
2167
//                IconThemeInfo selectedTheme = iconManager.readConfig();
2168
//                if (selectedTheme!=null) {
2169
//                        iconManager.setDefault(selectedTheme);
2170
//                        logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2171
//                }
2172
//                else {
2173
//                        // set the default dir and try to load the default theme
2174
//                        try {
2175
//                                iconManager.setThemesDir(new File("iconThemes"));
2176
//                                IconThemeInfo[] list = iconManager.list();
2177
//
2178
//                                for (int i=0; i<list.length; i++) {
2179
//                                        if (list[i].getResourceName().equals("iconThemes/icons")) {
2180
//                                                iconManager.setDefault(list[i]);
2181
//                                                logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2182
//                                                return;
2183
//                                        }
2184
//                                }
2185
//                        } catch (FileNotFoundException e) {
2186
//                                logger.info("IconTheme basedir does not exist");
2187
//                        }
2188
//                        // create an empty theme
2189
//                        IconThemeInfo info = new IconThemeInfo();
2190
//                        info.setName("No theme loaded");
2191
//                        info.setResource(null); // null resource means that no real theme is loaded
2192
//                        info.setDescription("No theme loaded");
2193
//                        info.setVersion("0");
2194
//                        iconManager.setDefault(new IconTheme(info));
2195
//                        logger.info("Setting an empty icon theme");
2196
//
2197
//                }
2198
//        }
2199

    
2200
        public static void initIconThemes(){
2201
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2202
                IIconTheme icontheme= iconManager.getIconThemeFromConfig();
2203
                if (icontheme!=null){
2204
                        iconManager.setCurrent(icontheme);
2205
                }
2206
        }
2207

    
2208
        /**
2209
         * Manages Andami termination process
2210
         *
2211
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2212
         */
2213
        public class TerminationProcess {
2214
                private boolean proceed = false;
2215
                private UnsavedDataPanel panel = null;
2216

    
2217
                public void run() {
2218
                        int exit = manageUnsavedData();
2219
                        if (exit==JOptionPane.NO_OPTION || exit == JOptionPane.CLOSED_OPTION) {
2220
                                // the user doesn't want to exit
2221
                                return;
2222
                        }
2223

    
2224
                        closeAndami();
2225
                }
2226

    
2227
                /**
2228
                 * Finishes the application without asking user if want or not to save unsaved data.
2229
                 */
2230
                public void closeAndami() {
2231
                        //Configuraci?n de Andami
2232
                        try {
2233
                                andamiConfigToXML(andamiConfigPath);
2234
                        } catch (MarshalException e) {
2235
                                logger.error(Messages.getString(
2236
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2237
                        } catch (ValidationException e) {
2238
                                logger.error(Messages.getString(
2239
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2240
                        } catch (IOException e) {
2241
                                logger.error(Messages.getString(
2242
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2243
                        }
2244

    
2245
                        //Persistencia de los plugins
2246
                        savePluginPersistence();
2247

    
2248
                        //Finalize all the extensions
2249
                        finalizeExtensions();
2250

    
2251
                        // Clean any temp data created
2252
                        Utilities.cleanUpTempFiles();
2253

    
2254
                        //Para la depuraci?n de memory leaks
2255
                        System.gc();
2256

    
2257
                        System.exit(0);
2258
                }
2259

    
2260
                /**
2261
                 * Exectutes the terminate method for all the extensions, in the reverse
2262
                 * order they were initialized
2263
                 *
2264
                 */
2265
                private void finalizeExtensions() {
2266
                        for (int i=extensions.size()-1; i>=0; i--) {
2267
                                com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
2268
                                extensionInstance.terminate();
2269
                        }
2270
                }
2271

    
2272

    
2273
                private ArrayList getUnsavedData() {
2274
                        ArrayList unsavedDataList = new ArrayList();
2275
                        IExtension exclusiveExtension=PluginServices.getExclusiveUIExtension();
2276

    
2277
                        for (int i=extensions.size()-1; i>=0; i--) {
2278
                                com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
2279
                                IExtensionStatus status = null;
2280
                                if (exclusiveExtension!=null) {
2281
                                        status = exclusiveExtension.getStatus(extensionInstance);
2282
                                }else {
2283
                                        status = extensionInstance.getStatus();
2284
                                }
2285
                                if (status!=null) {
2286
                                        if (status.hasUnsavedData()) {
2287
                                                IUnsavedData[] array = status.getUnsavedData();
2288
                                                for (int element = 0; element<array.length; element++) {
2289
                                                        unsavedDataList.add(array[element]);
2290
                                                }
2291
                                        }
2292
                                }
2293
                        }
2294
                        return unsavedDataList;
2295
                }
2296

    
2297
                public UnsavedDataPanel getUnsavedDataPanel() {
2298
                        if (panel==null) {
2299
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
2300
                        }
2301
                        return panel;
2302
                }
2303
                /**
2304
                 * Checks if the extensions have some unsaved data, and shows a dialog
2305
                 * to allow saving it. This dialog also allows to don't exit Andami.
2306
                 *
2307
                 * @return true if the user confirmed he wishes to exit, false otherwise
2308
                 */
2309
                public int manageUnsavedData(){
2310
                        ArrayList unsavedDataList = getUnsavedData();
2311

    
2312
                        // there was no unsaved data
2313
                        if (unsavedDataList.size()==0) {
2314
                                int option = JOptionPane.showConfirmDialog(frame,
2315
                                                Messages.getString("MDIFrame.quiere_salir"),
2316
                                                Messages.getString("MDIFrame.salir"),
2317
                                                JOptionPane.YES_NO_OPTION);
2318
                                return option;
2319
                        }
2320

    
2321
                        // it does not work if we directly cast the array
2322
                        IUnsavedData[] unsavedDataArray;
2323
                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2324
                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2325

    
2326
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2327
                        panel.setUnsavedDataArray(unsavedDataArray);
2328

    
2329

    
2330
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2331
                                public void cancel(UnsavedDataPanel panel){
2332
                                        proceed(false);
2333
                                        PluginServices.getMDIManager().closeWindow(panel);
2334

    
2335
                                }
2336

    
2337
                                public void discard(UnsavedDataPanel panel){
2338
                                        proceed(true);
2339
                                        PluginServices.getMDIManager().closeWindow(panel);
2340

    
2341
                                }
2342

    
2343
                                public void accept(UnsavedDataPanel panel){
2344
                                        IUnsavedData[] unsavedDataArray = panel.getSelectedsUnsavedData();
2345
                                        boolean saved;
2346
                                        for (int i=0; i<unsavedDataArray.length; i++) {
2347
                                                try {
2348
                                                        saved = unsavedDataArray[i].saveData();
2349
                                                }
2350
                                                catch (Exception ex) {
2351
                                                        PluginServices.getLogger().error("Error saving"+unsavedDataArray[i].getResourceName() ,ex);
2352
                                                        saved = false;
2353
                                                }
2354
                                                if (!saved) {
2355
                                                        JOptionPane.showMessageDialog(
2356
                                                                        panel,
2357
                                                                        PluginServices.getText(this, "The_following_resource_could_not_be_saved_")+
2358
                                                                        "\n"+unsavedDataArray[i].getResourceName() + " -- "
2359
                                                                        + unsavedDataArray[i].getDescription(),
2360
                                                                        PluginServices.getText(this, "Resource_was_not_saved"),
2361
                                                                        JOptionPane.ERROR_MESSAGE);
2362

    
2363
                                                        ArrayList unsavedDataList = getUnsavedData();
2364
                                                        // it does not work if we directly cast the array
2365
                                                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2366
                                                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2367
                                                        panel.setUnsavedDataArray(unsavedDataArray);
2368
                                                        return;
2369
                                                }
2370
                                        }
2371
                                        proceed(true);
2372
                                        PluginServices.getMDIManager().closeWindow(panel);
2373
                                }
2374
                        });
2375

    
2376
                        PluginServices.getMDIManager().addWindow(panel);
2377
                        if (proceed) {
2378
                                return JOptionPane.YES_OPTION;
2379
                        }
2380
                        else {
2381
                                return JOptionPane.NO_OPTION;
2382
                        }
2383
                }
2384

    
2385
                private void proceed(boolean proceed) {
2386
                        this.proceed = proceed;
2387
                }
2388

    
2389

    
2390
        }
2391

    
2392
        public static TerminationProcess getTerminationProcess() {
2393
                return (new Launcher()).new TerminationProcess();
2394
        }
2395
}