Statistics
| Revision:

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

History | View | Annotate | Download (9.82 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.event.ActionListener;
45
import java.io.File;
46
import java.lang.reflect.InvocationTargetException;
47
import java.util.Iterator;
48
import java.util.Locale;
49
import java.util.MissingResourceException;
50
import java.util.PropertyResourceBundle;
51
import java.util.ResourceBundle;
52

    
53
import javax.swing.SwingUtilities;
54

    
55
import org.apache.log4j.Logger;
56

    
57
import com.iver.andami.messages.Messages;
58
import com.iver.andami.messages.NotificationManager;
59
import com.iver.andami.plugins.Extension;
60
import com.iver.andami.plugins.PluginClassLoader;
61
import com.iver.andami.ui.mdiFrame.MDIFrame;
62
import com.iver.andami.ui.mdiFrame.MainFrame;
63
import com.iver.andami.ui.mdiManager.MDIManager;
64
import com.iver.utiles.XMLEntity;
65

    
66

    
67
/**
68
 * Clase que proporciona servicios a los plugins.
69
 *
70
 * @author Fernando Gonz?lez Cort?s
71
 */
72
public class PluginServices {
73
        private static Logger logger = Logger.getLogger(PluginServices.class.getName());
74
        private PluginClassLoader loader;
75
        private PropertyResourceBundle resourceBundle;
76
        private XMLEntity persistentXML;
77

    
78
        /**
79
         * Crea un nuevo PluginServices
80
         *
81
         * @param loader ClassLoader del plugin
82
         */
83
        public PluginServices(PluginClassLoader loader) {
84
                this.loader = loader;
85
        }
86

    
87
        /**
88
         * Devuelve el mensaje en el idioma del locale actual del texto
89
         * correspondiente a la clave que se pasa como par?metro
90
         *
91
         * @param key Clave del texto que se quiere obtener
92
         *
93
         * @return Texto en el idioma que toca o la propia clave si no se encuentra
94
         *                    en el fichero
95
         */
96
        public String getText(String key) {
97
                if (resourceBundle == null) {
98
                        return key;
99
                }
100

    
101
                if (key == null) {
102
                        return null;
103
                }
104

    
105
                try {
106
                        return resourceBundle.getString(key);
107
                } catch (MissingResourceException e) {
108
                        logger.warn(Messages.getString("PluginServices.No_se_encontro_la_traduccion_para") + " " + key);
109

    
110
                        return key;
111
                }
112
        }
113

    
114
        /**
115
         * Obtiene el classloader del plugin
116
         *
117
         * @return Returns the loader.
118
         */
119
        public PluginClassLoader getClassLoader() {
120
                return loader;
121
        }
122

    
123
        /**
124
         * Obtiene el nombre del plugin
125
         *
126
         * @return String
127
         */
128
        String getPluginName() {
129
                return loader.getPluginName();
130
        }
131

    
132
        /**
133
         * Establece el paquete de traducciones del objeto
134
         * pluginservices asociado a un plugin
135
         *
136
         * @param name nombre del paquete
137
         * @param locale locale para obtener los recursos del paquete
138
         */
139
        void setResourceBundle(String name, Locale locale) {
140
                try {
141
                        resourceBundle = (PropertyResourceBundle) ResourceBundle.getBundle(name,
142
                                        locale, loader);
143
                } catch (MissingResourceException e) {
144
                        logger.error(Messages.getString("PluginServices.No_se_encontro_el_recurso_de_traducciones") + name, e);
145
                }
146
        }
147

    
148
        /**
149
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
150
         * como par?metro
151
         *
152
         * @param pluginClassInstance Instancia de una clase propia del plugin a
153
         *                   cuyos servicios se quiere acceder
154
         *
155
         * @return Objeto PluginServices asociado al plugin
156
         *
157
         * @throws RuntimeException Si el par?metro no es un objeto cargado desde un plugin
158
         */
159
        public static PluginServices getPluginServices(Object pluginClassInstance) {
160
                try {
161
                        PluginClassLoader loader = (PluginClassLoader) pluginClassInstance.getClass()
162
                                                                                                                                                          .getClassLoader();
163

    
164
                        return Launcher.getPluginServices(loader.getPluginName());
165
                } catch (ClassCastException e) {
166
                        throw new RuntimeException(
167
                                "Parameter is not a plugin class instance");
168
                }
169
        }
170

    
171
        /**
172
         * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
173
         * como par?metro
174
         *
175
         * @param pluginName Instancia de una clase propia del plugin a cuyos
176
         *                   servicios se quiere acceder
177
         *
178
         * @return Objeto PluginServices asociado al plugin
179
         */
180
        public static PluginServices getPluginServices(String pluginName) {
181
                return Launcher.getPluginServices(pluginName);
182
        }
183

    
184
        /**
185
         * Obtiene una referencia al gestor de ventanas
186
         *
187
         * @return MDIManager
188
         */
189
        public static MDIManager getMDIManager() {
190
                return Launcher.getFrame().getMDIManager();
191
        }
192

    
193
        /**
194
         * Obtiene una referencia al marco principal de la
195
         * aplicaci?n
196
         *
197
         * @return MainFrame
198
         */
199
        public static MainFrame getMainFrame() {
200
                return Launcher.getFrame();
201
        }
202

    
203
        /**
204
         * Obtiene una referencia a la instancia de la extensi?n
205
         * cuya clase se pasa como par?metro
206
         *
207
         * @param extensionClass Clase de la extensi?n cuya instancia se quiere obtener
208
         *
209
         * @return Instancia de la extensi?n o null en caso de que no haya
210
         * una extensi?n con esa clase
211
         */
212
        public static Extension getExtension(Class extensionClass) {
213
                return (Extension) Launcher.getClassesExtensions().get(extensionClass);
214
        }
215

    
216
        /**
217
         * Obtiene un iterador sobre las extensiones
218
         *
219
         * @return Iterator
220
         */
221
        public static Iterator getExtensions() {
222
                return Launcher.getClassesExtensions().values().iterator();
223
        }
224

    
225
        /**
226
         * Obtiene una traducci?n de un plugin
227
         *
228
         * @param pluginObject Objeto cargado desde un plugin
229
         * @param key Nombre de la clave cuyo valor se quiere obtener
230
         *
231
         * @return El valor, si existe. La clave si no existe. Si el objeto que
232
         * se pasa como par?metro no ha sido cargado desde un plugin
233
         * se devuelve la clave.
234
         */
235
        public static String getText(Object pluginObject, String key) {
236
                try {
237
                        PluginServices ps = getPluginServices(pluginObject);
238

    
239
                        return ps.getText(key);
240
                } catch (RuntimeException e) {
241
                        logger.error("GetText: Clave = " + key + ". ", e);
242

    
243
                        return key;
244
                }
245
        }
246

    
247
        /**
248
         * Establece los datos del plugin que deber?n persistir entre ejecuciones
249
         * en formato xml
250
         *
251
         * @param entity DOCUMENT ME!
252
         */
253
        public void setPersistentXML(XMLEntity entity) {
254
                persistentXML = entity;
255
        }
256

    
257
        /**
258
         * Obtiene un objeto que representa la persistencia del plugin en formato
259
         * xml.
260
         *
261
         * @return Devuelve null hasta que se invoca el m?todo setPersistentXML
262
         */
263
        public XMLEntity getPersistentXML() {
264
                if (persistentXML == null){
265
                        persistentXML = new XMLEntity();
266
                }
267
                return persistentXML;
268
        }
269

    
270
        /**
271
         * A?ade un listener a un popup menu registrado en el
272
         * config.xml de alg?n plugin
273
         *
274
         * @param name Nombre del men? contextual
275
         * @param c Componente que desplegar? el men? cuando
276
         * se haga click con el bot?n derecho
277
         * @param listener Listener que se ejecutar? cuando se 
278
         * seleccione cualquier entrada del men?
279
         *
280
         * @throws RuntimeException Si la interfaz no est? preparada
281
         * todav?a. S?lo puede darse durante el arranque
282
         */
283
        public void addPopupMenuListener(String name, Component c,
284
                ActionListener listener) {
285
                MDIFrame frame = Launcher.getFrame();
286

    
287
                if (frame == null) {
288
                        throw new RuntimeException("MDIFrame not loaded yet");
289
                }
290

    
291
                frame.addPopupMenuListener(name, c, listener, loader);
292
        }
293

    
294
        /**
295
         * Obtiene una referencia al directorio del plugin
296
         *
297
         * @return File
298
         */
299
        public File getPluginDirectory() {
300
                return new File(Launcher.getPluginsDir() + File.separator +
301
                        getPluginName());
302
        }
303

    
304
        /**
305
         * Ejecuta una tarea en segundo plano, dejando a la 
306
         * interfaz responder pero inhibiendo los eventos
307
         *
308
         * @param r Tarea a ejecutar
309
         *
310
         * @return Thread en el que se ejecuta la tarea
311
         */
312
        public static Thread backgroundExecution(Runnable r) {
313
                Thread t = new Thread(new RunnableDecorator(r));
314
                t.start();
315

    
316
                return t;
317
        }
318

    
319
        /**
320
         * DOCUMENT ME!
321
         *
322
         * @author Fernando Gonz?lez Cort?s
323
         */
324
        private static class RunnableDecorator implements Runnable {
325
                private Runnable r;
326

    
327
                /**
328
                 * Crea un nuevo RunnableDecorator.
329
                 *
330
                 * @param r DOCUMENT ME!
331
                 */
332
                public RunnableDecorator(Runnable r) {
333
                        this.r = r;
334
                }
335

    
336
                /**
337
                 * @see java.lang.Runnable#run()
338
                 */
339
                public void run() {
340
                        try {
341
                                SwingUtilities.invokeAndWait(new Runnable() {
342
                                                public void run() {
343
                                                        getMDIManager().setWaitCursor();
344
                                                }
345
                                        });
346
                        } catch (InterruptedException e) {
347
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
348
                                        e);
349
                        } catch (InvocationTargetException e) {
350
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
351
                                        e);
352
                        }
353

    
354
                        try{
355
                                r.run();
356
                        } catch(RuntimeException e){
357
                                NotificationManager.addError(Messages.getString("PluginServices.Bug_en_el_codigo"), e);
358
                        } catch (Error e){
359
                                NotificationManager.addError(Messages.getString("PluginServices.Error_grave_de_la_aplicaci?n"), e);
360
                        }
361

    
362
                        try {
363
                                SwingUtilities.invokeAndWait(new Runnable() {
364
                                                public void run() {
365
                                                        getMDIManager().restoreCursor();
366
                                                }
367
                                        });
368
                        } catch (InterruptedException e) {
369
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
370
                                        e);
371
                        } catch (InvocationTargetException e) {
372
                                NotificationManager.addWarning(Messages.getString("PluginServices.No_se_pudo_restaurar_el_cursor_del_raton"),
373
                                        e);
374
                        }
375
                }
376
        }
377
}