Statistics
| Revision:

root / trunk / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 7584

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