Statistics
| Revision:

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

History | View | Annotate | Download (80.7 KB)

1 15936 jmvivo
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2 1104 fjp
 *
3 13079 cesar
 * Copyright (C) 2004-2007 IVER T.I. and Generalitat Valenciana.
4 1104 fjp
 *
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 14819 jmvivo
 *   Av. Blasco Ib??ez, 50
24 1104 fjp
 *   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 598 fernando
package com.iver.andami;
42
43 36378 nfrancisco
import java.awt.BorderLayout;
44 4306 ldiaz
import java.awt.Component;
45 4299 luisw2
import java.awt.Dimension;
46 1153 fernando
import java.awt.EventQueue;
47 7303 caballero
import java.awt.Frame;
48 5817 fjp
import java.awt.KeyboardFocusManager;
49 4299 luisw2
import java.awt.Point;
50 1153 fernando
import java.awt.Toolkit;
51 13832 cesar
import java.io.BufferedOutputStream;
52 6951 cesar
import java.io.BufferedReader;
53 598 fernando
import java.io.File;
54 1110 fernando
import java.io.FileFilter;
55 2332 fjp
import java.io.FileInputStream;
56 598 fernando
import java.io.FileNotFoundException;
57 2332 fjp
import java.io.FileOutputStream;
58 598 fernando
import java.io.FileReader;
59
import java.io.IOException;
60 2332 fjp
import java.io.InputStream;
61 6951 cesar
import java.io.InputStreamReader;
62 13832 cesar
import java.io.OutputStreamWriter;
63 8752 cesar
import java.io.Reader;
64 8884 fjp
import java.net.Authenticator;
65 598 fernando
import java.net.MalformedURLException;
66 8884 fjp
import java.net.PasswordAuthentication;
67 598 fernando
import java.net.URL;
68 2332 fjp
import java.net.URLConnection;
69 10042 cesar
import java.nio.channels.FileChannel;
70 7514 caballero
import java.security.AllPermission;
71
import java.security.CodeSource;
72
import java.security.PermissionCollection;
73
import java.security.Permissions;
74
import java.security.Policy;
75 598 fernando
import java.util.ArrayList;
76
import java.util.Comparator;
77 2332 fjp
import java.util.Date;
78 598 fernando
import java.util.HashMap;
79
import java.util.HashSet;
80
import java.util.Iterator;
81
import java.util.Locale;
82 2332 fjp
import java.util.Properties;
83 598 fernando
import java.util.TreeMap;
84 8884 fjp
import java.util.prefs.Preferences;
85 598 fernando
86 2332 fjp
import javax.jnlp.BasicService;
87
import javax.jnlp.ServiceManager;
88
import javax.jnlp.UnavailableServiceException;
89 598 fernando
import javax.swing.ImageIcon;
90 6589 cesar
import javax.swing.JButton;
91 598 fernando
import javax.swing.JComponent;
92 36378 nfrancisco
import javax.swing.JFrame;
93 4306 ldiaz
import javax.swing.JOptionPane;
94 9208 jmvivo
import javax.swing.JPopupMenu;
95 598 fernando
import javax.swing.SwingUtilities;
96
import javax.swing.UIManager;
97
98 2112 fernando
import org.apache.log4j.Logger;
99
import org.apache.log4j.PatternLayout;
100
import org.apache.log4j.PropertyConfigurator;
101
import org.apache.log4j.RollingFileAppender;
102
import org.exolab.castor.xml.MarshalException;
103
import org.exolab.castor.xml.ValidationException;
104 36378 nfrancisco
import org.gvsig.installer.swing.api.SwingInstallerLocator;
105
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
106
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
107
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
108
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
109 598 fernando
110 4306 ldiaz
import com.iver.andami.authentication.IAuthentication;
111 14819 jmvivo
import com.iver.andami.authentication.LoginUI;
112 2112 fernando
import com.iver.andami.config.generate.Andami;
113
import com.iver.andami.config.generate.AndamiConfig;
114
import com.iver.andami.config.generate.Plugin;
115 15944 jmvivo
import com.iver.andami.iconthemes.IIconTheme;
116
import com.iver.andami.iconthemes.IconThemeManager;
117 2112 fernando
import com.iver.andami.messages.Messages;
118 2332 fjp
import com.iver.andami.messages.NotificationManager;
119 11910 cesar
import com.iver.andami.plugins.ExclusiveUIExtension;
120 2862 jaume
import com.iver.andami.plugins.ExtensionDecorator;
121 8989 jmvivo
import com.iver.andami.plugins.IExtension;
122 2112 fernando
import com.iver.andami.plugins.PluginClassLoader;
123
import com.iver.andami.plugins.config.generate.ActionTool;
124 6589 cesar
import com.iver.andami.plugins.config.generate.ComboButton;
125
import com.iver.andami.plugins.config.generate.ComboButtonElement;
126
import com.iver.andami.plugins.config.generate.ComboScale;
127 2112 fernando
import com.iver.andami.plugins.config.generate.Depends;
128
import com.iver.andami.plugins.config.generate.Extension;
129
import com.iver.andami.plugins.config.generate.Extensions;
130
import com.iver.andami.plugins.config.generate.LabelSet;
131
import com.iver.andami.plugins.config.generate.Menu;
132
import com.iver.andami.plugins.config.generate.PluginConfig;
133
import com.iver.andami.plugins.config.generate.PopupMenu;
134
import com.iver.andami.plugins.config.generate.PopupMenus;
135
import com.iver.andami.plugins.config.generate.SelectableTool;
136
import com.iver.andami.plugins.config.generate.SkinExtension;
137
import com.iver.andami.plugins.config.generate.SkinExtensionType;
138
import com.iver.andami.plugins.config.generate.ToolBar;
139 12697 cesar
import com.iver.andami.plugins.status.IExtensionStatus;
140
import com.iver.andami.plugins.status.IUnsavedData;
141 2112 fernando
import com.iver.andami.ui.AndamiEventQueue;
142
import com.iver.andami.ui.MDIManagerLoadException;
143 9400 cesar
import com.iver.andami.ui.fonts.FontUtils;
144 2112 fernando
import com.iver.andami.ui.mdiFrame.MDIFrame;
145 14819 jmvivo
import com.iver.andami.ui.mdiFrame.NewStatusBar;
146 2112 fernando
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
147 7303 caballero
import com.iver.andami.ui.splash.MultiSplashWindow;
148 8921 caballero
import com.iver.andami.ui.theme.Theme;
149 12697 cesar
import com.iver.andami.ui.wizard.UnsavedDataPanel;
150 10009 cesar
import com.iver.utiles.DateTime;
151 33213 nbrodin
import com.iver.utiles.FileUtils;
152 2112 fernando
import com.iver.utiles.XMLEntity;
153 13832 cesar
import com.iver.utiles.xml.XMLEncodingUtils;
154 2112 fernando
import com.iver.utiles.xmlEntity.generate.XmlTag;
155
156
157 598 fernando
/**
158 14168 jdominguez
 * <p>
159
 * Andami's launching class. This is the class used to create the Andami's plugin environment.<br>
160
 * </p>
161 14819 jmvivo
 *
162 14168 jdominguez
 * <p>
163
 * <b>Syntax:</b>
164
 * <br>
165 14819 jmvivo
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or semicolon-separated(windows) list of files containg base library of classes}]
166
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
167
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
168 14168 jdominguez
 * [{list of additional custom application arguments separated by spaces}]
169
 * </p>
170 598 fernando
 *
171 14819 jmvivo
 *
172 598 fernando
 * @author $author$
173
 * @version $Revision$
174
 */
175
public class Launcher {
176 1067 fernando
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
177 8884 fjp
        private static Preferences prefs = Preferences.userRoot().node( "gvsig.connection" );
178 1067 fernando
        private static AndamiConfig andamiConfig;
179 7303 caballero
        private static MultiSplashWindow splashWindow;
180 1067 fernando
        private static String appName;
181
        private static Locale locale;
182
        private static HashMap pluginsConfig = new HashMap();
183
        private static HashMap pluginsServices = new HashMap();
184
        private static MDIFrame frame;
185
        private static HashMap classesExtensions = new HashMap();
186
        private static String andamiConfigPath;
187
        private static String pluginsPersistencePath;
188 6101 jaume
        private static final String nonWinDefaultLookAndFeel =  "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
189
190 2828 fjp
    private static ArrayList pluginsOrdered = new ArrayList();
191 7303 caballero
    private static ArrayList extensions=new ArrayList();
192 8120 jmvivo
    private static String appHomeDir = null;
193 13832 cesar
    // it seems castor uses this encoding
194 14819 jmvivo
    private static final String CASTORENCODING = "UTF8";
195 8921 caballero
196 8884 fjp
        private static final class ProxyAuth extends Authenticator {
197
                private PasswordAuthentication auth;
198
199
                private ProxyAuth(String user, String pass) {
200
                        auth = new PasswordAuthentication(user, pass.toCharArray());
201
                }
202
203
                protected PasswordAuthentication getPasswordAuthentication() {
204
                        return auth;
205
                }
206
        }
207
208 36378 nfrancisco
209
        public static void main(String[] args) throws Exception {
210
                boolean install = false;
211
                for (int i = 0; i < args.length; i++) {
212
                        if (args[i].equalsIgnoreCase("--install")) {
213
                                install = true;
214
                        }
215
                }
216
217
            new DefaultLibrariesInitializer().fullInitialize();
218 2142 fernando
219 36378 nfrancisco
                try {
220
                        if (install) {
221
                                doInstall(args);
222
                        } else {
223
                                doMain(args);
224
                        }
225
                } catch (Exception e) {
226
                        logger.error("excepci?n al arrancar", e);
227
                        System.exit(-1);
228
                }
229
        }
230
231
232
        /**
233
     * Launch the gvSIG package installer.
234
     *
235
     * @throws Exception
236
     *             if there is any error
237
     */
238
    private static void doInstall(String[] args) throws Exception {
239
240
        String installURL = null;
241
        if (args.length >= 4) {
242
            String installURLParam = args[3];
243
            if (installURLParam.startsWith("--installURL=")) {
244
                installURL =
245
                    installURLParam.substring("--installURL=".length());
246
            }
247
        }
248 6101 jaume
249 36378 nfrancisco
        if (args.length < 3) {
250
            System.err.println(Messages.get("usage")
251
                + ": Launcher appName plugins-directory "
252
                + "--install [--installURL=[URL]] [language=locale]");
253
        }
254 598 fernando
255 36378 nfrancisco
        initializeApp(args);
256
        AndamiConfig config = getAndamiConfig();
257
        config.setLocaleLanguage(locale.getLanguage());
258
        config.setLocaleCountry(locale.getCountry());
259
        config.setLocaleVariant(locale.getVariant());
260 4607 ldiaz
261 36378 nfrancisco
        // Configure default index download URL
262
        if (installURL != null) {
263
            try {
264
                SwingInstallerLocator.getSwingInstallerManager()
265
                    .setDefaultDownloadURL(new URL(installURL));
266
            } catch (MalformedURLException e) {
267
                logger.error(
268
                    "Error creating the default packages download URL pointing to"
269
                        + installURL, e);
270
            }
271
        }
272 1236 fernando
273 36378 nfrancisco
                // Launch installer
274
                File appFolder = new File(System.getProperty("user.dir"));
275 14819 jmvivo
276 36378 nfrancisco
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
277
                                .getSwingInstallerManager().createInstallPackageWizard(
278
                                                appFolder,
279
                                                new File(Launcher.getAndamiConfig()
280
                                                                .getPluginsDirectory()).getAbsoluteFile(),
281
                                                new File(appFolder, "install"));
282
                installPackageWizard
283
                                .setWizardActionListener(new InstallerWizardActionListener() {
284 33213 nbrodin
285 36378 nfrancisco
                                        public void finish(InstallerWizardPanel installerWizard) {
286
                                                System.exit(0);
287
                                        }
288 598 fernando
289 36378 nfrancisco
                                        public void cancel(InstallerWizardPanel installerWizard) {
290
                                                System.exit(0);
291
                                        }
292
                                });
293
294
        // the wizard will show the Typical or Advanced mode option.
295
        installPackageWizard.setAskTypicalOrCustom(true);
296
        // default packages will be selected.
297
        installPackageWizard.setSelectDefaultPackages(true);
298
299
        // 1. Create the frame.
300
        JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
301 598 fernando
302 36378 nfrancisco
        // 2. What happens when the frame closes?
303
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
304
        Runtime.getRuntime().addShutdownHook(new Thread() {
305 598 fernando
306 36378 nfrancisco
            @Override
307
            public void run() {
308
                getTerminationProcess().saveAndamiConfig();
309
            }
310
        });
311 33214 nbrodin
312 36378 nfrancisco
        // 3. Add the installer panel to the frame
313
        frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
314 598 fernando
315 36378 nfrancisco
        // 4. Size the frame and center on the screen
316
        frame.pack();
317
        frame.setLocationRelativeTo(null);
318 6101 jaume
319 36378 nfrancisco
        // 5. Show it.
320
        frame.setVisible(true);
321
    }
322 598 fernando
323 36378 nfrancisco
    private static void doMain(String[] args) throws Exception {
324
            try{
325 598 fernando
326 36378 nfrancisco
                    if (args.length < 1) {
327
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
328 7303 caballero
                    }
329 6101 jaume
330 36378 nfrancisco
                    initializeApp(args);
331
332 14819 jmvivo
                    // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
333 13793 cesar
                    // System.setSecurityManager(null);
334
                    Policy.setPolicy(new Policy() {
335
                            public PermissionCollection getPermissions(CodeSource codesource) {
336
                                    Permissions perms = new Permissions();
337
                                    perms.add(new AllPermission());
338
                                    return (perms);
339
                            }
340
                            public void
341
                            refresh() {}
342
                    });
343 14819 jmvivo
344 13832 cesar
                    initIconThemes();
345 15716 vcaballero
//                    Registramos los iconos base
346
                    registerIcons();
347 7483 caballero
                    validate();
348 23784 vcaballero
349 15936 jmvivo
                    // Obtener la personalizaci?n de la aplicaci?n.
350 13793 cesar
                    Theme theme=getTheme();
351 14819 jmvivo
352 13793 cesar
                    // Mostrar la ventana de inicio
353 8921 caballero
                    Frame f=new Frame();
354 14168 jdominguez
                    splashWindow=new MultiSplashWindow(f,theme, 190);
355 8884 fjp
356 14168 jdominguez
                    // 1. Ponemos los datos del proxy
357 14819 jmvivo
                    splashWindow.process(10,
358 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.configuring_proxy"));
359 8921 caballero
                    configureProxy();
360 8884 fjp
361 14168 jdominguez
                    // 2. TODO Buscar actualizaciones de los plugins
362 14819 jmvivo
                    splashWindow.process(20,
363 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_updates"));
364 7303 caballero
                    downloadExtensions(andamiConfig.getPluginsDirectory());
365 598 fernando
366 14168 jdominguez
                    // 3. Se leen los config.xml de los plugins -----++++
367 14819 jmvivo
                    splashWindow.process(30,
368 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.reading_plugins_config.xml"));
369 7303 caballero
                    loadPlugins(andamiConfig.getPluginsDirectory());
370 598 fernando
371 14168 jdominguez
                    // 4. Se configura el classloader del plugin
372 14819 jmvivo
                    splashWindow.process(40,
373 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_class_loaders"));
374 7303 caballero
                    pluginsClassLoaders();
375 1153 fernando
376 15936 jmvivo
                    // 5. Se carga un Skin si alguno de los plugins trae informaci?n para ello
377 14819 jmvivo
                    splashWindow.process(50,
378 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
379 17607 vcaballero
//                    skinPlugin(        "com.iver.core.mdiManager.NewSkin");
380
                    skinPlugin(null);
381 598 fernando
382 14168 jdominguez
                    // 6. Se configura la cola de eventos
383 14819 jmvivo
                    splashWindow.process(60,
384 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "setting_up_event_queue"));
385 7303 caballero
                    EventQueue waitQueue = new AndamiEventQueue();
386
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
387 598 fernando
388 15936 jmvivo
                    // 7. Se configura la mensajer?a del plugin
389 14819 jmvivo
                    splashWindow.process(70,
390 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.starting_plugin_internationalization_system"));
391 7303 caballero
                    pluginsMessages();
392 598 fernando
393 14168 jdominguez
                    // 8. Se modifica el andami-config con los plugins nuevos
394 14819 jmvivo
                    splashWindow.process(80,
395 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.looking_for_a_skin"));
396 7303 caballero
                    updateAndamiConfig();
397 598 fernando
398 16285 vcaballero
399
                    frame = new MDIFrame();
400
                    // 9. Se configura el nombre e icono de la aplicaci?n
401 14819 jmvivo
                    splashWindow.process(90,
402 16285 vcaballero
                                    PluginServices.getText(Launcher.class, "SplashWindow.setting_up_applications_name_and_icons"));
403
                    frameIcon(theme);
404
405
                    // 10. Se prepara el MainFrame para albergar las extensiones
406
                    splashWindow.process(100,
407 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.preparing_workbench"));
408 9208 jmvivo
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
409 16285 vcaballero
410 7303 caballero
                    SwingUtilities.invokeAndWait(new Runnable() {
411
                            public void run() {
412
                                    frame.init();
413
                            }
414
                    });
415 1013 fjp
416 14819 jmvivo
417 15716 vcaballero
418 16285 vcaballero
                    // 11. Leer el fichero de persistencia
419 14819 jmvivo
                    //  info de los plugins
420
                    //  bookmarks de los plugins
421 16285 vcaballero
                    splashWindow.process(110,
422 14819 jmvivo
                                    PluginServices.getText(Launcher.class, "SplashWindow.loading_plugin_settings"));
423
                    loadPluginsPersistence();
424
425
426 15633 jmvivo
427 14819 jmvivo
                    // Se instalan los controles del skin
428 16285 vcaballero
                    // 12. Se inicializan todas las extensiones de todos los plugins
429
                    splashWindow.process(120,
430 14819 jmvivo
                                        PluginServices.getText(Launcher.class, "SplashWindow.initializing_extensions"));
431
                    SwingUtilities.invokeAndWait(new Runnable() {
432
                            public void run() {
433
                                    initializeExtensions();
434
                            }
435
                    });
436
437 16285 vcaballero
                    // 13. Se inicializan la extensi?n exclusiva
438
                        splashWindow.process(130,
439 14819 jmvivo
                                        PluginServices.getText(Launcher.class, "SplashWindow.setting_up_master_extension"));
440
                        SwingUtilities.invokeAndWait(new Runnable() {
441
                            public void run() {
442
                                    initializeExclusiveUIExtension();
443
                            }
444
                    });
445
                    frame.setClassesExtensions(classesExtensions);
446
447
448 14168 jdominguez
449 14819 jmvivo
450 16285 vcaballero
451 14819 jmvivo
                    // 14. Se instalan los controles de las extensiones de los plugins
452
                    splashWindow.process(140,
453 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_controls"));
454 7303 caballero
                    SwingUtilities.invokeAndWait(new Runnable() {
455
                            public void run() {
456
                                    installPluginsControls();
457 14819 jmvivo
458 14168 jdominguez
                            }
459
                    });
460 14819 jmvivo
461
                    // 15. Se instalan los menus de las extensiones de los plugins
462
                    splashWindow.process(150,
463 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_menus"));
464
                    SwingUtilities.invokeAndWait(new Runnable() {
465
                            public void run() {
466 7303 caballero
                                    installPluginsMenus();
467 14819 jmvivo
468 14168 jdominguez
                            }
469
                    });
470 14819 jmvivo
471
                    // 16. Se instalan las etiquetas de las extensiones de los plugins
472
                    splashWindow.process(160,
473 14168 jdominguez
                                    PluginServices.getText(Launcher.class, "SplashWindow.installing_extensions_labels"));
474
                    SwingUtilities.invokeAndWait(new Runnable() {
475
                            public void run() {
476 7303 caballero
                                    installPluginsLabels();
477 1067 fernando
478 14168 jdominguez
                            }
479
                    });
480
481 6101 jaume
482 14819 jmvivo
                    // 17. Se instalan los bookmarks de los plugins
483
484
                    // 18. Se muestra el frame principal
485
                    splashWindow.process(180,
486
                                    PluginServices.getText(Launcher.class, "creating_main_window"));
487
                    frame.setVisible(true);
488
489
                    // 19. Se ejecuta el postInitialize
490
                        splashWindow.process(190,
491 14168 jdominguez
                                        PluginServices.getText(Launcher.class, "SplashWindow.post_initializing_extensions"));
492 14819 jmvivo
                    SwingUtilities.invokeAndWait(new Runnable() {
493 14168 jdominguez
                            public void run() {
494
                                    postInitializeExtensions();
495 1067 fernando
496 14168 jdominguez
                            }
497
                    });
498
499 6101 jaume
500 7303 caballero
                    // Definimos un KeyEventDispatcher global para que las extensiones
501 15936 jmvivo
                    // puedan registrar sus "teclas r?pidas".
502 7303 caballero
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
503
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
504 6101 jaume
505 7303 caballero
                    SwingUtilities.invokeAndWait(new Runnable() {
506
                            public void run() {
507
                                    frame.enableControls();
508
                            }
509
                    });
510
                    splashWindow.close();
511 14819 jmvivo
            }catch(Exception e){
512 15936 jmvivo
                    logger.error("excepci?n al arrancar", e);
513 7303 caballero
                    System.exit(-1);
514
            }
515
516
    }
517
518 36378 nfrancisco
519
        private static void initializeApp(String[] args) throws IOException,
520
                        ConfigurationException {
521
                if (!validJVM()){
522
                        System.exit(-1);
523
                }
524
525
                //  Clean temporal files
526
                Utilities.cleanUpTempFiles();
527
528
                appName = args[0];
529
530
                appHomeDir = System.getProperty(args[0]+".home");
531
                if (appHomeDir == null)
532
                        appHomeDir = System.getProperty("user.home");
533
534
                appHomeDir += File.separator + args[0] + File.separator;
535
536
                // If gvSIG.confDir exists, then it will override any other setting for
537
                // the configuration file path.
538
                // This is a Java property, which means it has to be passed to the
539
                // VM like this: java -DgvSIG.confDir=<path>
540
                String gvsig_conf_dir = System.getProperty("gvSIG.confDir");
541
                if ( gvsig_conf_dir != null ) {
542
                        gvsig_conf_dir = gvsig_conf_dir.trim();
543
                        if ( gvsig_conf_dir.length() > 0 ) {
544
                                if ( gvsig_conf_dir.endsWith(File.separator) ) {
545
                                        appHomeDir = gvsig_conf_dir;
546
                                } else {
547
                                        appHomeDir = gvsig_conf_dir + File.separator;
548
                                }
549
                        }
550
                }
551
552
                FileUtils.setAppHomeDir(appHomeDir);
553
                logger.debug("User settings will be stored in: " + appHomeDir );
554
555
                File parent = new File( appHomeDir );
556
                parent.mkdirs();
557
558
559
                andamiConfigPath = appHomeDir + "andami-config.xml";
560
                pluginsPersistencePath = appHomeDir + "plugins-persistence.xml";
561
562
563
                // Configurar el log4j
564
                Launcher.class.getClassLoader()
565
                .getResource(".");
566
                PropertyConfigurator.configure("log4j.properties");
567
568
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
569
570
                RollingFileAppender fa = new RollingFileAppender(l,
571
                                appHomeDir + args[0] + ".log", false);
572
573
                fa.setMaxFileSize("512KB");
574
                fa.setMaxBackupIndex(3);
575
                Logger.getRootLogger().addAppender(fa);
576
577
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
578
                // locale
579
                // Buscar actualizaci?nes al comenzar
580
                //  Andami
581
                //  Plugins
582
                // Directorio de las extensiones
583
                andamiConfigFromXML(andamiConfigPath);
584
                andamiConfig.setPluginsDirectory(args[1]);
585
586
                // Hacemos visibles los argumentos como una propiedad est?tica
587
                // de plugin services para quien lo quiera usar (por ejemplo, para
588
                // cargar un proyecto por l?nea de comandos)
589
                PluginServices.setArguments(args);
590
591
                configureLocales(args);
592
593
                //Se pone el lookAndFeel
594
                try {
595
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
596
                        if (lookAndFeel == null)
597
                                lookAndFeel = getDefaultLookAndFeel();
598
                        UIManager.setLookAndFeel(lookAndFeel);
599
                } catch (Exception e) {
600
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
601
                }
602
                FontUtils.initFonts();
603
        }
604
605 14819 jmvivo
    private static void registerIcons(){
606 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
607 14819 jmvivo
                            "login-gvsig",
608
                            LoginUI.class.getClassLoader().getResource("images/login_gvsig.png")
609
                    );
610 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
611 14819 jmvivo
                            "splash-gvsig",
612
                            MultiSplashWindow.class.getClassLoader().getResource("images/splash.png")
613
                    );
614 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
615 14819 jmvivo
                            "info-icon",
616
                            NewStatusBar.class.getClassLoader().getResource("images/info.gif")
617
                    );
618 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
619 14819 jmvivo
                            "error-icon",
620
                            NewStatusBar.class.getClassLoader().getResource("images/error.gif")
621
                    );
622 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
623 14819 jmvivo
                            "warning-icon",
624
                            NewStatusBar.class.getClassLoader().getResource("images/warning.gif")
625
                    );
626 15633 jmvivo
            PluginServices.getIconTheme().registerDefault(
627 14819 jmvivo
                            "no-icon",
628
                            NewStatusBar.class.getClassLoader().getResource("images/no_icon.png")
629
                    );
630
    }
631
632 8921 caballero
    /**
633 15936 jmvivo
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
634
     * la aplicaci?n.
635 8921 caballero
     *
636
     * @return Theme
637
     */
638
    private static Theme getTheme() {
639
            Theme theme=new Theme();
640 9096 caballero
            String name=PluginServices.getArgumentByName("andamiTheme");
641
                //File file=new File("theme/andami-theme.xml");
642 9211 fdiaz
            File file;
643
            if (name==null){
644 9956 caballero
                    file=new File("theme/andami-theme.xml");
645 9211 fdiaz
            }else{
646 9956 caballero
                    file=new File(name);
647 9211 fdiaz
            }
648 9956 caballero
649 9096 caballero
            if (file.exists()) {
650 8921 caballero
                        theme.readTheme(file);
651
                }
652
                return theme;
653
        }
654 4299 luisw2
        /**
655 15936 jmvivo
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
656 8921 caballero
     *del proxy.
657
     */
658
        private static void configureProxy() {
659
                String host = prefs.get("firewall.http.host", "");
660
                String port = prefs.get("firewall.http.port", "");
661
662
                System.getProperties().put("http.proxyHost", host);
663
                System.getProperties().put("http.proxyPort", port);
664
665
                // Ponemos el usuario y clave del proxy, si existe
666
                String proxyUser = prefs.get("firewall.http.user",null);
667
                String proxyPassword = prefs.get("firewall.http.password", null);
668
                if (proxyUser != null )
669
                {
670
                        System.getProperties().put("http.proxyUserName", proxyUser);
671
                        System.getProperties().put("http.proxyPassword", proxyPassword);
672
673
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
674
                                                        proxyPassword));
675
                } else {
676
                        Authenticator.setDefault(new ProxyAuth("", ""));
677
                }
678
        }
679
680
        /**
681 15936 jmvivo
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal de Andami.
682 4299 luisw2
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
683
         * @author LWS
684
         */
685
        private static void restoreMDIStatus(XMLEntity xml) {
686
                if (xml == null) xml = new XMLEntity();
687
                //  restore frame size
688
                Dimension sz = new Dimension(700,580);
689
                if (xml.contains("MDIFrameSize")) {
690
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
691
                        sz = new Dimension(wh[0], wh[1]);
692
                }
693
                frame.setSize(sz);
694
                //  restore frame location
695
                Point pos = new Point(10,10);
696
                if (xml.contains("MDIFramePos")) {
697
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
698
                        pos = new Point(xy[0], xy[1]);
699
                }
700
                frame.setLocation(pos);
701 6101 jaume
702 4299 luisw2
                //  restore frame status (Maximized, minimized, etc);
703
                int state = java.awt.Frame.MAXIMIZED_BOTH;
704
                if (xml.contains("MDIFrameState")) {
705
                        state = xml.getIntProperty("MDIFrameState");
706
                }
707
                frame.setExtendedState(state);
708 1067 fernando
        }
709 6101 jaume
710 4299 luisw2
        private static XMLEntity saveMDIStatus() {
711
                XMLEntity xml = new XMLEntity();
712
                // save frame size
713
                int [] wh = new int[2];
714
                wh[0] = frame.getWidth();
715
                wh[1] = frame.getHeight();
716
                xml.putProperty("MDIFrameSize", wh);
717
                // save frame location
718
                int [] xy = new int[2];
719
                xy[0] = frame.getX();
720
                xy[1] = frame.getY();
721
                xml.putProperty("MDIFramePos", xy);
722
                // save frame status
723
                xml.putProperty("MDIFrameState", frame.getExtendedState());
724
                return xml;
725
        }
726 1067 fernando
727 2142 fernando
    private static boolean validJVM() {
728
        char thirdCharacter = System.getProperty("java.version").charAt(2);
729
        if (thirdCharacter < '4'){
730
            return false;
731
            }else{
732
                return true;
733
            }
734
    }
735
736 1067 fernando
        private static void loadPluginsPersistence() throws ConfigurationException {
737
                XMLEntity entity = persistenceFromXML();
738
739 6861 jaume
                for (int i = 0; i < entity.getChildrenCount(); i++) {
740 1067 fernando
                        XMLEntity plugin = entity.getChild(i);
741
                        String pName = plugin.getStringProperty(
742
                                        "com.iver.andami.pluginName");
743 1381 vcaballero
                        if (pluginsServices.get(pName)!= null){
744
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
745 4299 luisw2
                        } else {
746
                                if (pName.startsWith("Andami.Launcher"))
747
                                        restoreMDIStatus(plugin);
748 1381 vcaballero
                        }
749 1067 fernando
                }
750
        }
751 6101 jaume
752 4299 luisw2
        /**
753
         * Salva la persistencia de los plugins.
754
         * @author LWS
755
         */
756
        private static void savePluginPersistence() {
757
                Iterator i = pluginsConfig.keySet().iterator();
758 1067 fernando
759 4299 luisw2
                XMLEntity entity = new XMLEntity();
760
761
                while (i.hasNext()) {
762
                        String pName = (String) i.next();
763
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
764
                        XMLEntity ent = ps.getPersistentXML();
765
766
                        if (ent != null) {
767
                                ent.putProperty("com.iver.andami.pluginName", pName);
768
                                entity.addChild(ent);
769
                        }
770
                }
771
                XMLEntity ent = saveMDIStatus();
772
                if (ent != null) {
773
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
774
                        entity.addChild(ent);
775
                }
776
                try {
777
                        persistenceToXML(entity);
778
                } catch (ConfigurationException e1) {
779
                        logger.error(Messages.getString(
780
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
781
                                e1);
782
                }
783
        }
784
785 1067 fernando
        private static void installPluginsLabels() {
786
                Iterator i = pluginsConfig.keySet().iterator();
787
788
                while (i.hasNext()) {
789
                        String name = (String) i.next();
790
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
791
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
792
793
                        LabelSet[] ls = pc.getLabelSet();
794
795
                        for (int j = 0; j < ls.length; j++) {
796
                                PluginClassLoader loader = ps.getClassLoader();
797
798
                                try {
799
                                        Class clase = loader.loadClass(ls[j].getClassName());
800 10532 cesar
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
801 1067 fernando
                                } catch (ClassNotFoundException e) {
802 1173 fernando
                                        logger.error(Messages.getString("Launcher.labelset_class"),
803 1067 fernando
                                                e);
804
                                }
805 598 fernando
                        }
806 1067 fernando
                }
807
        }
808 598 fernando
809 17607 vcaballero
        private static String configureSkin(XMLEntity xml,String defaultSkin) {
810
                if (defaultSkin == null){
811
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
812
                                if (xml.getChild(i).contains("Skin-Selected")) {
813
                                        String className = xml.getChild(i).getStringProperty(
814
                                        "Skin-Selected");
815
                                        return className;
816
                                }
817 15983 vcaballero
                        }
818
                }
819 23414 jcampos
//                return "com.iver.core.mdiManager.NewSkin";
820
                return  defaultSkin;
821 15983 vcaballero
        }
822 23784 vcaballero
823 17607 vcaballero
        private static void fixSkin(SkinExtension skinExtension,PluginClassLoader pluginClassLoader) throws MDIManagerLoadException{
824
                // now insert the skin selected.
825
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
826
                // MDIManagerFactory.setSkinExtension(se,
827
                // ps.getClassLoader());
828 23784 vcaballero
829 17607 vcaballero
                Class skinClass;
830 23784 vcaballero
831 17607 vcaballero
                try {
832
                        skinClass = pluginClassLoader.loadClass(
833
                                        skinExtension.getClassName());
834 23784 vcaballero
835 17607 vcaballero
                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass
836
                        .newInstance();
837
                        // classesExtensions.put(skinClass, skinInstance);
838
                        // jaume
839
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
840
                                        skinInstance, ExtensionDecorator.INACTIVE);
841
                        classesExtensions.put(skinClass, newExtensionDecorator);
842
                } catch (ClassNotFoundException e) {
843
                        logger
844
                        .error(
845
                                        Messages
846
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
847
                                        e);
848
                        throw new MDIManagerLoadException(e);
849
                } catch (InstantiationException e) {
850
                        logger
851
                        .error(
852
                                        Messages
853
                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
854
                                        e);
855
                        throw new MDIManagerLoadException(e);
856
                } catch (IllegalAccessException e) {
857
                        logger
858
                        .error(
859
                                        Messages
860
                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
861
                                        e);
862
                        throw new MDIManagerLoadException(e);
863
                }
864
865
        }
866 1067 fernando
        /**
867
         * DOCUMENT ME!
868
         *
869
         * @throws MDIManagerLoadException
870
         */
871 17607 vcaballero
        private static void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
872 15983 vcaballero
                XMLEntity entity =null;
873
                try {
874
                        entity = persistenceFromXML();
875
                } catch (ConfigurationException e1) {
876
                        // TODO Auto-generated catch block
877
                        e1.printStackTrace();
878
                }
879 1067 fernando
                Iterator i = pluginsConfig.keySet().iterator();
880 598 fernando
881 17607 vcaballero
                SkinExtension skinExtension = null;
882
                PluginClassLoader pluginClassLoader = null;
883 23414 jcampos
                ArrayList skinExtensions = new ArrayList();
884 1067 fernando
                while (i.hasNext()) {
885
                        String name = (String) i.next();
886
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
887
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
888
889
                        if (pc.getExtensions().getSkinExtension() != null) {
890 15983 vcaballero
//                                if (MDIManagerFactory.getSkinExtension() != null) {
891
//                                        logger.warn(Messages.getString(
892
//                                                        "Launcher.Dos_skin_extension"));
893
//                                }
894 1067 fernando
895 15983 vcaballero
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
896 23414 jcampos
                                for (int numExten=0; numExten<se.length; numExten++) {
897
                                        skinExtensions.add(se[numExten]);
898
                                }
899 15983 vcaballero
                                for (int j=0;j<se.length;j++){
900 23414 jcampos
                                        String configuredSkin = Launcher.configureSkin(entity,defaultSkin);
901
                                        if (configuredSkin!=null && configuredSkin.equals(se[j].getClassName())) {
902 17607 vcaballero
                                                skinExtension = se[j];
903
                                                pluginClassLoader = ps.getClassLoader();
904 15983 vcaballero
                                        }
905 1067 fernando
                                }
906 598 fernando
                        }
907 1067 fernando
                }
908 23784 vcaballero
909 17607 vcaballero
                if ((skinExtension != null) && (pluginClassLoader != null)) {
910 23414 jcampos
                        // configured skin was found
911 17607 vcaballero
                        fixSkin(skinExtension, pluginClassLoader);
912
                } else {
913 23414 jcampos
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
914
                                // try first NewSkin (from CorePlugin)
915 20791 jcampos
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
916
                        }
917 23414 jcampos
                        else if (skinExtensions.size()>0){
918 23784 vcaballero
                                // try to load the first skin found
919 23414 jcampos
                                SkinExtension se =  (SkinExtension)skinExtensions.get(0);
920
                                skinPlugin((String)se.getClassName());
921
                        }
922
                        else {
923
                                throw new MDIManagerLoadException("No Skin-Extension installed");
924
                        }
925 17607 vcaballero
                }
926 23784 vcaballero
927 1067 fernando
        }
928 598 fernando
929 8921 caballero
        private static void frameIcon(Theme theme) {
930 1067 fernando
                Iterator i = pluginsConfig.keySet().iterator();
931 598 fernando
932 1067 fernando
                while (i.hasNext()) {
933
                        String pName = (String) i.next();
934
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
935
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
936 8921 caballero
                        if (pc.getIcon() != null) {
937
                                if (theme.getIcon() != null) {
938
                                        frame.setIconImage(theme.getIcon().getImage());
939
                                } else {
940 598 fernando
941 15913 jmvivo
                                        ImageIcon icon = PluginServices.getIconTheme().get(pc.getIcon().getSrc());
942 8921 caballero
                                        frame.setIconImage(icon.getImage());
943
944
                                }
945
                                if (theme.getName() != null) {
946
                                        frame.setTitlePrefix(theme.getName());
947
                                } else {
948
                                        frame.setTitlePrefix(pc.getIcon().getText());
949
                                }
950
                                if (theme.getBackgroundImage() != null) {
951 8970 caballero
952
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
953 8921 caballero
                                }
954 1067 fernando
                        }
955
                }
956
        }
957 598 fernando
958 1067 fernando
        private static void initializeExtensions() {
959 2828 fjp
                Iterator i = pluginsOrdered.iterator();
960 598 fernando
961 1067 fernando
                while (i.hasNext()) {
962
                        String pName = (String) i.next();
963 2862 jaume
            logger.debug("Initializing extensions from " + pName);
964 1067 fernando
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
965
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
966 598 fernando
967 1067 fernando
                        Extension[] exts = pc.getExtensions().getExtension();
968 598 fernando
969 1067 fernando
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
970 598 fernando
971 1067 fernando
                        for (int j = 0; j < exts.length; j++) {
972
                                if (!exts[j].getActive()) {
973
                                        continue;
974
                                }
975 598 fernando
976 1067 fernando
                                if (orderedExtensions.containsKey(exts[j])) {
977 1236 fernando
                                        logger.warn(Messages.getString(
978
                                                        "Launcher.Two_extensions_with_the_same_priority") +
979 1067 fernando
                                                exts[j].getClassName());
980
                                }
981 598 fernando
982 1067 fernando
                                orderedExtensions.put(exts[j], null);
983
                        }
984 598 fernando
985 1067 fernando
                        Iterator e = orderedExtensions.keySet().iterator();
986 598 fernando
987 1067 fernando
                        while (e.hasNext()) {
988
                                Extension extension = (Extension) e.next();
989 5005 jorpiell
                                com.iver.andami.plugins.IExtension extensionInstance;
990 598 fernando
991 1067 fernando
                                try {
992
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
993 5005 jorpiell
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
994 6101 jaume
995
                                        // CON DECORATOR
996 2862 jaume
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
997
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
998
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
999 14819 jmvivo
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
1000
                                        // la extensi?n original que acabamos de crear
1001 2862 jaume
                                        // 0-> Inactivo, controla la extension
1002
                                        // 1-> Siempre visible
1003
                                        // 2-> Invisible
1004
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
1005
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
1006 11910 cesar
                                        logger.info("Initializing " + extension.getClassName()+"...");
1007 2828 fjp
                    // logger.debug("Initializing " + extension.getClassName());
1008 5005 jorpiell
                    extensionInstance.initialize();
1009 7303 caballero
                    extensions.add(extensionInstance);
1010 2828 fjp
                    // logger.debug(extension.getClassName() + " initialized.");
1011 598 fernando
1012 1067 fernando
                                } catch (InstantiationException e1) {
1013 1236 fernando
                                        logger.error(Messages.getString(
1014
                                                        "Launcher.Error_instanciando_la_extension") +
1015 1067 fernando
                                                extension.getClassName(), e1);
1016
                                } catch (IllegalAccessException e1) {
1017 1236 fernando
                                        logger.error(Messages.getString(
1018
                                                        "Launcher.Error_instanciando_la_extension") +
1019 1067 fernando
                                                extension.getClassName(), e1);
1020
                                } catch (ClassNotFoundException e1) {
1021 1236 fernando
                                        logger.error(Messages.getString(
1022
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
1023 1067 fernando
                                                extension.getClassName(), e1);
1024
                                } catch (NoClassDefFoundError e1) {
1025 1236 fernando
                                        logger.error(Messages.getString(
1026
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
1027 1067 fernando
                                                extension.getClassName(), e1);
1028
                                }
1029
                        }
1030
                }
1031
        }
1032 598 fernando
1033 7303 caballero
        private static void postInitializeExtensions() {
1034
                for (int i=0;i<extensions.size();i++) {
1035
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1036
                        extensionInstance.postInitialize();
1037
                }
1038
        }
1039 14168 jdominguez
1040 1067 fernando
        private static void installPluginsMenus() {
1041
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
1042 598 fernando
1043 1067 fernando
                Iterator i = pluginsConfig.keySet().iterator();
1044 598 fernando
1045 1067 fernando
                while (i.hasNext()) {
1046
                        String pName = (String) i.next();
1047
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1048
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1049 598 fernando
1050 1067 fernando
                        Extension[] exts = pc.getExtensions().getExtension();
1051 598 fernando
1052 1067 fernando
                        for (int j = 0; j < exts.length; j++) {
1053
                                if (!exts[j].getActive()) {
1054
                                        continue;
1055
                                }
1056 598 fernando
1057 3298 caballero
                                Menu[] menus = exts[j].getMenu();
1058 598 fernando
1059 3298 caballero
                                for (int k = 0; k < menus.length; k++) {
1060 1067 fernando
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1061 3298 caballero
                                                        exts[j], menus[k]);
1062 598 fernando
1063 1067 fernando
                                        if (orderedMenus.containsKey(sm)) {
1064 1236 fernando
                                                logger.error(Messages.getString(
1065 6589 cesar
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
1066
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
1067 1067 fernando
                                        }
1068 598 fernando
1069 1067 fernando
                                        orderedMenus.put(sm, null);
1070
                                }
1071
                        }
1072 598 fernando
1073 1067 fernando
                        // Se instalan las extensiones de MDI
1074 15983 vcaballero
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
1075
                        for (int j = 0; j < skinExts.length; j++) {
1076 598 fernando
1077
1078 15983 vcaballero
                        if (skinExts[j] != null) {
1079
                                Menu[] menu = skinExts[j].getMenu();
1080
1081 1067 fernando
                                for (int k = 0; k < menu.length; k++) {
1082
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1083 15983 vcaballero
                                                        skinExts[j], menu[k]);
1084 598 fernando
1085 1067 fernando
                                        if (orderedMenus.containsKey(sm)) {
1086 1236 fernando
                                                logger.error(Messages.getString(
1087
                                                                "Launcher.Two_menus_with_the_same_position") +
1088 15983 vcaballero
                                                        skinExts[j].getClassName());
1089 1067 fernando
                                        }
1090 598 fernando
1091 1067 fernando
                                        orderedMenus.put(sm, null);
1092
                                }
1093
                        }
1094 15983 vcaballero
                        }
1095 1067 fernando
                }
1096 598 fernando
1097 1067 fernando
                //Se itera por los menus ordenados
1098
                Iterator e = orderedMenus.keySet().iterator();
1099 598 fernando
1100 1067 fernando
                // Se ordenan los menues
1101
                while (e.hasNext()) {
1102
                        try {
1103
                                SortableMenu sm = (SortableMenu) e.next();
1104 598 fernando
1105 1067 fernando
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1106
                        } catch (ClassNotFoundException ex) {
1107 1236 fernando
                                logger.error(Messages.getString(
1108
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
1109 1067 fernando
                        }
1110
                }
1111
        }
1112 598 fernando
1113 1067 fernando
        /**
1114 6589 cesar
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
1115 6101 jaume
         * The order in which they are shown is determined here.
1116 1067 fernando
         */
1117
        private static void installPluginsControls() {
1118
                Iterator i = pluginsConfig.keySet().iterator();
1119 598 fernando
1120 2112 fernando
                HashMap extensionPluginServices = new HashMap();
1121
                HashMap extensionPluginConfig = new HashMap();
1122
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
1123 6101 jaume
1124 5421 cesar
                // First of all, sort the extensions.
1125
                // We need to iterate on the plugins, and iterate on each plugin's extensions
1126 6101 jaume
                // (each plugin may contain one or more extensions)
1127 5421 cesar
                while (i.hasNext()) { // iterate on the plugins
1128
                        String pName = (String) i.next();
1129
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1130
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1131 6101 jaume
1132 5421 cesar
                        Extension[] exts = pc.getExtensions().getExtension();
1133 6101 jaume
1134 5421 cesar
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
1135
                                if (exts[j].getActive()) {
1136
                                        if (orderedExtensions.containsKey(exts[j])) {
1137
                                                logger.error(Messages.getString(
1138
                                                "Launcher.Two_extensions_with_the_same_priority") +
1139
                                                exts[j].getClassName());
1140 1067 fernando
                                        }
1141 6101 jaume
1142 5421 cesar
                                        orderedExtensions.put(exts[j], null);
1143
                                        extensionPluginServices.put(exts[j], ps);
1144
                                        extensionPluginConfig.put(exts[j], pc);
1145 1067 fernando
                                }
1146 5421 cesar
                        }
1147 2112 fernando
                }
1148 598 fernando
1149 5421 cesar
                TreeMap orderedTools = new TreeMap(new ToolComparator());
1150
                Iterator e = orderedExtensions.keySet().iterator();
1151 6101 jaume
1152 6614 cesar
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
1153 10544 cesar
                // and load the  combo-scales and combo-buttons for the status bar
1154 5421 cesar
                while (e.hasNext()) {
1155
                        Extension ext = (Extension) e.next();
1156 6101 jaume
1157 5421 cesar
                        ToolBar[] toolbars = ext.getToolBar();
1158 6101 jaume
1159 6589 cesar
                        // get tools from toolbars
1160 5421 cesar
                        for (int k = 0; k < toolbars.length; k++) {
1161
                                ActionTool[] tools = toolbars[k].getActionTool();
1162 6101 jaume
1163 5421 cesar
                                for (int t = 0; t < tools.length; t++) {
1164 6589 cesar
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1165 5421 cesar
                                                        toolbars[k], tools[t]);
1166 6589 cesar
                                        orderedTools.put(sm, null);
1167 5421 cesar
                                }
1168 6101 jaume
1169 5421 cesar
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
1170 6101 jaume
1171 5421 cesar
                                for (int t = 0; t < sTools.length; t++) {
1172 6589 cesar
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
1173 5421 cesar
                                                        toolbars[k], sTools[t]);
1174 6589 cesar
                                        orderedTools.put(sm, null);
1175 5421 cesar
                                }
1176
                        }
1177 6861 jaume
1178 6589 cesar
                        // get controls for statusBar
1179
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
1180
                        PluginClassLoader loader = ps.getClassLoader();
1181 6861 jaume
1182 6589 cesar
                        //ArrayList componentList = new ArrayList();
1183
                        ComboScale[] comboScaleArray = ext.getComboScale();
1184
                        for (int k=0; k < comboScaleArray.length; k++) {
1185
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1186 6619 cesar
                                String label = comboScaleArray[k].getLabel();
1187
                                if (label!=null)
1188
                                        combo.setLabel(label);
1189 6623 cesar
                                String name = comboScaleArray[k].getName();
1190
                                if (name!=null)
1191
                                        combo.setName(name);
1192 6589 cesar
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
1193
                                long[] elements = new long[elementsString.length];
1194
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
1195
                                        try {
1196
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
1197
                                        }
1198
                                        catch (NumberFormatException nfex1) {
1199 6918 cesar
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
1200 6589 cesar
                                                elements[currentElem] = 0;
1201
                                        }
1202
                                }
1203
                                combo.setItems(elements);
1204
                                try {
1205
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
1206
                                        combo.setScale(value);
1207
                                }
1208
                                catch (NumberFormatException nfex2) {
1209 6918 cesar
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
1210 6589 cesar
                                }
1211
                                try {
1212 6614 cesar
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
1213 6589 cesar
                                } catch (ClassNotFoundException e1) {
1214
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1215
                                }
1216
                        }
1217
1218
                        ComboButton[] comboButtonArray = ext.getComboButton();
1219
                        for (int k=0; k < comboButtonArray.length; k++) {
1220
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
1221
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1222 6623 cesar
                                String name = comboButtonArray[k].getName();
1223
                                if (name!=null)
1224
                                        combo.setName(name);
1225 6589 cesar
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
1226
                                        ComboButtonElement element = elementList[currentElement];
1227
                                        ImageIcon icon;
1228
                                        URL iconLocation = loader.getResource(element.getIcon());
1229
                                        if (iconLocation==null)
1230
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
1231
                                        else {
1232
                                                icon = new ImageIcon(iconLocation);
1233
                                                JButton button = new JButton(icon);
1234
                                                combo.addButton(button);
1235
                                                button.setActionCommand(element.getActionCommand());
1236
                                        }
1237
                                }
1238
                                try {
1239 6614 cesar
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
1240 6589 cesar
                                } catch (ClassNotFoundException e1) {
1241
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
1242
                                }
1243
                        }
1244 5421 cesar
                }
1245 598 fernando
1246 6589 cesar
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
1247 5421 cesar
                i = pluginsConfig.keySet().iterator();
1248
                while (i.hasNext()) {
1249
                        String pName = (String) i.next();
1250
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1251
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1252 6101 jaume
1253 15983 vcaballero
                        SkinExtension[] skinExts = pc.getExtensions().getSkinExtension();
1254
                        for (int j = 0; j < skinExts.length; j++) {
1255 6101 jaume
1256
1257 15983 vcaballero
                        if (skinExts[j] != null) {
1258
                                ToolBar[] toolbars = skinExts[j].getToolBar();
1259
1260 2112 fernando
                                for (int k = 0; k < toolbars.length; k++) {
1261
                                        ActionTool[] tools = toolbars[k].getActionTool();
1262 6101 jaume
1263 2112 fernando
                                        for (int t = 0; t < tools.length; t++) {
1264 15983 vcaballero
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1265 3298 caballero
                                                                toolbars[k], tools[t]);
1266 6589 cesar
                                                orderedTools.put(stb,null);
1267 2112 fernando
                                        }
1268 6101 jaume
1269 2112 fernando
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1270 6101 jaume
1271 2112 fernando
                                        for (int t = 0; t < sTools.length; t++) {
1272 15983 vcaballero
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExts[j],
1273 3298 caballero
                                                                toolbars[k], sTools[t]);
1274 6589 cesar
                                                orderedTools.put(stb,null);
1275 1067 fernando
                                        }
1276
                                }
1277 2112 fernando
                        }
1278 15983 vcaballero
                        }
1279 6589 cesar
                        // Install popup menus
1280 5421 cesar
                        PopupMenus pus = pc.getPopupMenus();
1281 6101 jaume
1282 5421 cesar
                        if (pus != null) {
1283
                                PopupMenu[] menus = pus.getPopupMenu();
1284 6101 jaume
1285 5421 cesar
                                for (int j = 0; j < menus.length; j++) {
1286
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1287 1067 fernando
                                }
1288
                        }
1289 5421 cesar
                }
1290 3298 caballero
1291 6589 cesar
                // loop on the ordered extension list, to add them to the interface in an ordered way
1292 6101 jaume
                Iterator t = orderedTools.keySet().iterator();
1293 5421 cesar
                while (t.hasNext()) {
1294
                        try {
1295 6589 cesar
                                SortableTool stb = (SortableTool) t.next();
1296 5421 cesar
                                if (stb.actiontool!=null)
1297
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
1298
                                else
1299
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
1300
                        } catch (ClassNotFoundException ex) {
1301
                                logger.error(Messages.getString(
1302
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
1303 3298 caballero
                        }
1304 5421 cesar
                }
1305 1067 fernando
        }
1306 598 fernando
1307 1067 fernando
        /**
1308 6861 jaume
         * Adds new plugins to the the andami-config file.
1309 1067 fernando
         */
1310
        private static void updateAndamiConfig() {
1311
                HashSet olds = new HashSet();
1312 598 fernando
1313 1067 fernando
                Plugin[] plugins = andamiConfig.getPlugin();
1314 598 fernando
1315 1067 fernando
                for (int i = 0; i < plugins.length; i++) {
1316
                        olds.add(plugins[i].getName());
1317
                }
1318 598 fernando
1319 1067 fernando
                Iterator i = pluginsServices.values().iterator();
1320 598 fernando
1321 1067 fernando
                while (i.hasNext()) {
1322
                        PluginServices ps = (PluginServices) i.next();
1323 598 fernando
1324 1067 fernando
                        if (!olds.contains(ps.getPluginName())) {
1325
                                Plugin p = new Plugin();
1326
                                p.setName(ps.getPluginName());
1327
                                p.setUpdate(false);
1328 598 fernando
1329 1067 fernando
                                andamiConfig.addPlugin(p);
1330
                        }
1331
                }
1332
        }
1333 598 fernando
1334 1067 fernando
        private static void pluginsClassLoaders() {
1335
                HashSet instalados = new HashSet();
1336 598 fernando
1337 15936 jmvivo
                // Se itera hasta que est?n todos instalados
1338 1067 fernando
                while (instalados.size() != pluginsConfig.size()) {
1339
                        boolean circle = true;
1340 598 fernando
1341 1067 fernando
                        //Hacemos una pasada por todos los plugins
1342
                        Iterator i = pluginsConfig.keySet().iterator();
1343 598 fernando
1344 1067 fernando
                        while (i.hasNext()) {
1345
                                String pluginName = (String) i.next();
1346
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1347 598 fernando
1348 1067 fernando
                                if (instalados.contains(pluginName)) {
1349
                                        continue;
1350
                                }
1351 598 fernando
1352 1067 fernando
                                //Se obtienen las dependencias y sus class loaders
1353
                                boolean ready = true;
1354
                                Depends[] dependencies = config.getDepends();
1355
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1356 598 fernando
1357 1067 fernando
                                for (int j = 0; j < dependencies.length; j++) {
1358
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1359 1236 fernando
                                                logger.error(Messages.getString(
1360
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1361 1067 fernando
                                                        pluginName + ": " +
1362 1153 fernando
                                                        dependencies[j].getPluginName());
1363 598 fernando
1364 1067 fernando
                                                continue;
1365
                                        }
1366 598 fernando
1367 1067 fernando
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1368
                                                ready = false;
1369
                                        } else {
1370
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1371
                                        }
1372
                                }
1373 598 fernando
1374 15936 jmvivo
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1375 1067 fernando
                                if (!ready) {
1376
                                        continue;
1377
                                }
1378 598 fernando
1379 1067 fernando
                                //Se genera el class loader
1380 1110 fernando
                                String jardir = config.getLibraries().getLibraryDir();
1381
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1382
                                                File.separator + pluginName + File.separator + jardir);
1383
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1384 1236 fernando
                                                        public boolean accept(File pathname) {
1385
                                                                return (pathname.getName().toUpperCase()
1386
                                                                                                .endsWith(".JAR")) ||
1387
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1388
                                                        }
1389
                                                });
1390
1391 1110 fernando
                                URL[] urls = new URL[jarFiles.length];
1392 1236 fernando
1393 1110 fernando
                                for (int j = 0; j < jarFiles.length; j++) {
1394 1067 fernando
                                        try {
1395 1110 fernando
                                                urls[j] = new URL("file:" + jarFiles[j]);
1396 1067 fernando
                                        } catch (MalformedURLException e) {
1397 1236 fernando
                                                logger.error(Messages.getString(
1398
                                                                "Launcher.No_se_puede_acceder_a") +
1399 1110 fernando
                                                        jarFiles[j]);
1400 1067 fernando
                                        }
1401
                                }
1402 598 fernando
1403 1067 fernando
                                PluginClassLoader loader;
1404 598 fernando
1405 1067 fernando
                                try {
1406
                                        loader = new PluginClassLoader(urls,
1407
                                                        andamiConfig.getPluginsDirectory() +
1408
                                                        File.separator + pluginName,
1409
                                                        Launcher.class.getClassLoader(), loaders);
1410 598 fernando
1411 1067 fernando
                                        PluginServices ps = new PluginServices(loader);
1412 598 fernando
1413 1067 fernando
                                        pluginsServices.put(ps.getPluginName(), ps);
1414 598 fernando
1415 1067 fernando
                                        instalados.add(pluginName);
1416 6101 jaume
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1417 2828 fjp
                    // inicializar los plugins
1418
                    pluginsOrdered.add(pluginName);
1419 598 fernando
1420 1067 fernando
                                        circle = false;
1421
                                } catch (IOException e) {
1422 1236 fernando
                                        logger.error(Messages.getString(
1423
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1424 1067 fernando
                                        pluginsConfig.remove(pluginName);
1425
                                        i = pluginsConfig.keySet().iterator();
1426
                                }
1427
                        }
1428 598 fernando
1429 1067 fernando
                        if (circle) {
1430 1236 fernando
                                logger.error(Messages.getString(
1431
                                                "Launcher.Hay_dependencias_circulares"));
1432 598 fernando
1433 1067 fernando
                                break;
1434
                        }
1435
                }
1436 598 fernando
1437 1067 fernando
                //Se eliminan los plugins que no fueron instalados
1438
                Iterator i = pluginsConfig.keySet().iterator();
1439 598 fernando
1440 1067 fernando
                while (i.hasNext()) {
1441
                        String pluginName = (String) i.next();
1442
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1443
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1444 598 fernando
1445 1067 fernando
                        if (ps == null) {
1446
                                pluginsConfig.remove(pluginName);
1447
                                i = pluginsConfig.keySet().iterator();
1448
                        }
1449 6101 jaume
                }
1450 1067 fernando
        }
1451 598 fernando
1452 1067 fernando
        private static void pluginsMessages() {
1453 13681 cesar
                Iterator iterator = pluginsOrdered.iterator();
1454
                PluginConfig config;
1455
                PluginServices ps;
1456 13742 caballero
1457 13681 cesar
                while (iterator.hasNext()) {
1458
                        String pluginName = (String) iterator.next();
1459
                        config = (PluginConfig) pluginsConfig.get(pluginName);
1460
                        ps = (PluginServices) pluginsServices.get(pluginName);
1461 4909 cesar
1462 13681 cesar
                        if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1463
                                // add the locale files associated with the plugin
1464
                                org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1465 1067 fernando
                        }
1466
                }
1467
        }
1468 598 fernando
1469 1067 fernando
        static PluginServices getPluginServices(String name) {
1470
                return (PluginServices) pluginsServices.get(name);
1471
        }
1472 598 fernando
1473 1067 fernando
        static String getPluginsDir() {
1474
                return andamiConfig.getPluginsDirectory();
1475
        }
1476 598 fernando
1477 1067 fernando
        static void setPluginsDir(String s) {
1478
                andamiConfig.setPluginsDirectory(s);
1479
        }
1480 598 fernando
1481 1067 fernando
        static MDIFrame getMDIFrame() {
1482
                return frame;
1483
        }
1484 598 fernando
1485 1067 fernando
        private static void loadPlugins(String pluginsDirectory) {
1486
                File pDir = new File(pluginsDirectory);
1487 598 fernando
1488 1067 fernando
                if (!pDir.exists()) {
1489 13681 cesar
                        logger.error("\n\tPlugins directory not found: "+pDir.getAbsolutePath()+"\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1490
                        System.exit(-1);
1491 1067 fernando
                        return;
1492
                }
1493 598 fernando
1494 1067 fernando
                File[] pluginDirs = pDir.listFiles();
1495 13681 cesar
                if (pluginDirs.length==0) {
1496
                        logger.error("\n\tPlugins directory is empty: "+pDir.getAbsolutePath()+"Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
1497
                        System.exit(-1);
1498
                        return;
1499
                }
1500 598 fernando
1501 1067 fernando
                for (int i = 0; i < pluginDirs.length; i++) {
1502
                        if (pluginDirs[i].isDirectory()) {
1503
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1504
                                                File.separator + "config.xml");
1505 598 fernando
1506 1067 fernando
                                try {
1507 8752 cesar
                                        FileInputStream is = new FileInputStream(configXml);
1508
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1509
                                        if (xml==null) {
1510
                                                // the encoding was not correctly detected, use system default
1511
                                                xml = new FileReader(configXml);
1512
                                        }
1513
                                        else {
1514
                                                // use a buffered reader to improve performance
1515
                                                xml = new BufferedReader(xml);
1516
                                        }
1517 1067 fernando
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1518
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1519
                                } catch (FileNotFoundException e) {
1520 1236 fernando
                                        logger.info(Messages.getString(
1521
                                                        "Launcher.Ignorando_el_directorio") +
1522 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1523 1173 fernando
                                                Messages.getString("Launcher.config_no_encontrado"));
1524 1067 fernando
                                } catch (MarshalException e) {
1525 1236 fernando
                                        logger.info(Messages.getString(
1526
                                                        "Launcher.Ignorando_el_directorio") +
1527 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1528 1173 fernando
                                                Messages.getString("Launcher.config_mal_formado"), e);
1529 1067 fernando
                                } catch (ValidationException e) {
1530 1236 fernando
                                        logger.info(Messages.getString(
1531
                                                        "Launcher.Ignorando_el_directorio") +
1532 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1533 1173 fernando
                                                Messages.getString("Launcher.config_mal_formado"), e);
1534 1067 fernando
                                }
1535
                        }
1536
                }
1537 13742 caballero
1538 13681 cesar
                if (pluginsConfig.size()==0) {
1539
                        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...");
1540
                        System.exit(-1);
1541
                        return;
1542
                }
1543 1067 fernando
        }
1544 598 fernando
1545 1067 fernando
        private static Locale getLocale(String language, String country,
1546
                String variant) {
1547
                if (variant != null) {
1548
                        return new Locale(language, country, variant);
1549
                } else if (country != null) {
1550
                        return new Locale(language, country);
1551
                } else if (language != null) {
1552
                        return new Locale(language);
1553
                } else {
1554
                        return new Locale("es");
1555
                }
1556
        }
1557 598 fernando
1558 1067 fernando
        private static void andamiConfigToXML(String file)
1559
                throws IOException, MarshalException, ValidationException {
1560 10010 cesar
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1561
                File tmpFile = new File(file+"-"+DateTime.getCurrentDate().getTime());
1562 1067 fernando
                File xml = new File(file);
1563
                File parent = xml.getParentFile();
1564
                parent.mkdirs();
1565 598 fernando
1566 13832 cesar
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile));
1567
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
1568 1067 fernando
                andamiConfig.marshal(writer);
1569 10042 cesar
                writer.close();
1570 13713 caballero
1571 10042 cesar
                // if marshaling process finished correctly, move the file to the correct one
1572
                xml.delete();
1573
                if (!tmpFile.renameTo(xml)) {
1574
                        // if rename was not succesful, try copying it
1575
                        FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1576
                        FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1577
                        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1578
                        sourceChannel.close();
1579 13713 caballero
                        destinationChannel.close();
1580 10042 cesar
                }
1581 1067 fernando
        }
1582 598 fernando
1583 1067 fernando
        private static void andamiConfigFromXML(String file)
1584
                throws ConfigurationException {
1585
                File xml = new File(file);
1586 598 fernando
1587 13832 cesar
                InputStreamReader reader = null;
1588 10009 cesar
                try {
1589 15936 jmvivo
                        //Se lee la configuraci?n
1590 13832 cesar
                        reader = XMLEncodingUtils.getReader(xml);
1591 10009 cesar
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1592
                } catch (FileNotFoundException e) {
1593
                        //Si no existe se ponen los valores por defecto
1594
                        andamiConfig = getDefaultAndamiConfig();
1595
                } catch (MarshalException e) {
1596 10042 cesar
                        // try to close the stream, maybe it remains open
1597
                        if (reader!=null) {
1598
                                try { reader.close(); } catch (IOException e1) {}
1599
                        }
1600 10009 cesar
                        // if there was a problem reading the file, backup it and create a new one with default values
1601
                        String backupFile = file+"-"+DateTime.getCurrentDate().getTime();
1602 10023 cesar
                        NotificationManager.addError(Messages.getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1603 10009 cesar
                        xml.renameTo(new File(backupFile));
1604
                        andamiConfig = getDefaultAndamiConfig();
1605
                } catch (ValidationException e) {
1606
                        throw new ConfigurationException(e);
1607
                }
1608
        }
1609 13713 caballero
1610 10009 cesar
        private static AndamiConfig getDefaultAndamiConfig() {
1611
                AndamiConfig andamiConfig = new AndamiConfig();
1612 598 fernando
1613 10009 cesar
                Andami andami = new Andami();
1614
                andami.setUpdate(true);
1615
                andamiConfig.setAndami(andami);
1616
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1617
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1618
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1619 598 fernando
1620 10009 cesar
                if (System.getProperty("javawebstart.version") != null) // Es java web start)
1621
                 {
1622
                        andamiConfig.setPluginsDirectory(new File(appHomeDir
1623
                                        + "extensiones").getAbsolutePath());
1624 1067 fernando
                } else {
1625 10009 cesar
                        andamiConfig.setPluginsDirectory(new File(appName +
1626
                                        File.separator + "extensiones").getAbsolutePath());
1627
                }
1628 598 fernando
1629 10009 cesar
                andamiConfig.setPlugin(new Plugin[0]);
1630
                return andamiConfig;
1631 1067 fernando
        }
1632 598 fernando
1633 1067 fernando
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1634
                File xml = new File(pluginsPersistencePath);
1635 598 fernando
1636 1067 fernando
                if (xml.exists()) {
1637 13832 cesar
                        InputStreamReader reader = null;
1638 598 fernando
1639 1067 fernando
                        try {
1640 13832 cesar
                                reader = XMLEncodingUtils.getReader(xml);
1641 1067 fernando
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1642
                                return new XMLEntity(tag);
1643
                        } catch (FileNotFoundException e) {
1644
                                throw new ConfigurationException(e);
1645
                        } catch (MarshalException e) {
1646 14819 jmvivo
1647 13832 cesar
                                // try to reopen with default encoding (for backward compatibility)
1648
                                try {
1649
                                        reader = new FileReader(xml);
1650
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1651
                                        return new XMLEntity(tag);
1652 14819 jmvivo
1653 13832 cesar
                                } catch (MarshalException ex) {
1654
                                        // try to close the stream, maybe it remains open
1655
                                        if (reader!=null) {
1656
                                                try { reader.close(); } catch (IOException e1) {}
1657
                                        }
1658
                                        // backup the old file
1659
                                        String backupFile = pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime();
1660
                                        NotificationManager.addError(Messages.getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1661
                                        xml.renameTo(new File(backupFile));
1662
                                        // create a new, empty configuration
1663
                                        return new XMLEntity();
1664 10042 cesar
                                }
1665 13832 cesar
                                catch (FileNotFoundException ex) {
1666
                                        return new XMLEntity();
1667
                                } catch (ValidationException ex) {
1668
                                        throw new ConfigurationException(e);
1669
                                }
1670 1067 fernando
                        } catch (ValidationException e) {
1671
                                throw new ConfigurationException(e);
1672
                        }
1673
                } else {
1674
                        return new XMLEntity();
1675
                }
1676
        }
1677 598 fernando
1678 1067 fernando
        private static void persistenceToXML(XMLEntity entity)
1679
                throws ConfigurationException {
1680 10010 cesar
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1681
                File tmpFile = new File(pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime());
1682 13713 caballero
1683 1067 fernando
                File xml = new File(pluginsPersistencePath);
1684 13832 cesar
                OutputStreamWriter writer = null;
1685 14819 jmvivo
1686 1067 fernando
                try {
1687 13832 cesar
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile), CASTORENCODING);
1688 1067 fernando
                        entity.getXmlTag().marshal(writer);
1689 10042 cesar
                        writer.close();
1690 13713 caballero
1691
                        // if marshaling process finished correctly, move the file to the correct one
1692 10042 cesar
                        xml.delete();
1693
                        if (!tmpFile.renameTo(xml)) {
1694
                                // if rename was not succesful, try copying it
1695
                                FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1696
                                FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1697
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1698
                                sourceChannel.close();
1699
                                destinationChannel.close();
1700 13713 caballero
1701 10042 cesar
                        }
1702 1067 fernando
                } catch (FileNotFoundException e) {
1703
                        throw new ConfigurationException(e);
1704
                } catch (MarshalException e) {
1705 10042 cesar
                        // try to close the stream, maybe it remains open
1706
                        if (writer!=null) {
1707
                                try { writer.close(); } catch (IOException e1) {}
1708
                        }
1709 1067 fernando
                } catch (ValidationException e) {
1710
                        throw new ConfigurationException(e);
1711
                } catch (IOException e) {
1712
                        throw new ConfigurationException(e);
1713
                }
1714
        }
1715 598 fernando
1716 1067 fernando
        static MDIFrame getFrame() {
1717
                return frame;
1718
        }
1719 598 fernando
1720 1067 fernando
        /**
1721 12697 cesar
         * Gracefully closes the application. It shows dialogs to save data,
1722
         * finish processes, etc, then it terminates the extensions, removes
1723
         * temporal files and finally exits.
1724 1067 fernando
         */
1725 13079 cesar
        public synchronized static void closeApplication() {
1726 12697 cesar
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
1727
                terminationProcess.run();
1728 1067 fernando
        }
1729 6101 jaume
1730 1067 fernando
        static HashMap getClassesExtensions() {
1731
                return classesExtensions;
1732
        }
1733 598 fernando
1734 2332 fjp
        private static void downloadExtensions(String extDir) {
1735
                java.util.Date fechaActual = null;
1736
1737
                try {
1738
                        if (System.getProperty("javawebstart.version") != null) {
1739
                                //Obtenemos la URL del servidor
1740
                                BasicService bs = (BasicService) ServiceManager.lookup(
1741
                                                "javax.jnlp.BasicService");
1742
                                URL baseURL = bs.getCodeBase();
1743
1744
                                //Se descargan las extensiones
1745 14168 jdominguez
                                splashWindow.process(5,
1746 2332 fjp
                                        "Descargando las extensiones desde " + baseURL + " a " +
1747
                                        extDir);
1748
1749
                                URL url = new URL(baseURL + "extensiones.zip");
1750
                                URLConnection connection = url.openConnection();
1751
1752
                                System.out.println(url.toExternalForm() + ":");
1753
                                System.out.println("  Content Type: " +
1754
                                        connection.getContentType());
1755
                                System.out.println("  Content Length: " +
1756
                                        connection.getContentLength());
1757
                                System.out.println("  Last Modified: " +
1758
                                        new Date(connection.getLastModified()));
1759
                                System.out.println("  Expiration: " +
1760
                                        connection.getExpiration());
1761
                                System.out.println("  Content Encoding: " +
1762
                                        connection.getContentEncoding());
1763
1764
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1765 15936 jmvivo
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1766 2332 fjp
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1767
                                // nos bajamos nada.
1768
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1769
1770
                                File destDir = new File(extDir);
1771
1772
                                if (!destDir.exists()) {
1773
                                        // Creamos gvSIG
1774
                                        destDir.getParentFile().mkdir();
1775
1776
                                        if (!destDir.mkdir()) {
1777
                                                System.err.println("Imposible crear el directorio " +
1778
                                                        destDir.getAbsolutePath());
1779
                                        }
1780
                                }
1781
1782
                                File timeFile = new File(destDir.getParent() + File.separator +
1783
                                                "timeStamp.properties");
1784
1785
                                if (!timeFile.exists()) {
1786
                                        timeFile.createNewFile();
1787
                                }
1788
1789
                                FileInputStream inAux = new FileInputStream(timeFile);
1790
                                Properties prop = new Properties();
1791
                                prop.load(inAux);
1792
                                inAux.close();
1793
1794
                                if (prop.getProperty("timestamp") != null) {
1795
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1796
                                                                "timestamp"));
1797
1798
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1799 14819 jmvivo
                                                System.out.println("No hay nueva actualizaci?n");
1800
                        logger.debug("No hay nueva actualizaci?n -> Return");
1801 7514 caballero
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1802
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1803 2332 fjp
1804
                                                return;
1805
                                        }
1806
1807
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1808
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1809
                                } else {
1810 14819 jmvivo
                                        System.out.println("El timeStamp no est? escrito en " +
1811 2332 fjp
                                                timeFile.getAbsolutePath());
1812
                                }
1813
1814 7514 caballero
                                InputStream stream = url.openStream();
1815
                File temp = File.createTempFile("gvsig", ".zip");
1816 2332 fjp
1817 7514 caballero
                logger.debug(temp.getAbsolutePath());
1818 2332 fjp
1819 7514 caballero
                temp.deleteOnExit();
1820
                FileOutputStream file = new FileOutputStream(temp);
1821 2332 fjp
1822 7514 caballero
                byte[] lt_read = new byte[1];
1823 2332 fjp
1824 7514 caballero
                while (stream.read(lt_read) > 0)
1825
                  file.write(lt_read);
1826 2332 fjp
1827 7514 caballero
                                stream.close();
1828
                stream = null;
1829
                file.close();
1830
                file = null;
1831 2332 fjp
1832 7514 caballero
                System.gc();
1833 2332 fjp
1834 7514 caballero
                logger.debug("Ha creado el fichero ZIP");
1835 2332 fjp
                                //Se extrae el zip
1836 14168 jdominguez
                splashWindow.process(5, "Extensiones descargadas.");
1837 2332 fjp
1838
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1839
1840
                                Date fechaDir = new Date(destDir.lastModified());
1841
                                System.out.println("Fecha del directorio " + extDir + " = " +
1842
                                        fechaDir.toString());
1843
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1844
1845
                                // Si todo ha ido bien, guardamos el timestamp.
1846
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1847
                                // XMLEntity xml=ps.getPersistentXML();
1848
                                fechaActual = new java.util.Date();
1849
1850
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1851
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1852
                                prop.store(outAux, "last download");
1853
                                outAux.close();
1854
                                System.out.println("Fecha actual guardada: " +
1855
                                        fechaActual.toGMTString());
1856
1857
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1858
                                   ps.setPresistentXML(xml); */
1859
                        }
1860
                } catch (IOException e) {
1861
                        NotificationManager.addError("", e);
1862
                } catch (UnavailableServiceException e) {
1863
                        NotificationManager.addError("", e);
1864
                } catch (SecurityException e) {
1865
                        System.err.println("No se puede escribir el timeStamp " +
1866
                                fechaActual.toGMTString());
1867
                        NotificationManager.addError("", e);
1868
                }
1869
        }
1870
1871 1067 fernando
        private static Extensions[] getExtensions() {
1872
                ArrayList array = new ArrayList();
1873
                Iterator iter = pluginsConfig.values().iterator();
1874
1875
                while (iter.hasNext()) {
1876
                        array.add(((PluginConfig) iter.next()).getExtensions());
1877 735 vcaballero
                }
1878 1067 fernando
1879
                return (Extensions[]) array.toArray(new Extensions[0]);
1880 735 vcaballero
        }
1881 1067 fernando
1882 28374 vcaballero
        public static Iterator getExtensionIterator() {
1883
                return extensions.iterator();
1884
        }
1885
1886 1067 fernando
        public static HashMap getPluginConfig() {
1887 735 vcaballero
                return pluginsConfig;
1888
        }
1889 1067 fernando
1890
        public static Extension getExtension(String s) {
1891
                Extensions[] exts = getExtensions();
1892
1893
                for (int i = 0; i < exts.length; i++) {
1894
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1895
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1896 735 vcaballero
                                        return exts[i].getExtension(j);
1897
                                }
1898 1067 fernando
                        }
1899 735 vcaballero
                }
1900 1067 fernando
1901 735 vcaballero
                return null;
1902
        }
1903 1067 fernando
1904
        public static AndamiConfig getAndamiConfig() {
1905 794 vcaballero
                return andamiConfig;
1906
        }
1907 1236 fernando
1908 1153 fernando
        private static class ExtensionComparator implements Comparator {
1909 1067 fernando
                public int compare(Object o1, Object o2) {
1910
                        Extension e1 = (Extension) o1;
1911
                        Extension e2 = (Extension) o2;
1912
1913
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1914
                                return -1;
1915 735 vcaballero
                        }
1916 1067 fernando
1917
                        if (e1.hasPriority() && !e2.hasPriority()) {
1918 6696 cesar
                                return Integer.MIN_VALUE;
1919 1067 fernando
                        }
1920
1921
                        if (e2.hasPriority() && !e1.hasPriority()) {
1922
                                return Integer.MAX_VALUE;
1923
                        }
1924
1925 2112 fernando
                        if (e1.getPriority() != e2.getPriority()){
1926
                                return e2.getPriority() - e1.getPriority();
1927
                        }else{
1928
                                return (e2.toString().compareTo(e1.toString()));
1929
                        }
1930 735 vcaballero
                }
1931 1067 fernando
        }
1932
1933 1153 fernando
        private static class MenuComparator implements Comparator {
1934 1067 fernando
                private static ExtensionComparator extComp = new ExtensionComparator();
1935
1936
                public int compare(Object o1, Object o2) {
1937
                        SortableMenu e1 = (SortableMenu) o1;
1938
                        SortableMenu e2 = (SortableMenu) o2;
1939
1940
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1941
                                if (e1.extension instanceof SkinExtensionType) {
1942
                                        return 1;
1943
                                } else if (e2.extension instanceof SkinExtensionType) {
1944
                                        return -1;
1945
                                } else {
1946
                                        return extComp.compare(e1.extension, e2.extension);
1947
                                }
1948
                        }
1949
1950
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1951 6696 cesar
                                return Integer.MIN_VALUE;
1952 1067 fernando
                        }
1953
1954
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1955
                                return Integer.MAX_VALUE;
1956
                        }
1957 6696 cesar
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1958
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1959
                                return e1.menu.getPosition() - e2.menu.getPosition();
1960
                        }else{
1961
                                return (e1.toString().compareTo(e2.toString()));
1962
                        }
1963 735 vcaballero
                }
1964
        }
1965 1067 fernando
1966 1153 fernando
        private static class SortableMenu {
1967 1067 fernando
                public PluginClassLoader loader;
1968
                public Menu menu;
1969
                public SkinExtensionType extension;
1970
1971
                public SortableMenu(PluginClassLoader loader,
1972
                        SkinExtensionType skinExt, Menu menu2) {
1973
                        extension = skinExt;
1974
                        menu = menu2;
1975
                        this.loader = loader;
1976
                }
1977
        }
1978 14168 jdominguez
1979 6589 cesar
        private static class SortableTool {
1980 5421 cesar
                public PluginClassLoader loader;
1981
                public ToolBar toolbar;
1982
                public ActionTool actiontool;
1983
                public SelectableTool selectabletool;
1984
                public SkinExtensionType extension;
1985
1986 6589 cesar
                public SortableTool(PluginClassLoader loader,
1987 5421 cesar
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1988
                        extension = skinExt;
1989
                        toolbar = toolbar2;
1990
                        actiontool=actiontool2;
1991
                        this.loader = loader;
1992
                }
1993 6589 cesar
                public SortableTool(PluginClassLoader loader,
1994 5421 cesar
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1995
                        extension = skinExt;
1996
                        toolbar = toolbar2;
1997
                        selectabletool=selectabletool2;
1998
                        this.loader = loader;
1999
                }
2000
        }
2001 14168 jdominguez
2002 3298 caballero
        private static class ToolBarComparator implements Comparator {
2003
                private static ExtensionComparator extComp = new ExtensionComparator();
2004
2005
                public int compare(Object o1, Object o2) {
2006 6589 cesar
                        SortableTool e1 = (SortableTool) o1;
2007
                        SortableTool e2 = (SortableTool) o2;
2008 6101 jaume
2009 5421 cesar
                        // if the toolbars have the same name, they are considered to be
2010
                        // the same toolbar, so we don't need to do further comparing
2011
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
2012
                                return 0;
2013 6101 jaume
2014 3298 caballero
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2015
                                if (e1.extension instanceof SkinExtensionType) {
2016
                                        return 1;
2017
                                } else if (e2.extension instanceof SkinExtensionType) {
2018
                                        return -1;
2019
                                } else {
2020
                                        return extComp.compare(e1.extension, e2.extension);
2021
                                }
2022
                        }
2023
2024
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2025 6696 cesar
                                return Integer.MIN_VALUE;
2026 3298 caballero
                        }
2027
2028
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2029
                                return Integer.MAX_VALUE;
2030
                        }
2031 3310 caballero
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
2032 5421 cesar
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2033 6101 jaume
2034 3310 caballero
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
2035
                                return 0;
2036
                        }
2037 5421 cesar
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2038 3298 caballero
                }
2039
        }
2040 6101 jaume
2041 3298 caballero
        /**
2042 5421 cesar
         * <p>This class is used to compare tools (selectabletool and actiontool),
2043
         * using the "position"
2044
         * attribute.</p>
2045
         * <p>The ordering criteria are:</p>
2046
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
2047
         * order.
2048
         * (using the ToolBarComparator).</li>
2049
         * <li></li>
2050
         * <li>If any of the tools has not 'position' attribute, the tool which
2051
         * <strong>has</strong> the attribute will be placed first.</li>
2052
         * <li>If both tools have the same position (or they don't have a
2053
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
2054 3298 caballero
         *
2055 5421 cesar
         * @author cesar
2056 3298 caballero
         * @version $Revision$
2057
         */
2058 5421 cesar
        private static class ToolComparator implements Comparator {
2059
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2060 14168 jdominguez
2061 5421 cesar
                public int compare(Object o1, Object o2) {
2062
                        // compare the toolbars which contain the tools
2063
                        int result = toolBarComp.compare(o1, o2);
2064
                        if (result != 0) { // if the toolbars are different, use their order
2065
                                return result;
2066
                        }
2067
                        // otherwise, compare the tools
2068 6589 cesar
                        SortableTool e1 = (SortableTool) o1;
2069
                        SortableTool e2 = (SortableTool) o2;
2070 5421 cesar
                        int e1Position=-1, e2Position=-1;
2071
2072
                        if (e1.actiontool!=null) {
2073
                                if (e1.actiontool.hasPosition())
2074
                                        e1Position = e1.actiontool.getPosition();
2075
                        }
2076
                        else if (e1.selectabletool!=null) {
2077
                                if (e1.selectabletool.hasPosition())
2078
                                        e1Position = e1.selectabletool.getPosition();
2079
                        }
2080 6101 jaume
2081 5421 cesar
                        if (e2.actiontool!=null) {
2082
                                if (e2.actiontool.hasPosition())
2083
                                        e2Position = e2.actiontool.getPosition();
2084
                        }
2085
                        else if (e2.selectabletool!=null){
2086
                                if (e2.selectabletool.hasPosition())
2087
                                        e2Position = e2.selectabletool.getPosition();
2088
                        }
2089 6101 jaume
2090 5421 cesar
                        if (e1Position==-1 && e2Position!=-1) {
2091
                                return 1;
2092
                        }
2093
                        if (e1Position!=-1 && e2Position==-1) {
2094
                                return -1;
2095
                        }
2096
                        if (e1Position!=-1 && e2Position!=-1) {
2097
                                result = e1Position - e2Position;
2098
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
2099
                                if (result!=0) return result;
2100
                        }
2101
                        return e1.toString().compareTo(e2.toString());
2102 3298 caballero
                }
2103
        }
2104 6101 jaume
2105
2106 4306 ldiaz
        /**
2107
         * validates the user before starting gvsig
2108
         *
2109
         */
2110
        private static void validate(){
2111 14819 jmvivo
2112 4306 ldiaz
                IAuthentication session =  null;
2113
                try {
2114
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
2115
2116
                } catch (ClassNotFoundException e) {
2117
                        return;
2118
                } catch (InstantiationException e) {
2119 4308 ldiaz
                        return;
2120 4306 ldiaz
                } catch (IllegalAccessException e) {
2121 4308 ldiaz
                        return;
2122 4306 ldiaz
                }
2123 6101 jaume
2124 4306 ldiaz
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
2125
                if (session.validationRequired()){
2126 7584 ldiaz
                        if(session.Login()){
2127 4306 ldiaz
                                System.out.println("You are logged in");
2128
                        }
2129
                        else{
2130
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
2131 6101 jaume
                                                 "You are not logged in");
2132 7584 ldiaz
                                //System.exit(0);
2133 4358 ldiaz
                        }
2134
                        PluginServices.setAuthentication(session);
2135 6101 jaume
                }
2136 4306 ldiaz
        }
2137 6101 jaume
2138
        public static String getDefaultLookAndFeel() {
2139
                String osName = (String) System.getProperty("os.name");
2140
2141 9208 jmvivo
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2142
                        return nonWinDefaultLookAndFeel;
2143 25553 vcaballero
                if (osName.toLowerCase().startsWith("mac os x"))
2144
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2145 9956 caballero
2146 25553 vcaballero
2147 9349 mija
                return UIManager.getSystemLookAndFeelClassName();
2148 6101 jaume
        }
2149 6951 cesar
2150
        /**
2151
         * Gets the ISO 839 two-characters-long language code matching the
2152
         * provided language code (which may be an ISO 839-2/T
2153
         * three-characters-long code or an ISO 839-1 two-characters-long
2154
         * code).
2155 7303 caballero
         *
2156 6951 cesar
         * If the provided parameter is already two characters long, it
2157
         * returns the parameter without any modification.
2158 7303 caballero
         *
2159 6951 cesar
         * @param langCode A language code representing either
2160
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2161
         * @return A two-characters-long code specifying
2162
         *  an ISO 839 language code.
2163
         */
2164
        private static String normalizeLanguageCode(String langCode) {
2165
                final String fileName = "iso_639.tab";
2166
                if (langCode.length()==2)
2167
                        return langCode;
2168
                else if (langCode.length()==3) {
2169
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2170
                                return "ca";
2171
                        }
2172
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2173
                        if (isoCodes!=null) {
2174
                                try {
2175
                                        BufferedReader reader =
2176
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2177
                                                String line;
2178
2179
                                                while ((line = reader.readLine()) != null) {
2180
                                                        String[] language = line.split("\t");
2181
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2182
                                                                return language[2]; // third column i the two characters code
2183
                                                }
2184
                                }
2185
                                catch (IOException ex) {
2186
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2187
                                        return "es";
2188
                                }
2189
                        }
2190
                        else {
2191
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2192
                                return "es";
2193
                        }
2194
                }
2195
                return "es";
2196
        }
2197 7303 caballero
2198 6951 cesar
        /**
2199
         * Configures the locales (languages and local resources) to be used
2200
         * by the application.
2201 7303 caballero
         *
2202 6951 cesar
         * First it tries to get the locale from the command line parameters,
2203
         * then the andami-config file is checked.
2204 7303 caballero
         *
2205 6951 cesar
         * The locale name is normalized to get a two characters language code
2206
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2207
         * are also accepted from the command line or the configuration file).
2208 7303 caballero
         *
2209 6951 cesar
         * Finally, the gvsig-i18n library and the default locales for Java and
2210
         * Swing are configured.
2211
         *
2212
         */
2213
        private static void configureLocales(String[] args) {
2214
                //                 Configurar el locale
2215
        String localeStr = null;
2216 8989 jmvivo
        /*
2217 6951 cesar
        for (int i=2; i < args.length; i++)
2218
        {
2219
                int index = args[i].indexOf("language=");
2220
                if (index != -1)
2221
                        localeStr = args[i].substring(index+9);
2222
        }
2223 8989 jmvivo
         */
2224
        localeStr = PluginServices.getArgumentByName("language");
2225 6951 cesar
                if (localeStr == null)
2226
                {
2227
            localeStr = andamiConfig.getLocaleLanguage();
2228
                }
2229
                localeStr = normalizeLanguageCode(localeStr);
2230
                locale = getLocale(localeStr,
2231
                andamiConfig.getLocaleCountry(),
2232
                andamiConfig.getLocaleVariant());
2233
                Locale.setDefault(locale);
2234
                JComponent.setDefaultLocale(locale);
2235
        org.gvsig.i18n.Messages.addLocale(locale);
2236
                // add english and spanish as fallback languages
2237 28941 vcaballero
        if (localeStr.equals("es")||localeStr.equals("ca")||localeStr.equals("gl")||localeStr.equals("eu")||localeStr.equals("va")) {
2238 13079 cesar
                // prefer Spanish for languages spoken in Spain
2239
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2240
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2241
        }
2242
        else {
2243
                // prefer English for the rest
2244
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2245 13713 caballero
                    org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2246 13079 cesar
        }
2247 6951 cesar
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2248
2249
        }
2250 8120 jmvivo
2251
        /**
2252
         * Gets Home Directory location of the application.
2253
         * May be set from outside the aplication by means of
2254
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2255
         * of the application
2256
         * @return
2257
         */
2258
        public static String getAppHomeDir() {
2259
                return appHomeDir;
2260
        }
2261
2262
        /**
2263
         * Sets Home Directory location of the application.
2264
         * May be set from outside the aplication by means of
2265
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2266
         * of the application
2267
         * @param appHomeDir
2268
         */
2269
        public static void setAppHomeDir(String appHomeDir) {
2270
                Launcher.appHomeDir = appHomeDir;
2271
        }
2272 9096 caballero
2273 8989 jmvivo
        /**
2274
         * Initialize the extesion that have to take the control
2275
         *  of the state of action controls of the UI of all extensions.
2276
         * <br>
2277
         * <br>
2278 9096 caballero
         * For use this option you have to add an argument
2279 8989 jmvivo
         * to the command line like this:
2280
         * <br>
2281
         * <br>
2282
         * -exclusiveUI={pathToExtensionClass}
2283
         * <br>
2284
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
2285
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
2286
         */
2287
        private static void initializeExclusiveUIExtension(){
2288
                String name = PluginServices.getArgumentByName("exclusiveUI");
2289 9096 caballero
                if (name == null)
2290 8989 jmvivo
                        return;
2291 9096 caballero
2292
2293 8989 jmvivo
                Iterator iter  = classesExtensions.keySet().iterator();
2294
                int charIndex;
2295
                Class key;
2296
                while (iter.hasNext()) {
2297
                        key = (Class)iter.next();
2298
                        charIndex = key.getName().indexOf(name);
2299
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2300
                        if (charIndex == 0) {
2301 9074 fdiaz
                                IExtension ext =(IExtension)classesExtensions.get(key);
2302
                                if (ext instanceof ExtensionDecorator)
2303
                                        ext = ((ExtensionDecorator)ext).getExtension();
2304 11910 cesar
                                if (ext instanceof ExclusiveUIExtension)
2305
                                        PluginServices.setExclusiveUIExtension((ExclusiveUIExtension)ext);
2306 8989 jmvivo
                                break;
2307
                        }
2308
                }
2309 9096 caballero
2310 8989 jmvivo
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2311
        }
2312 14819 jmvivo
2313
2314 15633 jmvivo
//        public static void initIconThemes() {
2315
//                // load the iconTheme
2316
//                IconThemeManager iconManager = new IconThemeManager();
2317
//                PluginServices.setIconThemeManager(iconManager);
2318
//                IconThemeInfo selectedTheme = iconManager.readConfig();
2319
//                if (selectedTheme!=null) {
2320
//                        iconManager.setDefault(selectedTheme);
2321
//                        logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
2322
//                }
2323
//                else {
2324
//                        // set the default dir and try to load the default theme
2325
//                        try {
2326
//                                iconManager.setThemesDir(new File("iconThemes"));
2327
//                                IconThemeInfo[] list = iconManager.list();
2328
//
2329
//                                for (int i=0; i<list.length; i++) {
2330
//                                        if (list[i].getResourceName().equals("iconThemes/icons")) {
2331
//                                                iconManager.setDefault(list[i]);
2332
//                                                logger.info("Setting the default icon theme: "+list[i].toVerboseString());
2333
//                                                return;
2334
//                                        }
2335
//                                }
2336
//                        } catch (FileNotFoundException e) {
2337
//                                logger.info("IconTheme basedir does not exist");
2338
//                        }
2339
//                        // create an empty theme
2340
//                        IconThemeInfo info = new IconThemeInfo();
2341
//                        info.setName("No theme loaded");
2342
//                        info.setResource(null); // null resource means that no real theme is loaded
2343
//                        info.setDescription("No theme loaded");
2344
//                        info.setVersion("0");
2345
//                        iconManager.setDefault(new IconTheme(info));
2346
//                        logger.info("Setting an empty icon theme");
2347
//
2348
//                }
2349
//        }
2350
2351
        public static void initIconThemes(){
2352 15944 jmvivo
                IconThemeManager iconManager = IconThemeManager.getIconThemeManager();
2353
                IIconTheme icontheme= iconManager.getIconThemeFromConfig();
2354 15633 jmvivo
                if (icontheme!=null){
2355
                        iconManager.setCurrent(icontheme);
2356 13832 cesar
                }
2357
        }
2358
2359 12697 cesar
        /**
2360
         * Manages Andami termination process
2361 13713 caballero
         *
2362 12697 cesar
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
2363
         */
2364
        public class TerminationProcess {
2365
                private boolean proceed = false;
2366
                private UnsavedDataPanel panel = null;
2367 13713 caballero
2368 12697 cesar
                public void run() {
2369
                        int exit = manageUnsavedData();
2370 23784 vcaballero
                        if (exit==JOptionPane.NO_OPTION || exit == JOptionPane.CLOSED_OPTION) {
2371 12697 cesar
                                // the user doesn't want to exit
2372
                                return;
2373
                        }
2374
2375
                        closeAndami();
2376
                }
2377 13713 caballero
2378 24435 vcaballero
                /**
2379
                 * Finishes the application without asking user if want or not to save unsaved data.
2380
                 */
2381
                public void closeAndami() {
2382 36378 nfrancisco
                        saveAndamiConfig();
2383 12697 cesar
2384
                        //Persistencia de los plugins
2385
                        savePluginPersistence();
2386
2387
                        //Finalize all the extensions
2388
                        finalizeExtensions();
2389
2390
                        // Clean any temp data created
2391
                        Utilities.cleanUpTempFiles();
2392
2393 15936 jmvivo
                        //Para la depuraci?n de memory leaks
2394 12697 cesar
                        System.gc();
2395
2396
                        System.exit(0);
2397
                }
2398 13713 caballero
2399 36378 nfrancisco
                public void saveAndamiConfig() {
2400
                        //Configuraci?n de Andami
2401
                        try {
2402
                                andamiConfigToXML(andamiConfigPath);
2403
                        } catch (MarshalException e) {
2404
                                logger.error(Messages.getString(
2405
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2406
                        } catch (ValidationException e) {
2407
                                logger.error(Messages.getString(
2408
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2409
                        } catch (IOException e) {
2410
                                logger.error(Messages.getString(
2411
                                "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
2412
                        }
2413
                }
2414
2415 12697 cesar
                /**
2416
                 * Exectutes the terminate method for all the extensions, in the reverse
2417
                 * order they were initialized
2418
                 *
2419
                 */
2420
                private void finalizeExtensions() {
2421
                        for (int i=extensions.size()-1; i>=0; i--) {
2422
                                com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
2423
                                extensionInstance.terminate();
2424
                        }
2425
                }
2426
2427 13713 caballero
2428 12697 cesar
                private ArrayList getUnsavedData() {
2429
                        ArrayList unsavedDataList = new ArrayList();
2430 13713 caballero
                        IExtension exclusiveExtension=PluginServices.getExclusiveUIExtension();
2431
2432 12697 cesar
                        for (int i=extensions.size()-1; i>=0; i--) {
2433
                                com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
2434 13713 caballero
                                IExtensionStatus status = null;
2435
                                if (exclusiveExtension!=null) {
2436
                                        status = exclusiveExtension.getStatus(extensionInstance);
2437
                                }else {
2438
                                        status = extensionInstance.getStatus();
2439
                                }
2440 12697 cesar
                                if (status!=null) {
2441
                                        if (status.hasUnsavedData()) {
2442
                                                IUnsavedData[] array = status.getUnsavedData();
2443
                                                for (int element = 0; element<array.length; element++) {
2444
                                                        unsavedDataList.add(array[element]);
2445
                                                }
2446
                                        }
2447
                                }
2448
                        }
2449
                        return unsavedDataList;
2450
                }
2451 13713 caballero
2452 12697 cesar
                public UnsavedDataPanel getUnsavedDataPanel() {
2453
                        if (panel==null) {
2454
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
2455
                        }
2456
                        return panel;
2457
                }
2458
                /**
2459
                 * Checks if the extensions have some unsaved data, and shows a dialog
2460 13713 caballero
                 * to allow saving it. This dialog also allows to don't exit Andami.
2461
                 *
2462 12697 cesar
                 * @return true if the user confirmed he wishes to exit, false otherwise
2463
                 */
2464
                public int manageUnsavedData(){
2465
                        ArrayList unsavedDataList = getUnsavedData();
2466
2467
                        // there was no unsaved data
2468
                        if (unsavedDataList.size()==0) {
2469
                                int option = JOptionPane.showConfirmDialog(frame,
2470
                                                Messages.getString("MDIFrame.quiere_salir"),
2471
                                                Messages.getString("MDIFrame.salir"),
2472
                                                JOptionPane.YES_NO_OPTION);
2473
                                return option;
2474
                        }
2475 13713 caballero
2476 12697 cesar
                        // it does not work if we directly cast the array
2477
                        IUnsavedData[] unsavedDataArray;
2478
                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2479
                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2480 13713 caballero
2481 12697 cesar
                        UnsavedDataPanel panel = getUnsavedDataPanel();
2482
                        panel.setUnsavedDataArray(unsavedDataArray);
2483
2484 13713 caballero
2485 12697 cesar
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
2486 13079 cesar
                                public void cancel(UnsavedDataPanel panel){
2487 12697 cesar
                                        proceed(false);
2488
                                        PluginServices.getMDIManager().closeWindow(panel);
2489 13713 caballero
2490 12697 cesar
                                }
2491 13713 caballero
2492 13079 cesar
                                public void discard(UnsavedDataPanel panel){
2493
                                        proceed(true);
2494
                                        PluginServices.getMDIManager().closeWindow(panel);
2495 13713 caballero
2496 13079 cesar
                                }
2497 12697 cesar
2498 13079 cesar
                                public void accept(UnsavedDataPanel panel){
2499 12697 cesar
                                        IUnsavedData[] unsavedDataArray = panel.getSelectedsUnsavedData();
2500
                                        boolean saved;
2501
                                        for (int i=0; i<unsavedDataArray.length; i++) {
2502
                                                try {
2503
                                                        saved = unsavedDataArray[i].saveData();
2504
                                                }
2505
                                                catch (Exception ex) {
2506
                                                        PluginServices.getLogger().error("Error saving"+unsavedDataArray[i].getResourceName() ,ex);
2507
                                                        saved = false;
2508
                                                }
2509
                                                if (!saved) {
2510
                                                        JOptionPane.showMessageDialog(
2511
                                                                        panel,
2512
                                                                        PluginServices.getText(this, "The_following_resource_could_not_be_saved_")+
2513
                                                                        "\n"+unsavedDataArray[i].getResourceName() + " -- "
2514
                                                                        + unsavedDataArray[i].getDescription(),
2515
                                                                        PluginServices.getText(this, "Resource_was_not_saved"),
2516
                                                                        JOptionPane.ERROR_MESSAGE);
2517 13713 caballero
2518 12697 cesar
                                                        ArrayList unsavedDataList = getUnsavedData();
2519
                                                        // it does not work if we directly cast the array
2520
                                                        unsavedDataArray = new IUnsavedData[unsavedDataList.size()];
2521
                                                        System.arraycopy(unsavedDataList.toArray(), 0, unsavedDataArray, 0, unsavedDataList.size());
2522
                                                        panel.setUnsavedDataArray(unsavedDataArray);
2523
                                                        return;
2524
                                                }
2525
                                        }
2526
                                        proceed(true);
2527
                                        PluginServices.getMDIManager().closeWindow(panel);
2528
                                }
2529
                        });
2530
2531
                        PluginServices.getMDIManager().addWindow(panel);
2532
                        if (proceed) {
2533
                                return JOptionPane.YES_OPTION;
2534
                        }
2535
                        else {
2536
                                return JOptionPane.NO_OPTION;
2537
                        }
2538
                }
2539 13713 caballero
2540 12697 cesar
                private void proceed(boolean proceed) {
2541
                        this.proceed = proceed;
2542
                }
2543 14819 jmvivo
2544
2545 12697 cesar
        }
2546 13713 caballero
2547 12697 cesar
        public static TerminationProcess getTerminationProcess() {
2548
                return (new Launcher()).new TerminationProcess();
2549
        }
2550 598 fernando
}