Statistics
| Revision:

root / branches / v10 / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 9144

History | View | Annotate | Download (60.9 KB)

1 1104 fjp
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41 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 8765 jjdelcerro
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 6951 cesar
import java.io.BufferedReader;
51 598 fernando
import java.io.File;
52 1110 fernando
import java.io.FileFilter;
53 2332 fjp
import java.io.FileInputStream;
54 598 fernando
import java.io.FileNotFoundException;
55 2332 fjp
import java.io.FileOutputStream;
56 598 fernando
import java.io.FileReader;
57
import java.io.FileWriter;
58
import java.io.FilenameFilter;
59
import java.io.IOException;
60 2332 fjp
import java.io.InputStream;
61 6951 cesar
import java.io.InputStreamReader;
62 8765 jjdelcerro
import java.io.Reader;
63 598 fernando
import java.lang.reflect.InvocationTargetException;
64 8885 fjp
import java.net.Authenticator;
65 598 fernando
import java.net.MalformedURLException;
66 8885 fjp
import java.net.PasswordAuthentication;
67 598 fernando
import java.net.URL;
68 2332 fjp
import java.net.URLConnection;
69 7513 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 8885 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 598 fernando
import javax.swing.SwingUtilities;
93
import javax.swing.UIManager;
94
95 2112 fernando
import org.apache.log4j.Logger;
96
import org.apache.log4j.PatternLayout;
97
import org.apache.log4j.PropertyConfigurator;
98
import org.apache.log4j.RollingFileAppender;
99
import org.exolab.castor.xml.MarshalException;
100
import org.exolab.castor.xml.ValidationException;
101 598 fernando
102 4306 ldiaz
import com.iver.andami.authentication.IAuthentication;
103 2112 fernando
import com.iver.andami.config.generate.Andami;
104
import com.iver.andami.config.generate.AndamiConfig;
105
import com.iver.andami.config.generate.Plugin;
106
import com.iver.andami.messages.Messages;
107 2332 fjp
import com.iver.andami.messages.NotificationManager;
108 2862 jaume
import com.iver.andami.plugins.ExtensionDecorator;
109 2112 fernando
import com.iver.andami.plugins.PluginClassLoader;
110
import com.iver.andami.plugins.config.generate.ActionTool;
111 6589 cesar
import com.iver.andami.plugins.config.generate.ComboButton;
112
import com.iver.andami.plugins.config.generate.ComboButtonElement;
113
import com.iver.andami.plugins.config.generate.ComboScale;
114 2112 fernando
import com.iver.andami.plugins.config.generate.Depends;
115
import com.iver.andami.plugins.config.generate.Extension;
116
import com.iver.andami.plugins.config.generate.Extensions;
117
import com.iver.andami.plugins.config.generate.LabelSet;
118
import com.iver.andami.plugins.config.generate.Menu;
119
import com.iver.andami.plugins.config.generate.PluginConfig;
120
import com.iver.andami.plugins.config.generate.PopupMenu;
121
import com.iver.andami.plugins.config.generate.PopupMenus;
122
import com.iver.andami.plugins.config.generate.SelectableTool;
123
import com.iver.andami.plugins.config.generate.SkinExtension;
124
import com.iver.andami.plugins.config.generate.SkinExtensionType;
125
import com.iver.andami.plugins.config.generate.ToolBar;
126
import com.iver.andami.ui.AndamiEventQueue;
127
import com.iver.andami.ui.MDIManagerLoadException;
128
import com.iver.andami.ui.mdiFrame.MDIFrame;
129
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
130 8765 jjdelcerro
import com.iver.andami.ui.splash.MultiSplashWindow;
131 2112 fernando
import com.iver.utiles.XMLEntity;
132
import com.iver.utiles.xmlEntity.generate.XmlTag;
133
134
135 598 fernando
/**
136
 * DOCUMENT ME!
137
 *
138
 * @author $author$
139
 * @version $Revision$
140
 */
141
public class Launcher {
142 1067 fernando
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
143 8885 fjp
        private static Preferences prefs = Preferences.userRoot().node( "gvsig.connection" );
144 1067 fernando
        private static AndamiConfig andamiConfig;
145 8765 jjdelcerro
        private static MultiSplashWindow splashWindow;
146 1067 fernando
        private static String appName;
147
        private static Locale locale;
148
        private static HashMap pluginsConfig = new HashMap();
149
        private static HashMap pluginsServices = new HashMap();
150
        private static MDIFrame frame;
151
        private static HashMap classesExtensions = new HashMap();
152
        private static String andamiConfigPath;
153
        private static String pluginsPersistencePath;
154 6101 jaume
        private static final String nonWinDefaultLookAndFeel =  "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
155
156 2828 fjp
    private static ArrayList pluginsOrdered = new ArrayList();
157 8765 jjdelcerro
    private static ArrayList extensions=new ArrayList();
158 7682 luisw2
    private static String appHomeDir = null;
159 8885 fjp
160
    private static final class ProxyAuth extends Authenticator {
161
                private PasswordAuthentication auth;
162
163
                private ProxyAuth(String user, String pass) {
164
                        auth = new PasswordAuthentication(user, pass.toCharArray());
165
                }
166
167
                protected PasswordAuthentication getPasswordAuthentication() {
168
                        return auth;
169
                }
170
        }
171
172 1067 fernando
        /**
173
         * DOCUMENT ME!
174
         *
175
         * @param args DOCUMENT ME!
176 2142 fernando
         * @throws Exception
177 1067 fernando
         *
178
         * @throws InterruptedException
179
         * @throws InvocationTargetException
180
         * @throws ConfigurationException
181
         * @throws MDIManagerLoadException
182
         * @throws IOException
183
         */
184 8765 jjdelcerro
    public static void main(String[] args) throws Exception {
185
            try{
186 2142 fernando
187 8765 jjdelcerro
                    if (!validJVM()){
188
                            System.exit(-1);
189
                    }
190 6101 jaume
191 8765 jjdelcerro
                    if (args.length < 1) {
192
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
193
                    }
194 598 fernando
195 8765 jjdelcerro
                    //  Clean temporal files
196
                    Utilities.cleanUpTempFiles();
197 4607 ldiaz
198 8765 jjdelcerro
                    appName = args[0];
199 1236 fernando
200 8765 jjdelcerro
                    //Se crea el directorio de configuraci?n de la aplicaci?n
201
                    appHomeDir = System.getProperty(args[0]+".home");
202
                    if (appHomeDir == null)
203
                            appHomeDir = System.getProperty("user.home");
204
                    //System.err.println("LWS: "+args[0]+".home"+"="+appHomeDir);
205
                    appHomeDir += File.separator + args[0] + File.separator;
206
                    File parent = new File( appHomeDir );
207
                    parent.mkdirs();
208 598 fernando
209 8765 jjdelcerro
                    andamiConfigPath = appHomeDir + "andami-config.xml";
210
                    pluginsPersistencePath = appHomeDir +
211
                    "plugins-persistence.xml";
212 598 fernando
213 8765 jjdelcerro
                    // Configurar el log4j
214
                    PropertyConfigurator.configure(Launcher.class.getClassLoader()
215
                                    .getResource("log4j.properties"));
216 598 fernando
217 8765 jjdelcerro
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
218
                    RollingFileAppender fa = new RollingFileAppender(l,
219
                                    appHomeDir + args[0] + ".log", false);
220
                    fa.setMaxFileSize("512KB");
221
                    fa.setMaxBackupIndex(3);
222
                    Logger.getRootLogger().addAppender(fa);
223 598 fernando
224 8765 jjdelcerro
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
225
                    // locale
226
                    // Buscar actualizaci?nes al comenzar
227
                    //  Andami
228
                    //  Plugins
229
                    // Directorio de las extensiones
230
                    andamiConfigFromXML(andamiConfigPath);
231
                    andamiConfig.setPluginsDirectory(args[1]);
232 6101 jaume
233 8765 jjdelcerro
                    // Hacemos visibles los argumentos como una propiedad est?tica
234
                    // de plugin services para quien lo quiera usar (por ejemplo, para
235
                    // cargar un proyecto por l?nea de comandos)
236
                    PluginServices.setArguments(args);
237 7513 caballero
238 8765 jjdelcerro
                    configureLocales(args);
239 7513 caballero
240 8765 jjdelcerro
                    //Se pone el lookAndFeel
241
                    try {
242
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
243
                            if (lookAndFeel == null)
244
                                    lookAndFeel = getDefaultLookAndFeel();
245
                            UIManager.setLookAndFeel(lookAndFeel);
246
                    } catch (Exception e) {
247
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
248
                    }
249 7513 caballero
                // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
250
                // System.setSecurityManager(null);
251
             Policy.setPolicy(new Policy() {
252
             public PermissionCollection getPermissions(CodeSource codesource) {
253
                      Permissions perms = new Permissions();
254
                      perms.add(new AllPermission());
255
                      return (perms);
256
             }
257
             public void
258
                         refresh() {}
259
             });
260
261 8765 jjdelcerro
                    validate();
262
                    // Mostrar la ventana de inicio
263
                    Frame f=new Frame();
264
                    splashWindow=new MultiSplashWindow(f);
265 8885 fjp
                    validate();
266
267
                    // Ponemos los datos del proxy
268
                    String host = prefs.get("firewall.http.host", "");
269
                        String port = prefs.get("firewall.http.port", "");
270 7513 caballero
271 8885 fjp
                        System.getProperties().put("http.proxyHost", host);
272
                        System.getProperties().put("http.proxyPort", port);
273
274
                    // Ponemos el usuario y clave del proxy, si existe
275
                    String proxyUser = prefs.get("firewall.http.user",null);
276
                    String proxyPassword = prefs.get("firewall.http.password", null);
277
                        if (proxyUser != null )
278
                        {
279
                                System.getProperties().put("http.proxyUserName", proxyUser);
280
                                System.getProperties().put("http.proxyPassword", proxyPassword);
281
282
                                Authenticator.setDefault(new ProxyAuth(proxyUser,
283
                                                                proxyPassword));
284
                        } else {
285
                                Authenticator.setDefault(new ProxyAuth("", ""));
286
                        }
287 8765 jjdelcerro
                    // TODO Buscar actualizaciones de los plugins
288
                    downloadExtensions(andamiConfig.getPluginsDirectory());
289 598 fernando
290 8765 jjdelcerro
                    // Se leen los config.xml de los plugins -----++++
291
                    loadPlugins(andamiConfig.getPluginsDirectory());
292 6101 jaume
293 8765 jjdelcerro
                    // Se configura el classloader del plugin
294
                    pluginsClassLoaders();
295 598 fernando
296 8765 jjdelcerro
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
297
                    skinPlugin();
298 598 fernando
299 8765 jjdelcerro
                    //Se configura la cola de eventos
300
                    EventQueue waitQueue = new AndamiEventQueue();
301
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
302 598 fernando
303 8765 jjdelcerro
                    // Se configura la mensajer?a del plugin
304
                    pluginsMessages();
305 598 fernando
306 8765 jjdelcerro
                    // Se modifica el andami-config con los plugins nuevos
307
                    updateAndamiConfig();
308 1153 fernando
309 8765 jjdelcerro
                    // Se prepara el MainFrame para albergar las extensiones
310
                    frame = new MDIFrame();
311 598 fernando
312 8765 jjdelcerro
                    // Se configura el nombre e icono de la aplicaci?n
313
                    frameIcon();
314 598 fernando
315 8765 jjdelcerro
                    SwingUtilities.invokeAndWait(new Runnable() {
316
                            public void run() {
317
                                    frame.init();
318
                            }
319
                    });
320 598 fernando
321 8765 jjdelcerro
                    // Se instalan los controles de las extensiones de los plugins
322
                    SwingUtilities.invokeAndWait(new Runnable() {
323
                            public void run() {
324
                                    installPluginsControls();
325
                                    installPluginsMenus();
326
                                    installPluginsLabels();
327
                            }
328
                    });
329 598 fernando
330 8765 jjdelcerro
                    // Leer el fichero de persistencia
331
                    //  info de los plugins
332
                    //  bookmarks de los plugins
333
                    loadPluginsPersistence();
334 598 fernando
335 8765 jjdelcerro
                    // Se instalan los controles del skin
336
                    // Se inicializan todas las extensiones de todos los plugins
337
                    SwingUtilities.invokeAndWait(new Runnable() {
338
                            public void run() {
339
                                    initializeExtensions();
340
                                    postInitializeExtensions();
341
                            }
342
                    });
343
                    frame.setClassesExtensions(classesExtensions);
344 598 fernando
345 8765 jjdelcerro
                    // Se instalan los bookmarks de los plugins
346 1013 fjp
347 8765 jjdelcerro
                    //Se muestra el frame principal
348
                    frame.show();
349 1067 fernando
350 8765 jjdelcerro
                    // Definimos un KeyEventDispatcher global para que las extensiones
351
                    // puedan registrar sus "teclas r?pidas".
352
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
353
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
354 1067 fernando
355 8765 jjdelcerro
                    SwingUtilities.invokeAndWait(new Runnable() {
356
                            public void run() {
357
                                    frame.enableControls();
358
                            }
359
                    });
360
                    splashWindow.close();
361
            }catch(Exception e){
362
                    logger.error("excepci?n al arrancar", e);
363
                    System.exit(-1);
364
            }
365 6101 jaume
366 8765 jjdelcerro
    }
367 1067 fernando
368 4299 luisw2
        /**
369
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
370
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
371
         * @author LWS
372
         */
373
        private static void restoreMDIStatus(XMLEntity xml) {
374
                //System.err.println("Launcher: restoreMDIStatus()");
375
                if (xml == null) xml = new XMLEntity();
376
                //  restore frame size
377
                Dimension sz = new Dimension(700,580);
378
                if (xml.contains("MDIFrameSize")) {
379
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
380
                        sz = new Dimension(wh[0], wh[1]);
381
                }
382
                frame.setSize(sz);
383
                //  restore frame location
384
                Point pos = new Point(10,10);
385
                if (xml.contains("MDIFramePos")) {
386
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
387
                        pos = new Point(xy[0], xy[1]);
388
                }
389
                frame.setLocation(pos);
390 6101 jaume
391 4299 luisw2
                //  restore frame status (Maximized, minimized, etc);
392
                int state = java.awt.Frame.MAXIMIZED_BOTH;
393
                if (xml.contains("MDIFrameState")) {
394
                        state = xml.getIntProperty("MDIFrameState");
395
                }
396
                frame.setExtendedState(state);
397 1067 fernando
        }
398 6101 jaume
399 4299 luisw2
        private static XMLEntity saveMDIStatus() {
400
                XMLEntity xml = new XMLEntity();
401
                // save frame size
402
                int [] wh = new int[2];
403
                wh[0] = frame.getWidth();
404
                wh[1] = frame.getHeight();
405
                xml.putProperty("MDIFrameSize", wh);
406
                // save frame location
407
                int [] xy = new int[2];
408
                xy[0] = frame.getX();
409
                xy[1] = frame.getY();
410
                xml.putProperty("MDIFramePos", xy);
411
                // save frame status
412
                xml.putProperty("MDIFrameState", frame.getExtendedState());
413
                return xml;
414
        }
415 1067 fernando
416
        /**
417 2142 fernando
     * @return
418
     */
419
    private static boolean validJVM() {
420
        char thirdCharacter = System.getProperty("java.version").charAt(2);
421
        if (thirdCharacter < '4'){
422
            return false;
423
            }else{
424
                return true;
425
            }
426
    }
427
428
    /**
429 1067 fernando
         * DOCUMENT ME!
430
         *
431
         * @throws ConfigurationException
432
         */
433
        private static void loadPluginsPersistence() throws ConfigurationException {
434
                XMLEntity entity = persistenceFromXML();
435
436 4299 luisw2
                //System.err.println("loadPluginPersistence()");
437 6861 jaume
                for (int i = 0; i < entity.getChildrenCount(); i++) {
438 1067 fernando
                        XMLEntity plugin = entity.getChild(i);
439
                        String pName = plugin.getStringProperty(
440
                                        "com.iver.andami.pluginName");
441 4299 luisw2
                        //System.err.println("--> "+pName);
442 1381 vcaballero
                        if (pluginsServices.get(pName)!= null){
443
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
444 4299 luisw2
                        } else {
445
                                if (pName.startsWith("Andami.Launcher"))
446
                                        restoreMDIStatus(plugin);
447 1381 vcaballero
                        }
448 1067 fernando
                }
449
        }
450 6101 jaume
451 4299 luisw2
        /**
452
         * Salva la persistencia de los plugins.
453
         * @author LWS
454
         */
455
        private static void savePluginPersistence() {
456
                Iterator i = pluginsConfig.keySet().iterator();
457 1067 fernando
458 4299 luisw2
                XMLEntity entity = new XMLEntity();
459
460
                while (i.hasNext()) {
461
                        String pName = (String) i.next();
462
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
463
                        XMLEntity ent = ps.getPersistentXML();
464
465
                        if (ent != null) {
466
                                ent.putProperty("com.iver.andami.pluginName", pName);
467
                                entity.addChild(ent);
468
                        }
469
                }
470
                XMLEntity ent = saveMDIStatus();
471
                if (ent != null) {
472
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
473
                        entity.addChild(ent);
474
                }
475
                try {
476
                        persistenceToXML(entity);
477
                } catch (ConfigurationException e1) {
478
                        logger.error(Messages.getString(
479
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
480
                                e1);
481
                }
482
        }
483
484 1067 fernando
        /**
485
         * DOCUMENT ME!
486
         */
487
        private static void installPluginsLabels() {
488
                Iterator i = pluginsConfig.keySet().iterator();
489
490
                while (i.hasNext()) {
491
                        String name = (String) i.next();
492
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
493
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
494
495
                        LabelSet[] ls = pc.getLabelSet();
496
497
                        for (int j = 0; j < ls.length; j++) {
498
                                PluginClassLoader loader = ps.getClassLoader();
499
500
                                try {
501
                                        Class clase = loader.loadClass(ls[j].getClassName());
502
                                        frame.setLabels(clase, ls[j].getLabel());
503
                                } catch (ClassNotFoundException e) {
504 1173 fernando
                                        logger.error(Messages.getString("Launcher.labelset_class"),
505 1067 fernando
                                                e);
506
                                }
507 598 fernando
                        }
508 1067 fernando
                }
509
        }
510 598 fernando
511 1067 fernando
        /**
512
         * DOCUMENT ME!
513
         *
514
         * @throws MDIManagerLoadException
515
         */
516
        private static void skinPlugin() throws MDIManagerLoadException {
517
                Iterator i = pluginsConfig.keySet().iterator();
518 598 fernando
519 1067 fernando
                while (i.hasNext()) {
520
                        String name = (String) i.next();
521
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
522
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
523
524
                        if (pc.getExtensions().getSkinExtension() != null) {
525
                                if (MDIManagerFactory.getSkinExtension() != null) {
526 1236 fernando
                                        logger.warn(Messages.getString(
527
                                                        "Launcher.Dos_skin_extension"));
528 1067 fernando
                                }
529
530
                                SkinExtension se = pc.getExtensions().getSkinExtension();
531
532
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
533
534
                                Class skinClass;
535
536
                                try {
537
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
538
539 5005 jorpiell
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
540 2862 jaume
                                        // classesExtensions.put(skinClass, skinInstance);
541
                                        // jaume
542
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
543
                                        classesExtensions.put(skinClass, newExtensionDecorator);
544 1067 fernando
                                } catch (ClassNotFoundException e) {
545 1236 fernando
                                        logger.error(Messages.getString(
546
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
547 1067 fernando
                                        throw new MDIManagerLoadException(e);
548
                                } catch (InstantiationException e) {
549 1236 fernando
                                        logger.error(Messages.getString(
550
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
551
                                                e);
552 1067 fernando
                                        throw new MDIManagerLoadException(e);
553
                                } catch (IllegalAccessException e) {
554 1236 fernando
                                        logger.error(Messages.getString(
555
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
556
                                                e);
557 1067 fernando
                                        throw new MDIManagerLoadException(e);
558
                                }
559 598 fernando
                        }
560 1067 fernando
                }
561
        }
562 598 fernando
563 1067 fernando
        /**
564
         *
565
         */
566
        private static void frameIcon() {
567
                Iterator i = pluginsConfig.keySet().iterator();
568 598 fernando
569 1067 fernando
                while (i.hasNext()) {
570
                        String pName = (String) i.next();
571
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
572
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
573 598 fernando
574 1067 fernando
                        if (pc.getIcon() != null) {
575
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
576
                                                                                                                                                                 .getSrc()));
577
                                frame.setIconImage(icon.getImage());
578 1409 fernando
                                frame.setTitlePrefix(pc.getIcon().getText());
579 1067 fernando
                        }
580
                }
581
        }
582 598 fernando
583 1067 fernando
        /**
584
         *
585
         */
586
        private static void initializeExtensions() {
587 2828 fjp
                Iterator i = pluginsOrdered.iterator();
588 598 fernando
589 1067 fernando
                while (i.hasNext()) {
590
                        String pName = (String) i.next();
591 2862 jaume
            logger.debug("Initializing extensions from " + pName);
592 1067 fernando
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
593
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
594 598 fernando
595 1067 fernando
                        Extension[] exts = pc.getExtensions().getExtension();
596 598 fernando
597 1067 fernando
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
598 598 fernando
599 1067 fernando
                        for (int j = 0; j < exts.length; j++) {
600
                                if (!exts[j].getActive()) {
601
                                        continue;
602
                                }
603 598 fernando
604 1067 fernando
                                if (orderedExtensions.containsKey(exts[j])) {
605 1236 fernando
                                        logger.warn(Messages.getString(
606
                                                        "Launcher.Two_extensions_with_the_same_priority") +
607 1067 fernando
                                                exts[j].getClassName());
608
                                }
609 598 fernando
610 1067 fernando
                                orderedExtensions.put(exts[j], null);
611
                        }
612 598 fernando
613 1067 fernando
                        Iterator e = orderedExtensions.keySet().iterator();
614 598 fernando
615 1067 fernando
                        while (e.hasNext()) {
616
                                Extension extension = (Extension) e.next();
617 5005 jorpiell
                                com.iver.andami.plugins.IExtension extensionInstance;
618 598 fernando
619 1067 fernando
                                try {
620
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
621 5005 jorpiell
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
622 6101 jaume
623
                                        // CON DECORATOR
624 2862 jaume
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
625
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
626
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
627
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
628
                                        // la extensi?n original que acabamos de crear
629
                                        // 0-> Inactivo, controla la extension
630
                                        // 1-> Siempre visible
631
                                        // 2-> Invisible
632
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
633
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
634
                                        System.err.println("Loading "+extension.getClassName()+"...");
635 2828 fjp
                    // logger.debug("Initializing " + extension.getClassName());
636 5005 jorpiell
                    extensionInstance.initialize();
637 8765 jjdelcerro
                    extensions.add(extensionInstance);
638 2828 fjp
                    // logger.debug(extension.getClassName() + " initialized.");
639 598 fernando
640 1067 fernando
                                } catch (InstantiationException e1) {
641 1236 fernando
                                        logger.error(Messages.getString(
642
                                                        "Launcher.Error_instanciando_la_extension") +
643 1067 fernando
                                                extension.getClassName(), e1);
644
                                } catch (IllegalAccessException e1) {
645 1236 fernando
                                        logger.error(Messages.getString(
646
                                                        "Launcher.Error_instanciando_la_extension") +
647 1067 fernando
                                                extension.getClassName(), e1);
648
                                } catch (ClassNotFoundException e1) {
649 1236 fernando
                                        logger.error(Messages.getString(
650
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
651 1067 fernando
                                                extension.getClassName(), e1);
652
                                } catch (NoClassDefFoundError e1) {
653 1236 fernando
                                        logger.error(Messages.getString(
654
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
655 1067 fernando
                                                extension.getClassName(), e1);
656
                                }
657
                        }
658
                }
659
        }
660 598 fernando
661 8765 jjdelcerro
        private static void postInitializeExtensions() {
662
                for (int i=0;i<extensions.size();i++) {
663
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
664
                        extensionInstance.postInitialize();
665
                }
666
        }
667 1067 fernando
        /**
668
         * DOCUMENT ME!
669
         */
670
        private static void installPluginsMenus() {
671
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
672 598 fernando
673 1067 fernando
                Iterator i = pluginsConfig.keySet().iterator();
674 598 fernando
675 1067 fernando
                while (i.hasNext()) {
676
                        String pName = (String) i.next();
677
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
678
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
679 598 fernando
680 1067 fernando
                        Extension[] exts = pc.getExtensions().getExtension();
681 598 fernando
682 1067 fernando
                        for (int j = 0; j < exts.length; j++) {
683
                                if (!exts[j].getActive()) {
684
                                        continue;
685
                                }
686 598 fernando
687 3298 caballero
                                Menu[] menus = exts[j].getMenu();
688 598 fernando
689 3298 caballero
                                for (int k = 0; k < menus.length; k++) {
690 1067 fernando
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
691 3298 caballero
                                                        exts[j], menus[k]);
692 598 fernando
693 1067 fernando
                                        if (orderedMenus.containsKey(sm)) {
694 1236 fernando
                                                logger.error(Messages.getString(
695 6589 cesar
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
696
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
697 1067 fernando
                                        }
698 598 fernando
699 1067 fernando
                                        orderedMenus.put(sm, null);
700
                                }
701
                        }
702 598 fernando
703 1067 fernando
                        // Se instalan las extensiones de MDI
704
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
705 598 fernando
706 1067 fernando
                        if (skinExt != null) {
707
                                Menu[] menu = skinExt.getMenu();
708 598 fernando
709 1067 fernando
                                for (int k = 0; k < menu.length; k++) {
710
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
711
                                                        skinExt, menu[k]);
712 598 fernando
713 1067 fernando
                                        if (orderedMenus.containsKey(sm)) {
714 1236 fernando
                                                logger.error(Messages.getString(
715
                                                                "Launcher.Two_menus_with_the_same_position") +
716 1067 fernando
                                                        skinExt.getClassName());
717
                                        }
718 598 fernando
719 1067 fernando
                                        orderedMenus.put(sm, null);
720
                                }
721
                        }
722
                }
723 598 fernando
724 1067 fernando
                //Se itera por los menus ordenados
725
                Iterator e = orderedMenus.keySet().iterator();
726 598 fernando
727 1067 fernando
                // Se ordenan los menues
728
                while (e.hasNext()) {
729
                        try {
730
                                SortableMenu sm = (SortableMenu) e.next();
731 598 fernando
732 1067 fernando
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
733
                        } catch (ClassNotFoundException ex) {
734 1236 fernando
                                logger.error(Messages.getString(
735
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
736 1067 fernando
                        }
737
                }
738
        }
739 598 fernando
740 1067 fernando
        /**
741 6589 cesar
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
742 6101 jaume
         * The order in which they are shown is determined here.
743 1067 fernando
         */
744
        private static void installPluginsControls() {
745
                Iterator i = pluginsConfig.keySet().iterator();
746 598 fernando
747 2112 fernando
                HashMap extensionPluginServices = new HashMap();
748
                HashMap extensionPluginConfig = new HashMap();
749
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
750 6101 jaume
751 5421 cesar
                // First of all, sort the extensions.
752
                // We need to iterate on the plugins, and iterate on each plugin's extensions
753 6101 jaume
                // (each plugin may contain one or more extensions)
754 5421 cesar
                while (i.hasNext()) { // iterate on the plugins
755
                        String pName = (String) i.next();
756
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
757
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
758 6101 jaume
759 5421 cesar
                        Extension[] exts = pc.getExtensions().getExtension();
760 6101 jaume
761 5421 cesar
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
762
                                if (exts[j].getActive()) {
763
                                        if (orderedExtensions.containsKey(exts[j])) {
764
                                                logger.error(Messages.getString(
765
                                                "Launcher.Two_extensions_with_the_same_priority") +
766
                                                exts[j].getClassName());
767 1067 fernando
                                        }
768 6101 jaume
769 5421 cesar
                                        orderedExtensions.put(exts[j], null);
770
                                        extensionPluginServices.put(exts[j], ps);
771
                                        extensionPluginConfig.put(exts[j], pc);
772 1067 fernando
                                }
773 5421 cesar
                        }
774 2112 fernando
                }
775 598 fernando
776 5421 cesar
                TreeMap orderedTools = new TreeMap(new ToolComparator());
777
                Iterator e = orderedExtensions.keySet().iterator();
778 6101 jaume
779 6614 cesar
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
780
                // and load the  combo-scales and combo-buttons for the status bar
781 5421 cesar
                while (e.hasNext()) {
782
                        Extension ext = (Extension) e.next();
783 6101 jaume
784 5421 cesar
                        ToolBar[] toolbars = ext.getToolBar();
785 6101 jaume
786 6589 cesar
                        // get tools from toolbars
787 5421 cesar
                        for (int k = 0; k < toolbars.length; k++) {
788
                                ActionTool[] tools = toolbars[k].getActionTool();
789 6101 jaume
790 5421 cesar
                                for (int t = 0; t < tools.length; t++) {
791 6589 cesar
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
792 5421 cesar
                                                        toolbars[k], tools[t]);
793 6589 cesar
                                        orderedTools.put(sm, null);
794 5421 cesar
                                }
795 6101 jaume
796 5421 cesar
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
797 6101 jaume
798 5421 cesar
                                for (int t = 0; t < sTools.length; t++) {
799 6589 cesar
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
800 5421 cesar
                                                        toolbars[k], sTools[t]);
801 6589 cesar
                                        orderedTools.put(sm, null);
802 5421 cesar
                                }
803
                        }
804 6861 jaume
805 6589 cesar
                        // get controls for statusBar
806
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
807
                        PluginClassLoader loader = ps.getClassLoader();
808 6861 jaume
809 6589 cesar
                        //ArrayList componentList = new ArrayList();
810
                        ComboScale[] comboScaleArray = ext.getComboScale();
811
                        for (int k=0; k < comboScaleArray.length; k++) {
812
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
813 6619 cesar
                                String label = comboScaleArray[k].getLabel();
814
                                if (label!=null)
815
                                        combo.setLabel(label);
816 6623 cesar
                                String name = comboScaleArray[k].getName();
817
                                if (name!=null)
818
                                        combo.setName(name);
819 6589 cesar
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
820
                                long[] elements = new long[elementsString.length];
821
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
822
                                        try {
823
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
824
                                        }
825
                                        catch (NumberFormatException nfex1) {
826 6918 cesar
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
827 6589 cesar
                                                elements[currentElem] = 0;
828
                                        }
829
                                }
830
                                combo.setItems(elements);
831
                                try {
832
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
833
                                        combo.setScale(value);
834
                                }
835
                                catch (NumberFormatException nfex2) {
836 6918 cesar
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
837 6589 cesar
                                }
838
                                try {
839 6614 cesar
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
840 6589 cesar
                                } catch (ClassNotFoundException e1) {
841
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
842
                                }
843
                        }
844
845
                        ComboButton[] comboButtonArray = ext.getComboButton();
846
                        for (int k=0; k < comboButtonArray.length; k++) {
847
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
848
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
849 6623 cesar
                                String name = comboButtonArray[k].getName();
850
                                if (name!=null)
851
                                        combo.setName(name);
852 6589 cesar
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
853
                                        ComboButtonElement element = elementList[currentElement];
854
                                        ImageIcon icon;
855
                                        URL iconLocation = loader.getResource(element.getIcon());
856
                                        if (iconLocation==null)
857
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
858
                                        else {
859
                                                icon = new ImageIcon(iconLocation);
860
                                                JButton button = new JButton(icon);
861
                                                combo.addButton(button);
862
                                                button.setActionCommand(element.getActionCommand());
863
                                        }
864
                                }
865
                                try {
866 6614 cesar
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
867 6589 cesar
                                } catch (ClassNotFoundException e1) {
868
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
869
                                }
870
                        }
871 5421 cesar
                }
872 598 fernando
873 6589 cesar
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
874 5421 cesar
                i = pluginsConfig.keySet().iterator();
875
                while (i.hasNext()) {
876
                        String pName = (String) i.next();
877
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
878
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
879 6101 jaume
880 5421 cesar
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
881 6101 jaume
882 5421 cesar
                        if (skinExt != null) {
883
                                ToolBar[] toolbars = skinExt.getToolBar();
884 6101 jaume
885 2112 fernando
                                for (int k = 0; k < toolbars.length; k++) {
886
                                        ActionTool[] tools = toolbars[k].getActionTool();
887 6101 jaume
888 2112 fernando
                                        for (int t = 0; t < tools.length; t++) {
889 6589 cesar
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
890 3298 caballero
                                                                toolbars[k], tools[t]);
891 6589 cesar
                                                orderedTools.put(stb,null);
892 2112 fernando
                                        }
893 6101 jaume
894 2112 fernando
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
895 6101 jaume
896 2112 fernando
                                        for (int t = 0; t < sTools.length; t++) {
897 6589 cesar
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
898 3298 caballero
                                                                toolbars[k], sTools[t]);
899 6589 cesar
                                                orderedTools.put(stb,null);
900 1067 fernando
                                        }
901
                                }
902 2112 fernando
                        }
903 6589 cesar
                        // Install popup menus
904 5421 cesar
                        PopupMenus pus = pc.getPopupMenus();
905 6101 jaume
906 5421 cesar
                        if (pus != null) {
907
                                PopupMenu[] menus = pus.getPopupMenu();
908 6101 jaume
909 5421 cesar
                                for (int j = 0; j < menus.length; j++) {
910
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
911 1067 fernando
                                }
912
                        }
913 5421 cesar
                }
914 3298 caballero
915 6589 cesar
                // loop on the ordered extension list, to add them to the interface in an ordered way
916 6101 jaume
                Iterator t = orderedTools.keySet().iterator();
917 5421 cesar
                while (t.hasNext()) {
918
                        try {
919 6589 cesar
                                SortableTool stb = (SortableTool) t.next();
920 5421 cesar
                                if (stb.actiontool!=null)
921
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
922
                                else
923
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
924
                        } catch (ClassNotFoundException ex) {
925
                                logger.error(Messages.getString(
926
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
927 3298 caballero
                        }
928 5421 cesar
                }
929 1067 fernando
        }
930 598 fernando
931 1067 fernando
        /**
932 6861 jaume
         * Adds new plugins to the the andami-config file.
933 1067 fernando
         */
934
        private static void updateAndamiConfig() {
935
                HashSet olds = new HashSet();
936 598 fernando
937 1067 fernando
                Plugin[] plugins = andamiConfig.getPlugin();
938 598 fernando
939 1067 fernando
                for (int i = 0; i < plugins.length; i++) {
940
                        olds.add(plugins[i].getName());
941
                }
942 598 fernando
943 1067 fernando
                Iterator i = pluginsServices.values().iterator();
944 598 fernando
945 1067 fernando
                while (i.hasNext()) {
946
                        PluginServices ps = (PluginServices) i.next();
947 598 fernando
948 1067 fernando
                        if (!olds.contains(ps.getPluginName())) {
949
                                Plugin p = new Plugin();
950
                                p.setName(ps.getPluginName());
951
                                p.setUpdate(false);
952 598 fernando
953 1067 fernando
                                andamiConfig.addPlugin(p);
954
                        }
955
                }
956
        }
957 598 fernando
958 1067 fernando
        /**
959
         * DOCUMENT ME!
960
         */
961
        private static void pluginsClassLoaders() {
962
                HashSet instalados = new HashSet();
963 598 fernando
964 1067 fernando
                // Se itera hasta que est?n todos instalados
965
                while (instalados.size() != pluginsConfig.size()) {
966
                        boolean circle = true;
967 598 fernando
968 1067 fernando
                        //Hacemos una pasada por todos los plugins
969
                        Iterator i = pluginsConfig.keySet().iterator();
970 598 fernando
971 1067 fernando
                        while (i.hasNext()) {
972
                                String pluginName = (String) i.next();
973
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
974 598 fernando
975 1067 fernando
                                if (instalados.contains(pluginName)) {
976
                                        continue;
977
                                }
978 598 fernando
979 1067 fernando
                                //Se obtienen las dependencias y sus class loaders
980
                                boolean ready = true;
981
                                Depends[] dependencies = config.getDepends();
982
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
983 598 fernando
984 1067 fernando
                                for (int j = 0; j < dependencies.length; j++) {
985
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
986 1236 fernando
                                                logger.error(Messages.getString(
987
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
988 1067 fernando
                                                        pluginName + ": " +
989 1153 fernando
                                                        dependencies[j].getPluginName());
990 598 fernando
991 1067 fernando
                                                continue;
992
                                        }
993 598 fernando
994 1067 fernando
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
995
                                                ready = false;
996
                                        } else {
997
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
998
                                        }
999
                                }
1000 598 fernando
1001 1067 fernando
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1002
                                if (!ready) {
1003
                                        continue;
1004
                                }
1005 598 fernando
1006 1067 fernando
                                //Se genera el class loader
1007 1110 fernando
                                String jardir = config.getLibraries().getLibraryDir();
1008
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1009
                                                File.separator + pluginName + File.separator + jardir);
1010
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1011 1236 fernando
                                                        public boolean accept(File pathname) {
1012
                                                                return (pathname.getName().toUpperCase()
1013
                                                                                                .endsWith(".JAR")) ||
1014
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1015
                                                        }
1016
                                                });
1017
1018 1110 fernando
                                URL[] urls = new URL[jarFiles.length];
1019 1236 fernando
1020 1110 fernando
                                for (int j = 0; j < jarFiles.length; j++) {
1021 1067 fernando
                                        try {
1022 1110 fernando
                                                urls[j] = new URL("file:" + jarFiles[j]);
1023 1067 fernando
                                        } catch (MalformedURLException e) {
1024 1236 fernando
                                                logger.error(Messages.getString(
1025
                                                                "Launcher.No_se_puede_acceder_a") +
1026 1110 fernando
                                                        jarFiles[j]);
1027 1067 fernando
                                        }
1028
                                }
1029 598 fernando
1030 1067 fernando
                                PluginClassLoader loader;
1031 598 fernando
1032 1067 fernando
                                try {
1033
                                        loader = new PluginClassLoader(urls,
1034
                                                        andamiConfig.getPluginsDirectory() +
1035
                                                        File.separator + pluginName,
1036
                                                        Launcher.class.getClassLoader(), loaders);
1037 598 fernando
1038 1067 fernando
                                        PluginServices ps = new PluginServices(loader);
1039 598 fernando
1040 1067 fernando
                                        pluginsServices.put(ps.getPluginName(), ps);
1041 598 fernando
1042 1067 fernando
                                        instalados.add(pluginName);
1043 6101 jaume
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1044 2828 fjp
                    // inicializar los plugins
1045
                    pluginsOrdered.add(pluginName);
1046 598 fernando
1047 1067 fernando
                                        circle = false;
1048
                                } catch (IOException e) {
1049 1236 fernando
                                        logger.error(Messages.getString(
1050
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1051 1067 fernando
                                        pluginsConfig.remove(pluginName);
1052
                                        i = pluginsConfig.keySet().iterator();
1053
                                }
1054
                        }
1055 598 fernando
1056 1067 fernando
                        if (circle) {
1057 1236 fernando
                                logger.error(Messages.getString(
1058
                                                "Launcher.Hay_dependencias_circulares"));
1059 598 fernando
1060 1067 fernando
                                break;
1061
                        }
1062
                }
1063 598 fernando
1064 1067 fernando
                //Se eliminan los plugins que no fueron instalados
1065
                Iterator i = pluginsConfig.keySet().iterator();
1066 598 fernando
1067 1067 fernando
                while (i.hasNext()) {
1068
                        String pluginName = (String) i.next();
1069
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1070
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1071 598 fernando
1072 1067 fernando
                        if (ps == null) {
1073
                                pluginsConfig.remove(pluginName);
1074
                                i = pluginsConfig.keySet().iterator();
1075
                        }
1076 6101 jaume
                }
1077 1067 fernando
        }
1078 598 fernando
1079 1067 fernando
        /**
1080
         * DOCUMENT ME!
1081
         */
1082
        private static void pluginsMessages() {
1083 6101 jaume
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1084 4909 cesar
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1085 6101 jaume
                 * I keep this workaround for the moment.
1086 4909 cesar
                 */
1087
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1088
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1089
                if (config.getResourceBundle() != null) {
1090
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1091
                }
1092
1093 1067 fernando
                //Iteramos por todos los plugins
1094
                Iterator i = pluginsConfig.keySet().iterator();
1095 6101 jaume
1096 1067 fernando
                while (i.hasNext()) {
1097
                        String pluginName = (String) i.next();
1098 4909 cesar
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1099
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1100
                                ps = (PluginServices) pluginsServices.get(pluginName);
1101 6101 jaume
1102 4909 cesar
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1103
                                        // add the locale files associated with the plugin
1104
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1105
                                }
1106 1067 fernando
                        }
1107
                }
1108
        }
1109 598 fernando
1110 1067 fernando
        /**
1111
         * DOCUMENT ME!
1112
         *
1113
         * @param name DOCUMENT ME!
1114
         *
1115
         * @return DOCUMENT ME!
1116
         */
1117
        static PluginServices getPluginServices(String name) {
1118
                return (PluginServices) pluginsServices.get(name);
1119
        }
1120 598 fernando
1121 1067 fernando
        /**
1122
         * DOCUMENT ME!
1123
         *
1124
         * @return DOCUMENT ME!
1125
         */
1126
        static String getPluginsDir() {
1127
                return andamiConfig.getPluginsDirectory();
1128
        }
1129 598 fernando
1130 1067 fernando
        /**
1131
         * DOCUMENT ME!
1132
         *
1133
         * @param s DOCUMENT ME!
1134
         */
1135
        static void setPluginsDir(String s) {
1136
                andamiConfig.setPluginsDirectory(s);
1137
        }
1138 598 fernando
1139 1067 fernando
        /**
1140
         * DOCUMENT ME!
1141
         *
1142
         * @return DOCUMENT ME!
1143
         */
1144
        static MDIFrame getMDIFrame() {
1145
                return frame;
1146
        }
1147 598 fernando
1148 1067 fernando
        /**
1149
         * DOCUMENT ME!
1150
         *
1151
         * @param pluginsDirectory
1152
         */
1153
        private static void loadPlugins(String pluginsDirectory) {
1154
                File pDir = new File(pluginsDirectory);
1155 598 fernando
1156 1067 fernando
                if (!pDir.exists()) {
1157
                        return;
1158
                }
1159 598 fernando
1160 1067 fernando
                File[] pluginDirs = pDir.listFiles();
1161 598 fernando
1162 1067 fernando
                for (int i = 0; i < pluginDirs.length; i++) {
1163
                        if (pluginDirs[i].isDirectory()) {
1164
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1165
                                                File.separator + "config.xml");
1166 598 fernando
1167 1067 fernando
                                try {
1168 8765 jjdelcerro
                                        FileInputStream is = new FileInputStream(configXml);
1169
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1170
                                        if (xml==null) {
1171
                                                // the encoding was not correctly detected, use system default
1172
                                                xml = new FileReader(configXml);
1173
                                        }
1174
                                        else {
1175
                                                // use a buffered reader to improve performance
1176
                                                xml = new BufferedReader(xml);
1177
                                        }
1178 1067 fernando
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1179
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1180
                                } catch (FileNotFoundException e) {
1181 1236 fernando
                                        logger.info(Messages.getString(
1182
                                                        "Launcher.Ignorando_el_directorio") +
1183 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1184 1173 fernando
                                                Messages.getString("Launcher.config_no_encontrado"));
1185 1067 fernando
                                } catch (MarshalException e) {
1186 1236 fernando
                                        logger.info(Messages.getString(
1187
                                                        "Launcher.Ignorando_el_directorio") +
1188 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1189 1173 fernando
                                                Messages.getString("Launcher.config_mal_formado"), e);
1190 1067 fernando
                                } catch (ValidationException e) {
1191 1236 fernando
                                        logger.info(Messages.getString(
1192
                                                        "Launcher.Ignorando_el_directorio") +
1193 1067 fernando
                                                pluginDirs[i].getAbsolutePath() +
1194 1173 fernando
                                                Messages.getString("Launcher.config_mal_formado"), e);
1195 1067 fernando
                                }
1196
                        }
1197
                }
1198
        }
1199 598 fernando
1200 1067 fernando
        /**
1201
         * DOCUMENT ME!
1202
         *
1203
         * @param language
1204
         * @param country
1205
         * @param variant
1206
         *
1207
         * @return DOCUMENT ME!
1208
         */
1209
        private static Locale getLocale(String language, String country,
1210
                String variant) {
1211
                if (variant != null) {
1212
                        return new Locale(language, country, variant);
1213
                } else if (country != null) {
1214
                        return new Locale(language, country);
1215
                } else if (language != null) {
1216
                        return new Locale(language);
1217
                } else {
1218
                        return new Locale("es");
1219
                }
1220
        }
1221 598 fernando
1222 1067 fernando
        /**
1223
         * DOCUMENT ME!
1224
         *
1225
         * @param file DOCUMENT ME!
1226
         *
1227
         * @throws IOException DOCUMENT ME!
1228
         * @throws MarshalException DOCUMENT ME!
1229
         * @throws ValidationException DOCUMENT ME!
1230
         */
1231
        private static void andamiConfigToXML(String file)
1232
                throws IOException, MarshalException, ValidationException {
1233
                File xml = new File(file);
1234
                File parent = xml.getParentFile();
1235
                parent.mkdirs();
1236 598 fernando
1237 1067 fernando
                FileWriter writer = new FileWriter(xml);
1238
                andamiConfig.marshal(writer);
1239
        }
1240 598 fernando
1241 1067 fernando
        /**
1242
         * DOCUMENT ME!
1243
         *
1244
         * @param file DOCUMENT ME!
1245
         *
1246
         * @throws ConfigurationException DOCUMENT ME!
1247
         */
1248
        private static void andamiConfigFromXML(String file)
1249
                throws ConfigurationException {
1250
                File xml = new File(file);
1251 598 fernando
1252 1067 fernando
                //Si no existe se ponen los valores por defecto
1253
                if (!xml.exists()) {
1254
                        andamiConfig = new AndamiConfig();
1255 598 fernando
1256 1067 fernando
                        Andami andami = new Andami();
1257
                        andami.setUpdate(true);
1258
                        andamiConfig.setAndami(andami);
1259
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1260
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1261
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1262 598 fernando
1263 1067 fernando
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1264
                         {
1265 7682 luisw2
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1266
                                                + "extensiones").getAbsolutePath());
1267 1067 fernando
                        } else {
1268
                                andamiConfig.setPluginsDirectory(new File(appName +
1269
                                                File.separator + "extensiones").getAbsolutePath());
1270
                        }
1271 598 fernando
1272 1067 fernando
                        andamiConfig.setPlugin(new Plugin[0]);
1273
                } else {
1274
                        //Se lee la configuraci?n
1275
                        FileReader reader;
1276 598 fernando
1277 1067 fernando
                        try {
1278
                                reader = new FileReader(xml);
1279
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1280
                        } catch (FileNotFoundException e) {
1281
                                throw new ConfigurationException(e);
1282
                        } catch (MarshalException e) {
1283
                                throw new ConfigurationException(e);
1284
                        } catch (ValidationException e) {
1285
                                throw new ConfigurationException(e);
1286
                        }
1287
                }
1288
        }
1289 598 fernando
1290 1067 fernando
        /**
1291
         * DOCUMENT ME!
1292
         *
1293
         * @return DOCUMENT ME!
1294
         *
1295
         * @throws ConfigurationException DOCUMENT ME!
1296
         */
1297
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1298
                File xml = new File(pluginsPersistencePath);
1299 598 fernando
1300 1067 fernando
                if (xml.exists()) {
1301
                        FileReader reader;
1302 598 fernando
1303 1067 fernando
                        try {
1304
                                reader = new FileReader(xml);
1305 598 fernando
1306 1067 fernando
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1307 598 fernando
1308 1067 fernando
                                return new XMLEntity(tag);
1309
                        } catch (FileNotFoundException e) {
1310
                                throw new ConfigurationException(e);
1311
                        } catch (MarshalException e) {
1312
                                throw new ConfigurationException(e);
1313
                        } catch (ValidationException e) {
1314
                                throw new ConfigurationException(e);
1315
                        }
1316
                } else {
1317
                        return new XMLEntity();
1318
                }
1319
        }
1320 598 fernando
1321 1067 fernando
        /**
1322
         * DOCUMENT ME!
1323
         *
1324
         * @param entity DOCUMENT ME!
1325
         *
1326
         * @throws ConfigurationException DOCUMENT ME!
1327
         */
1328
        private static void persistenceToXML(XMLEntity entity)
1329
                throws ConfigurationException {
1330
                File xml = new File(pluginsPersistencePath);
1331 598 fernando
1332 1067 fernando
                FileWriter writer;
1333 598 fernando
1334 1067 fernando
                try {
1335
                        writer = new FileWriter(xml);
1336
                        entity.getXmlTag().marshal(writer);
1337
                } catch (FileNotFoundException e) {
1338
                        throw new ConfigurationException(e);
1339
                } catch (MarshalException e) {
1340
                        throw new ConfigurationException(e);
1341
                } catch (ValidationException e) {
1342
                        throw new ConfigurationException(e);
1343
                } catch (IOException e) {
1344
                        throw new ConfigurationException(e);
1345
                }
1346
        }
1347 598 fernando
1348 1067 fernando
        /**
1349
         * Devuelve un array con los directorios de los plugins
1350
         *
1351
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1352
         *                   todos los directorios de los plugins
1353
         *
1354
         * @return ArrayList con los directorios
1355
         */
1356
        private String[] getLocales(File dirExt) {
1357
                ArrayList types = new ArrayList();
1358
                File[] files = dirExt.listFiles();
1359 598 fernando
1360 1067 fernando
                for (int i = 0; i < files.length; i++) {
1361
                        if (files[i].isDirectory()) {
1362
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1363
                                                        public boolean accept(File dir, String fileName) {
1364
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1365
                                                        }
1366
                                                });
1367 598 fernando
1368 1067 fernando
                                for (int j = 0; j < textFile.length; j++) {
1369
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1370
                                        s = s.replaceAll(".properties", "");
1371
                                        s = s.trim();
1372 598 fernando
1373 1067 fernando
                                        if (!types.contains(s)) {
1374
                                                types.add(s);
1375
                                        }
1376
                                }
1377
                        }
1378
                }
1379 598 fernando
1380 1067 fernando
                return (String[]) types.toArray(new String[0]);
1381
        }
1382 598 fernando
1383 1067 fernando
        /**
1384
         * DOCUMENT ME!
1385
         *
1386
         * @return Returns the frame.
1387
         */
1388
        static MDIFrame getFrame() {
1389
                return frame;
1390
        }
1391 598 fernando
1392 1067 fernando
        /**
1393
         * Secuencia de cerrado de Andami
1394
         */
1395
        public static void closeApplication() {
1396
                //Configuraci?n de Andami
1397
                try {
1398
                        andamiConfigToXML(andamiConfigPath);
1399
                } catch (MarshalException e) {
1400 1236 fernando
                        logger.error(Messages.getString(
1401
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1402 1067 fernando
                } catch (ValidationException e) {
1403 1236 fernando
                        logger.error(Messages.getString(
1404
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1405 1067 fernando
                } catch (IOException e) {
1406 1236 fernando
                        logger.error(Messages.getString(
1407
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1408 1067 fernando
                }
1409 598 fernando
1410 1067 fernando
                //Persistencia de los plugins
1411 4299 luisw2
                savePluginPersistence();
1412 6101 jaume
1413 5005 jorpiell
                //Finalize all the extensions
1414
                finalizeExtensions();
1415 6101 jaume
1416 3707 jaume
                // Clean any temp data created
1417
                Utilities.cleanUpTempFiles();
1418 6101 jaume
1419 1236 fernando
                //Para la depuraci?n de memory leaks
1420
                System.gc();
1421
1422
        System.exit(0);
1423 1067 fernando
        }
1424 6101 jaume
1425 5005 jorpiell
        /**
1426 8765 jjdelcerro
         * Exectutes the terminate method for all the extensions, in the reverse
1427
         * order they were initialized
1428 5005 jorpiell
         *
1429
         */
1430
        private static void finalizeExtensions() {
1431 8765 jjdelcerro
                for (int i=extensions.size()-1; i>=0; i--) {
1432
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1433
                        extensionInstance.terminate();
1434 6101 jaume
                }
1435 5005 jorpiell
        }
1436 598 fernando
1437 5005 jorpiell
1438 1067 fernando
        /**
1439
         * DOCUMENT ME!
1440
         *
1441
         * @return DOCUMENT ME!
1442
         */
1443
        static HashMap getClassesExtensions() {
1444
                return classesExtensions;
1445
        }
1446 598 fernando
1447 1067 fernando
        /**
1448
         * DOCUMENT ME!
1449
         *
1450 2332 fjp
         * @param extDir DOCUMENT ME!
1451
         */
1452
        private static void downloadExtensions(String extDir) {
1453
                java.util.Date fechaActual = null;
1454
1455
                try {
1456
                        if (System.getProperty("javawebstart.version") != null) {
1457
                                //Obtenemos la URL del servidor
1458
                                BasicService bs = (BasicService) ServiceManager.lookup(
1459
                                                "javax.jnlp.BasicService");
1460
                                URL baseURL = bs.getCodeBase();
1461
1462
                                //Se descargan las extensiones
1463 8765 jjdelcerro
                                MultiSplashWindow.process(5,
1464 2332 fjp
                                        "Descargando las extensiones desde " + baseURL + " a " +
1465
                                        extDir);
1466
1467
                                URL url = new URL(baseURL + "extensiones.zip");
1468
                                URLConnection connection = url.openConnection();
1469
1470
                                System.out.println(url.toExternalForm() + ":");
1471
                                System.out.println("  Content Type: " +
1472
                                        connection.getContentType());
1473
                                System.out.println("  Content Length: " +
1474
                                        connection.getContentLength());
1475
                                System.out.println("  Last Modified: " +
1476
                                        new Date(connection.getLastModified()));
1477
                                System.out.println("  Expiration: " +
1478
                                        connection.getExpiration());
1479
                                System.out.println("  Content Encoding: " +
1480
                                        connection.getContentEncoding());
1481
1482
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1483
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1484
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1485
                                // nos bajamos nada.
1486
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1487
1488
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1489
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1490
                                File destDir = new File(extDir);
1491
1492
                                if (!destDir.exists()) {
1493
                                        // Creamos gvSIG
1494
                                        destDir.getParentFile().mkdir();
1495
1496
                                        if (!destDir.mkdir()) {
1497
                                                System.err.println("Imposible crear el directorio " +
1498
                                                        destDir.getAbsolutePath());
1499
                                        }
1500
                                }
1501
1502
                                File timeFile = new File(destDir.getParent() + File.separator +
1503
                                                "timeStamp.properties");
1504
1505
                                if (!timeFile.exists()) {
1506
                                        timeFile.createNewFile();
1507
                                }
1508
1509
                                FileInputStream inAux = new FileInputStream(timeFile);
1510
                                Properties prop = new Properties();
1511
                                prop.load(inAux);
1512
                                inAux.close();
1513
1514
                                if (prop.getProperty("timestamp") != null) {
1515
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1516
                                                                "timestamp"));
1517
1518
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1519
                                                System.out.println("No hay nueva actualizaci?n");
1520 7513 caballero
                        logger.debug("No hay nueva actualizaci?n -> Return");
1521
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1522
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1523 2332 fjp
1524
                                                return;
1525
                                        }
1526
1527
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1528
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1529
                                } else {
1530
                                        System.out.println("El timeStamp no est? escrito en " +
1531
                                                timeFile.getAbsolutePath());
1532
                                }
1533
1534 7513 caballero
                                InputStream stream = url.openStream();
1535
                File temp = File.createTempFile("gvsig", ".zip");
1536 2332 fjp
1537 7513 caballero
                logger.debug(temp.getAbsolutePath());
1538 2332 fjp
1539 7513 caballero
                temp.deleteOnExit();
1540
                FileOutputStream file = new FileOutputStream(temp);
1541 2332 fjp
1542 7513 caballero
                byte[] lt_read = new byte[1];
1543 2332 fjp
1544 7513 caballero
                while (stream.read(lt_read) > 0)
1545
                  file.write(lt_read);
1546 2332 fjp
1547 8765 jjdelcerro
                                stream.close();
1548 7513 caballero
                stream = null;
1549
                file.close();
1550
                file = null;
1551 2332 fjp
1552 7513 caballero
                System.gc();
1553 2332 fjp
1554 7513 caballero
                logger.debug("Ha creado el fichero ZIP");
1555 2332 fjp
                                //Se extrae el zip
1556 8765 jjdelcerro
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1557 2332 fjp
1558
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1559
1560
                                Date fechaDir = new Date(destDir.lastModified());
1561
                                System.out.println("Fecha del directorio " + extDir + " = " +
1562
                                        fechaDir.toString());
1563
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1564
1565
                                // Si todo ha ido bien, guardamos el timestamp.
1566
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1567
                                // XMLEntity xml=ps.getPersistentXML();
1568
                                fechaActual = new java.util.Date();
1569
1570
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1571
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1572
                                prop.store(outAux, "last download");
1573
                                outAux.close();
1574
                                System.out.println("Fecha actual guardada: " +
1575
                                        fechaActual.toGMTString());
1576
1577
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1578
                                   ps.setPresistentXML(xml); */
1579
                        }
1580
                } catch (IOException e) {
1581
                        NotificationManager.addError("", e);
1582
                } catch (UnavailableServiceException e) {
1583
                        NotificationManager.addError("", e);
1584
                } catch (SecurityException e) {
1585
                        System.err.println("No se puede escribir el timeStamp " +
1586
                                fechaActual.toGMTString());
1587
                        NotificationManager.addError("", e);
1588
                }
1589
        }
1590
1591
        /**
1592
         * DOCUMENT ME!
1593
         *
1594 1067 fernando
         * @return DOCUMENT ME!
1595
         */
1596
        private static Extensions[] getExtensions() {
1597
                ArrayList array = new ArrayList();
1598
                Iterator iter = pluginsConfig.values().iterator();
1599
1600
                while (iter.hasNext()) {
1601
                        array.add(((PluginConfig) iter.next()).getExtensions());
1602 735 vcaballero
                }
1603 1067 fernando
1604
                return (Extensions[]) array.toArray(new Extensions[0]);
1605 735 vcaballero
        }
1606 1067 fernando
1607
        /**
1608
         * DOCUMENT ME!
1609
         *
1610
         * @return DOCUMENT ME!
1611
         */
1612
        public static HashMap getPluginConfig() {
1613 735 vcaballero
                return pluginsConfig;
1614
        }
1615 1067 fernando
1616
        /**
1617
         * DOCUMENT ME!
1618
         *
1619
         * @param s DOCUMENT ME!
1620
         *
1621
         * @return DOCUMENT ME!
1622
         */
1623
        public static Extension getExtension(String s) {
1624
                Extensions[] exts = getExtensions();
1625
1626
                for (int i = 0; i < exts.length; i++) {
1627
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1628
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1629 735 vcaballero
                                        return exts[i].getExtension(j);
1630
                                }
1631 1067 fernando
                        }
1632 735 vcaballero
                }
1633 1067 fernando
1634 735 vcaballero
                return null;
1635
        }
1636 1067 fernando
1637
        /**
1638
         * DOCUMENT ME!
1639
         *
1640
         * @return DOCUMENT ME!
1641
         */
1642
        public static AndamiConfig getAndamiConfig() {
1643 794 vcaballero
                return andamiConfig;
1644
        }
1645 1236 fernando
1646 1067 fernando
        /**
1647
         * DOCUMENT ME!
1648
         *
1649
         * @author $author$
1650
         * @version $Revision$
1651
         */
1652 1153 fernando
        private static class ExtensionComparator implements Comparator {
1653 1067 fernando
                /**
1654
                 * DOCUMENT ME!
1655
                 *
1656
                 * @param o1 DOCUMENT ME!
1657
                 * @param o2 DOCUMENT ME!
1658
                 *
1659
                 * @return DOCUMENT ME!
1660
                 */
1661
                public int compare(Object o1, Object o2) {
1662
                        Extension e1 = (Extension) o1;
1663
                        Extension e2 = (Extension) o2;
1664
1665
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1666
                                return -1;
1667 735 vcaballero
                        }
1668 1067 fernando
1669
                        if (e1.hasPriority() && !e2.hasPriority()) {
1670 6696 cesar
                                return Integer.MIN_VALUE;
1671 1067 fernando
                        }
1672
1673
                        if (e2.hasPriority() && !e1.hasPriority()) {
1674
                                return Integer.MAX_VALUE;
1675
                        }
1676
1677 2112 fernando
                        if (e1.getPriority() != e2.getPriority()){
1678
                                return e2.getPriority() - e1.getPriority();
1679
                        }else{
1680
                                return (e2.toString().compareTo(e1.toString()));
1681
                        }
1682 735 vcaballero
                }
1683 1067 fernando
        }
1684
1685
        /**
1686
         * DOCUMENT ME!
1687
         */
1688 1153 fernando
        private static class MenuComparator implements Comparator {
1689 1067 fernando
                private static ExtensionComparator extComp = new ExtensionComparator();
1690
1691
                /**
1692
                 * DOCUMENT ME!
1693
                 *
1694
                 * @param o1 DOCUMENT ME!
1695
                 * @param o2 DOCUMENT ME!
1696
                 *
1697
                 * @return DOCUMENT ME!
1698
                 */
1699
                public int compare(Object o1, Object o2) {
1700
                        SortableMenu e1 = (SortableMenu) o1;
1701
                        SortableMenu e2 = (SortableMenu) o2;
1702
1703
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1704
                                if (e1.extension instanceof SkinExtensionType) {
1705
                                        return 1;
1706
                                } else if (e2.extension instanceof SkinExtensionType) {
1707
                                        return -1;
1708
                                } else {
1709
                                        return extComp.compare(e1.extension, e2.extension);
1710
                                }
1711
                        }
1712
1713
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1714 6696 cesar
                                return Integer.MIN_VALUE;
1715 1067 fernando
                        }
1716
1717
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1718
                                return Integer.MAX_VALUE;
1719
                        }
1720 6696 cesar
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1721
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1722
                                return e1.menu.getPosition() - e2.menu.getPosition();
1723
                        }else{
1724
                                return (e1.toString().compareTo(e2.toString()));
1725
                        }
1726 735 vcaballero
                }
1727
        }
1728 1067 fernando
1729
        /**
1730
         * DOCUMENT ME!
1731
         *
1732
         * @author $author$
1733
         * @version $Revision$
1734
         */
1735 1153 fernando
        private static class SortableMenu {
1736 1067 fernando
                public PluginClassLoader loader;
1737
                public Menu menu;
1738
                public SkinExtensionType extension;
1739
1740
                /**
1741
                 * DOCUMENT ME!
1742
                 *
1743
                 * @param loader DOCUMENT ME!
1744
                 * @param skinExt
1745
                 * @param menu2
1746
                 */
1747
                public SortableMenu(PluginClassLoader loader,
1748
                        SkinExtensionType skinExt, Menu menu2) {
1749
                        extension = skinExt;
1750
                        menu = menu2;
1751
                        this.loader = loader;
1752
                }
1753
        }
1754 3298 caballero
        /**
1755
         * DOCUMENT ME!
1756
         */
1757 6589 cesar
        private static class SortableTool {
1758 5421 cesar
                public PluginClassLoader loader;
1759
                public ToolBar toolbar;
1760
                public ActionTool actiontool;
1761
                public SelectableTool selectabletool;
1762
                public SkinExtensionType extension;
1763
1764
                /**
1765
                 * DOCUMENT ME!
1766
                 *
1767
                 * @param loader DOCUMENT ME!
1768
                 * @param skinExt
1769
                 * @param menu2
1770
                 */
1771 6589 cesar
                public SortableTool(PluginClassLoader loader,
1772 5421 cesar
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1773
                        extension = skinExt;
1774
                        toolbar = toolbar2;
1775
                        actiontool=actiontool2;
1776
                        this.loader = loader;
1777
                }
1778 6589 cesar
                public SortableTool(PluginClassLoader loader,
1779 5421 cesar
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1780
                        extension = skinExt;
1781
                        toolbar = toolbar2;
1782
                        selectabletool=selectabletool2;
1783
                        this.loader = loader;
1784
                }
1785
        }
1786
        /**
1787
         * DOCUMENT ME!
1788
         */
1789 3298 caballero
        private static class ToolBarComparator implements Comparator {
1790
                private static ExtensionComparator extComp = new ExtensionComparator();
1791
1792
                /**
1793
                 * DOCUMENT ME!
1794
                 *
1795
                 * @param o1 DOCUMENT ME!
1796
                 * @param o2 DOCUMENT ME!
1797
                 *
1798
                 * @return DOCUMENT ME!
1799
                 */
1800
                public int compare(Object o1, Object o2) {
1801 6589 cesar
                        SortableTool e1 = (SortableTool) o1;
1802
                        SortableTool e2 = (SortableTool) o2;
1803 6101 jaume
1804 5421 cesar
                        // if the toolbars have the same name, they are considered to be
1805
                        // the same toolbar, so we don't need to do further comparing
1806
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1807
                                return 0;
1808 6101 jaume
1809 3298 caballero
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1810
                                if (e1.extension instanceof SkinExtensionType) {
1811
                                        return 1;
1812
                                } else if (e2.extension instanceof SkinExtensionType) {
1813
                                        return -1;
1814
                                } else {
1815
                                        return extComp.compare(e1.extension, e2.extension);
1816
                                }
1817
                        }
1818
1819
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1820 6696 cesar
                                return Integer.MIN_VALUE;
1821 3298 caballero
                        }
1822
1823
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1824
                                return Integer.MAX_VALUE;
1825
                        }
1826 3310 caballero
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1827 5421 cesar
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1828 6101 jaume
1829 3310 caballero
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1830
                                return 0;
1831
                        }
1832 5421 cesar
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1833 3298 caballero
                }
1834
        }
1835 6101 jaume
1836 3298 caballero
        /**
1837 5421 cesar
         * <p>This class is used to compare tools (selectabletool and actiontool),
1838
         * using the "position"
1839
         * attribute.</p>
1840
         * <p>The ordering criteria are:</p>
1841
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1842
         * order.
1843
         * (using the ToolBarComparator).</li>
1844
         * <li></li>
1845
         * <li>If any of the tools has not 'position' attribute, the tool which
1846
         * <strong>has</strong> the attribute will be placed first.</li>
1847
         * <li>If both tools have the same position (or they don't have a
1848
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1849 3298 caballero
         *
1850 5421 cesar
         * @author cesar
1851 3298 caballero
         * @version $Revision$
1852
         */
1853 5421 cesar
        private static class ToolComparator implements Comparator {
1854
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1855 3298 caballero
                /**
1856
                 * DOCUMENT ME!
1857
                 *
1858 5421 cesar
                 * @param o1 DOCUMENT ME!
1859
                 * @param o2 DOCUMENT ME!
1860
                 *
1861
                 * @return DOCUMENT ME!
1862 3298 caballero
                 */
1863 5421 cesar
                public int compare(Object o1, Object o2) {
1864
                        // compare the toolbars which contain the tools
1865
                        int result = toolBarComp.compare(o1, o2);
1866
                        if (result != 0) { // if the toolbars are different, use their order
1867
                                return result;
1868
                        }
1869
                        // otherwise, compare the tools
1870 6589 cesar
                        SortableTool e1 = (SortableTool) o1;
1871
                        SortableTool e2 = (SortableTool) o2;
1872 5421 cesar
                        int e1Position=-1, e2Position=-1;
1873
1874
                        if (e1.actiontool!=null) {
1875
                                if (e1.actiontool.hasPosition())
1876
                                        e1Position = e1.actiontool.getPosition();
1877
                        }
1878
                        else if (e1.selectabletool!=null) {
1879
                                if (e1.selectabletool.hasPosition())
1880
                                        e1Position = e1.selectabletool.getPosition();
1881
                        }
1882 6101 jaume
1883 5421 cesar
                        if (e2.actiontool!=null) {
1884
                                if (e2.actiontool.hasPosition())
1885
                                        e2Position = e2.actiontool.getPosition();
1886
                        }
1887
                        else if (e2.selectabletool!=null){
1888
                                if (e2.selectabletool.hasPosition())
1889
                                        e2Position = e2.selectabletool.getPosition();
1890
                        }
1891 6101 jaume
1892 5421 cesar
                        if (e1Position==-1 && e2Position!=-1) {
1893
                                return 1;
1894
                        }
1895
                        if (e1Position!=-1 && e2Position==-1) {
1896
                                return -1;
1897
                        }
1898
                        if (e1Position!=-1 && e2Position!=-1) {
1899
                                result = e1Position - e2Position;
1900
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1901
                                if (result!=0) return result;
1902
                        }
1903
                        return e1.toString().compareTo(e2.toString());
1904 3298 caballero
                }
1905
        }
1906 6101 jaume
1907
1908 4306 ldiaz
        /**
1909
         * validates the user before starting gvsig
1910
         *
1911
         */
1912
        private static void validate(){
1913 6101 jaume
1914 4306 ldiaz
                IAuthentication session =  null;
1915
                try {
1916
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1917
1918
                } catch (ClassNotFoundException e) {
1919
                        // TODO Auto-generated catch block
1920 4308 ldiaz
                        //e.printStackTrace();
1921 4306 ldiaz
                        return;
1922
                } catch (InstantiationException e) {
1923
                        // TODO Auto-generated catch block
1924 4308 ldiaz
                        //e.printStackTrace();
1925
                        return;
1926 4306 ldiaz
                } catch (IllegalAccessException e) {
1927
                        // TODO Auto-generated catch block
1928 4308 ldiaz
                        //e.printStackTrace();
1929
                        return;
1930 4306 ldiaz
                }
1931 6101 jaume
1932 4306 ldiaz
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1933
                if (session.validationRequired()){
1934 8765 jjdelcerro
                        if(session.Login()){
1935 4306 ldiaz
                                System.out.println("You are logged in");
1936
                        }
1937
                        else{
1938
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1939 6101 jaume
                                                 "You are not logged in");
1940 8765 jjdelcerro
                                //System.exit(0);
1941 4358 ldiaz
                        }
1942
                        PluginServices.setAuthentication(session);
1943 6101 jaume
                }
1944 4306 ldiaz
        }
1945 6101 jaume
1946
        public static String getDefaultLookAndFeel() {
1947
                String osName = (String) System.getProperty("os.name");
1948
1949
            if (osName.substring(0,3).toLowerCase().equals("win"))
1950
                    return UIManager.getSystemLookAndFeelClassName();
1951
        else
1952 9144 mija
                if (osName.substring(0,6).toLowerCase().equals("mac os"))
1953
                        return UIManager.getSystemLookAndFeelClassName();
1954
                else
1955
                        return nonWinDefaultLookAndFeel;
1956 6101 jaume
        }
1957 6951 cesar
1958
        /**
1959
         * Gets the ISO 839 two-characters-long language code matching the
1960
         * provided language code (which may be an ISO 839-2/T
1961
         * three-characters-long code or an ISO 839-1 two-characters-long
1962
         * code).
1963 7513 caballero
         *
1964 6951 cesar
         * If the provided parameter is already two characters long, it
1965
         * returns the parameter without any modification.
1966 7513 caballero
         *
1967 6951 cesar
         * @param langCode A language code representing either
1968
         *  an ISO 839-2/T language code or an ISO 839-1 code.
1969
         * @return A two-characters-long code specifying
1970
         *  an ISO 839 language code.
1971
         */
1972
        private static String normalizeLanguageCode(String langCode) {
1973
                final String fileName = "iso_639.tab";
1974
                if (langCode.length()==2)
1975
                        return langCode;
1976
                else if (langCode.length()==3) {
1977
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
1978
                                return "ca";
1979
                        }
1980
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
1981
                        if (isoCodes!=null) {
1982
                                try {
1983
                                        BufferedReader reader =
1984
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
1985
                                                String line;
1986
1987
                                                while ((line = reader.readLine()) != null) {
1988
                                                        String[] language = line.split("\t");
1989
                                                        if (language[0].equals(langCode)) // first column is the three characters code
1990
                                                                return language[2]; // third column i the two characters code
1991
                                                }
1992
                                }
1993
                                catch (IOException ex) {
1994
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
1995
                                        return "es";
1996
                                }
1997
                        }
1998
                        else {
1999
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2000
                                return "es";
2001
                        }
2002
                }
2003
                return "es";
2004
        }
2005 7513 caballero
2006 6951 cesar
        /**
2007
         * Configures the locales (languages and local resources) to be used
2008
         * by the application.
2009 7513 caballero
         *
2010 6951 cesar
         * First it tries to get the locale from the command line parameters,
2011
         * then the andami-config file is checked.
2012 7513 caballero
         *
2013 6951 cesar
         * The locale name is normalized to get a two characters language code
2014
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2015
         * are also accepted from the command line or the configuration file).
2016 7513 caballero
         *
2017 6951 cesar
         * Finally, the gvsig-i18n library and the default locales for Java and
2018
         * Swing are configured.
2019
         *
2020
         */
2021
        private static void configureLocales(String[] args) {
2022
                //                 Configurar el locale
2023
        String localeStr = null;
2024
        for (int i=2; i < args.length; i++)
2025
        {
2026
                int index = args[i].indexOf("language=");
2027
                if (index != -1)
2028
                        localeStr = args[i].substring(index+9);
2029
        }
2030
                if (localeStr == null)
2031
                {
2032
            localeStr = andamiConfig.getLocaleLanguage();
2033
                }
2034
                localeStr = normalizeLanguageCode(localeStr);
2035
                locale = getLocale(localeStr,
2036
                andamiConfig.getLocaleCountry(),
2037
                andamiConfig.getLocaleVariant());
2038
                Locale.setDefault(locale);
2039
                JComponent.setDefaultLocale(locale);
2040
        org.gvsig.i18n.Messages.addLocale(locale);
2041
                // add english and spanish as fallback languages
2042
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2043
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2044
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2045
2046
        }
2047 7682 luisw2
2048
        /**
2049
         * Gets Home Directory location of the application.
2050
         * May be set from outside the aplication by means of
2051
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2052
         * of the application
2053
         * @return
2054
         */
2055
        public static String getAppHomeDir() {
2056
                return appHomeDir;
2057
        }
2058
2059
        /**
2060
         * Sets Home Directory location of the application.
2061
         * May be set from outside the aplication by means of
2062
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2063
         * of the application
2064
         * @param appHomeDir
2065
         */
2066
        public static void setAppHomeDir(String appHomeDir) {
2067
                Launcher.appHomeDir = appHomeDir;
2068
        }
2069 598 fernando
}