Statistics
| Revision:

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

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