Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / PluginServices.java @ 4732

History | View | Annotate | Download (13.9 KB)

1
/* 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
package com.iver.andami;
42

    
43
import java.awt.Component;
44
import java.awt.Frame;
45
import java.awt.event.ActionListener;
46
import java.io.File;
47
import java.lang.reflect.InvocationTargetException;
48
import java.util.Iterator;
49
import java.util.Locale;
50
import java.util.MissingResourceException;
51
import java.util.PropertyResourceBundle;
52
import java.util.ResourceBundle;
53

    
54
import javax.swing.ProgressMonitor;
55
import javax.swing.SwingUtilities;
56
import javax.swing.Timer;
57

    
58
import org.apache.log4j.Logger;
59

    
60
import com.iver.andami.authentication.IAuthentication;
61
import com.iver.andami.messages.Messages;
62
import com.iver.andami.messages.NotificationManager;
63
import com.iver.andami.plugins.Extension;
64
import com.iver.andami.plugins.ExtensionDecorator;
65
import com.iver.andami.plugins.PluginClassLoader;
66
import com.iver.andami.ui.mdiFrame.MDIFrame;
67
import com.iver.andami.ui.mdiFrame.MainFrame;
68
import com.iver.andami.ui.mdiManager.MDIManager;
69
import com.iver.utiles.XMLEntity;
70
import com.iver.utiles.swing.threads.IMonitorableTask;
71
import com.iver.utiles.swing.threads.IProgressMonitorIF;
72
import com.iver.utiles.swing.threads.ProgressMonitorAdapter;
73
import com.iver.utiles.swing.threads.TaskMonitorTimerListener;
74
import com.iver.utiles.swing.threads.UndefinedProgressMonitor;
75

    
76
/**
77
 * Clase que proporciona servicios a los plugins.
78
 * 
79
 * @author Fernando Gonz?lez Cort?s
80
 */
81
public class PluginServices {
82
        private static Logger logger = Logger.getLogger(PluginServices.class
83
                        .getName());
84

    
85
        private static String[] arguments;
86

    
87
        private static IAuthentication authentication;
88

    
89
        private PluginClassLoader loader;
90

    
91
        private PropertyResourceBundle resourceBundle;
92

    
93
        private XMLEntity persistentXML;
94

    
95
        /**
96
         * Crea un nuevo PluginServices
97
         * 
98
         * @param loader
99
         *            ClassLoader del plugin
100
         */
101
        public PluginServices(PluginClassLoader loader) {
102
                this.loader = loader;
103
        }
104

    
105
        /**
106
         * Devuelve el mensaje en el idioma del locale actual del texto
107
         * correspondiente a la clave que se pasa como par?metro
108
         * 
109
         * @param key
110
         *            Clave del texto que se quiere obtener
111
         * 
112
         * @return Texto en el idioma que toca o la propia clave si no se encuentra
113
         *         en el fichero
114
         */
115
        public String getText(String key) {
116
                if (key == null) return null;
117
                String translation = org.gvsig.i18n.Messages.getText(key, false);
118
                if (translation != null)
119
                        return translation;
120
                else
121
                {
122
                        logger.warn("Plugin "+getPluginName()+" -- "+org.gvsig.i18n.Messages.getText("Messages._no_se_encontro_la_traduccion_para", false)+ key);
123
                        return key;
124
                }
125
        }
126

    
127
        /**
128
         * Obtiene el classloader del plugin
129
         * 
130
         * @return Returns the loader.
131
         */
132
        public PluginClassLoader getClassLoader() {
133
                return loader;
134
        }
135

    
136
        /**
137
         * Obtiene el nombre del plugin
138
         * 
139
         * @return String
140
         */
141
        String getPluginName() {
142
                return loader.getPluginName();
143
        }
144

    
145
        /**
146
         * Establece el paquete de traducciones del objeto pluginservices asociado a
147
         * un plugin
148
         * 
149
         * @param name
150
         *            nombre del paquete
151
         * @param locale
152
         *            locale para obtener los recursos del paquete
153
         */
154
        void setResourceBundle(String name, Locale locale) {
155
                try {
156
                        resourceBundle = (PropertyResourceBundle) ResourceBundle.getBundle(name,
157
                                        locale, loader);
158
                } catch (MissingResourceException e) {
159
                        logger.error(Messages.getString("PluginServices.No_se_encontro_el_recurso_de_traducciones")
160
                                                        + " '" + name + "' en " + getPluginName(),e);
161
                }
162
        }
163

    
164
        /**
165
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
166
         * como par?metro
167
         * 
168
         * @param pluginClassInstance
169
         *            Instancia de una clase propia del plugin a cuyos servicios se
170
         *            quiere acceder
171
         * 
172
         * @return Objeto PluginServices asociado al plugin
173
         * 
174
         * @throws RuntimeException
175
         *             Si el par?metro no es un objeto cargado desde un plugin
176
         */
177
        public static PluginServices getPluginServices(Object pluginClassInstance) {
178
                try {
179
                        PluginClassLoader loader = (PluginClassLoader) pluginClassInstance
180
                                        .getClass().getClassLoader();
181

    
182
                        return Launcher.getPluginServices(loader.getPluginName());
183
                } catch (ClassCastException e) {
184
                        /*
185
                         * throw new RuntimeException( "Parameter is not a plugin class
186
                         * instance");
187
                         */
188
                        return null;
189
                }
190
        }
191

    
192
        /**
193
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
194
         * como par?metro
195
         * 
196
         * @param pluginName
197
         *            Instancia de una clase propia del plugin a cuyos servicios se
198
         *            quiere acceder
199
         * 
200
         * @return Objeto PluginServices asociado al plugin
201
         */
202
        public static PluginServices getPluginServices(String pluginName) {
203
                return Launcher.getPluginServices(pluginName);
204
        }
205

    
206
        /**
207
         * Obtiene una referencia al gestor de ventanas
208
         * 
209
         * @return MDIManager
210
         */
211
        public static MDIManager getMDIManager() {
212
                return Launcher.getFrame().getMDIManager();
213
        }
214

    
215
        /**
216
         * Obtiene una referencia al marco principal de la aplicaci?n
217
         * 
218
         * @return MainFrame
219
         */
220
        public static MainFrame getMainFrame() {
221
                return Launcher.getFrame();
222
        }
223

    
224
        /**
225
         * Obtiene una referencia a la instancia de la extensi?n cuya clase se pasa
226
         * como par?metro
227
         * 
228
         * @param extensionClass
229
         *            Clase de la extensi?n cuya instancia se quiere obtener
230
         * 
231
         * @return Instancia de la extensi?n o null en caso de que no haya una
232
         *         extensi?n con esa clase
233
         */
234
        public static Extension getExtension(Class extensionClass) {
235
                ExtensionDecorator extAux = (ExtensionDecorator) Launcher
236
                                .getClassesExtensions().get(extensionClass);
237
                return extAux.getExtension();
238
                // return (Extension)
239
                // Launcher.getClassesExtensions().get(extensionClass);
240

    
241
        }
242

    
243
        /**
244
         * Gets a reference to the Extension Decorator with support for several more
245
         * options
246
         * 
247
         * @param extensionClass
248
         * @return
249
         */
250
        public static ExtensionDecorator getDecoratedExtension(Class extensionClass) {
251
                return (ExtensionDecorator) Launcher.getClassesExtensions().get(
252
                                extensionClass);
253
        }
254

    
255
        /**
256
         * Obtiene un iterador sobre las extensiones
257
         * 
258
         * @return Iterator
259
         */
260
        public static Iterator getExtensions() {
261
                return Launcher.getClassesExtensions().values().iterator();
262
        }
263

    
264
        /**
265
         * Obtiene una traducci?n de un plugin
266
         * 
267
         * @param pluginObject
268
         *            Objeto cargado desde un plugin
269
         * @param key
270
         *            Nombre de la clave cuyo valor se quiere obtener
271
         * 
272
         * @return El valor, si existe. La clave si no existe. Si el objeto que se
273
         *         pasa como par?metro no ha sido cargado desde un plugin se
274
         *         devuelve la clave.
275
         */
276
        public static String getText(Object pluginObject, String key) {
277
                if (key == null) return null;
278
                String translation = org.gvsig.i18n.Messages.getText(key, false);
279
                if (translation != null)
280
                        return translation;
281
                else
282
                {
283
                        logger.warn(org.gvsig.i18n.Messages.getText("Messages._no_se_encontro_la_traduccion_para",false) + key);
284
                        return key;
285
                }
286
        }
287

    
288
        /**
289
         * Establece los datos del plugin que deber?n persistir entre ejecuciones en
290
         * formato xml
291
         * 
292
         * @param entity
293
         *            DOCUMENT ME!
294
         */
295
        public void setPersistentXML(XMLEntity entity) {
296
                persistentXML = entity;
297
        }
298

    
299
        /**
300
         * Obtiene un objeto que representa la persistencia del plugin en formato
301
         * xml.
302
         * 
303
         * @return Devuelve null hasta que se invoca el m?todo setPersistentXML
304
         */
305
        public XMLEntity getPersistentXML() {
306
                if (persistentXML == null) {
307
                        persistentXML = new XMLEntity();
308
                }
309
                return persistentXML;
310
        }
311

    
312
        /**
313
         * A?ade un listener a un popup menu registrado en el config.xml de alg?n
314
         * plugin
315
         * 
316
         * @param name
317
         *            Nombre del men? contextual
318
         * @param c
319
         *            Componente que desplegar? el men? cuando se haga click con el
320
         *            bot?n derecho
321
         * @param listener
322
         *            Listener que se ejecutar? cuando se seleccione cualquier
323
         *            entrada del men?
324
         * 
325
         * @throws RuntimeException
326
         *             Si la interfaz no est? preparada todav?a. S?lo puede darse
327
         *             durante el arranque
328
         */
329
        public void addPopupMenuListener(String name, Component c,
330
                        ActionListener listener) {
331
                MDIFrame frame = Launcher.getFrame();
332

    
333
                if (frame == null) {
334
                        throw new RuntimeException("MDIFrame not loaded yet");
335
                }
336

    
337
                frame.addPopupMenuListener(name, c, listener, loader);
338
        }
339

    
340
        /**
341
         * Obtiene una referencia al directorio del plugin
342
         * 
343
         * @return File
344
         */
345
        public File getPluginDirectory() {
346
                return new File(Launcher.getPluginsDir() + File.separator
347
                                + getPluginName());
348
        }
349

    
350
        /**
351
         * Ejecuta una tarea en segundo plano, dejando a la interfaz responder pero
352
         * inhibiendo los eventos
353
         * 
354
         * @param r
355
         *            Tarea a ejecutar
356
         * 
357
         * @return Thread en el que se ejecuta la tarea
358
         */
359
        public static Thread backgroundExecution(Runnable r) {
360
                Thread t = new Thread(new RunnableDecorator(r));
361
                t.start();
362

    
363
                return t;
364
        }
365

    
366
        /**
367
         * Runs a task in background. This task could be monitored and canceled, and
368
         * doesnt inhibed any event.
369
         * 
370
         * @param task
371
         *            IMonitorableTask
372
         */
373
        public static void cancelableBackgroundExecution(final IMonitorableTask task) {
374
                final com.iver.utiles.swing.threads.SwingWorker worker = new com.iver.utiles.swing.threads.SwingWorker() {
375
                        public Object construct() {
376
                                try {
377
                                        task.run();
378
                                        return task;
379
                                } catch (Exception e) {
380
                                        NotificationManager.addError(null, e);
381
                                }
382
                                return null;
383
                        }
384
                };
385

    
386
                Component mainFrame = (Component) PluginServices.getMainFrame();
387

    
388
                IProgressMonitorIF progressMonitor = null;
389
                progressMonitor = new UndefinedProgressMonitor((Frame) mainFrame);
390
                progressMonitor.setIndeterminated(!task.isDefined());
391
                progressMonitor.setInitialStep(task.getInitialStep());
392
                progressMonitor.setLastStep(task.getFinishStep());
393
                progressMonitor.setCurrentStep(task.getCurrentStep());
394
                progressMonitor.setMainTitleLabel(task.getStatusMessage());
395
                progressMonitor.setNote(task.getNote());
396
                progressMonitor.open();
397
                int delay = 500;
398
                TaskMonitorTimerListener timerListener = new TaskMonitorTimerListener(
399
                                progressMonitor, task);
400
                Timer timer = new Timer(delay, timerListener);
401
                timerListener.setTimer(timer);
402
                timer.start();
403

    
404
                worker.start();
405

    
406
        }
407

    
408
        public static void closeApplication() {
409
                Launcher.closeApplication();
410
        }
411

    
412
        /**
413
         * DOCUMENT ME!
414
         * 
415
         * @author Fernando Gonz?lez Cort?s
416
         */
417
        private static class RunnableDecorator implements Runnable {
418
                private Runnable r;
419

    
420
                /**
421
                 * Crea un nuevo RunnableDecorator.
422
                 * 
423
                 * @param r
424
                 *            DOCUMENT ME!
425
                 */
426
                public RunnableDecorator(Runnable r) {
427
                        this.r = r;
428
                }
429

    
430
                /**
431
                 * @see java.lang.Runnable#run()
432
                 */
433
                public void run() {
434
                        /*
435
                         * try { SwingUtilities.invokeAndWait(new Runnable() { public void
436
                         * run() { getMDIManager().setWaitCursor(); } }); } catch
437
                         * (InterruptedException e) {
438
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
439
                         * e); } catch (InvocationTargetException e) {
440
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
441
                         * e); }
442
                         */
443

    
444
                        try {
445
                                SwingUtilities.invokeAndWait(new Runnable() {
446
                                        public void run() {
447
                                                try {
448
                                                        r.run();
449
                                                } catch (RuntimeException e) {
450
                                                        NotificationManager
451
                                                                        .addError(
452
                                                                                        Messages
453
                                                                                                        .getString("PluginServices.Bug_en_el_codigo"),
454
                                                                                        e);
455
                                                } catch (Error e) {
456
                                                        NotificationManager
457
                                                                        .addError(
458
                                                                                        Messages
459
                                                                                                        .getString("PluginServices.Error_grave_de_la_aplicaci?n"),
460
                                                                                        e);
461
                                                }
462
                                        }
463
                                });
464
                        } catch (InterruptedException e) {
465
                                NotificationManager
466
                                                .addWarning(
467
                                                                Messages
468
                                                                                .getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
469
                                                                e);
470
                        } catch (InvocationTargetException e) {
471
                                NotificationManager
472
                                                .addWarning(
473
                                                                Messages
474
                                                                                .getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
475
                                                                e);
476
                        }
477

    
478
                        /*
479
                         * try { SwingUtilities.invokeAndWait(new Runnable() { public void
480
                         * run() { getMDIManager().restoreCursor(); } }); } catch
481
                         * (InterruptedException e) {
482
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
483
                         * e); } catch (InvocationTargetException e) {
484
                         * NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
485
                         * e); }
486
                         */
487
                }
488
        }
489

    
490
        /**
491
         * Usually appName plugins-directory [locale] [other args]
492
         * 
493
         * @return the original arguments that Andami received. (app-name
494
         *         plugins-directory, locale, etc)
495
         */
496
        public static String[] getArguments() {
497
                return arguments;
498
        }
499

    
500
        public static void setArguments(String[] arguments) {
501
                PluginServices.arguments = arguments;
502
        }
503

    
504
        public static Logger getLogger() {
505
                return logger;
506
        }
507

    
508
        public static IAuthentication getAuthentication() {
509
                return authentication;
510
        }
511

    
512
        public static void setAuthentication(IAuthentication authen) {
513
                authentication = authen;
514
        }
515
}