Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.framework / org.gvsig.andami / src / main / java / org / gvsig / andami / impl / DefaultPluginsManager.java @ 44075

History | View | Annotate | Download (15.1 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.andami.impl;
25

    
26
import java.io.File;
27
import java.io.IOException;
28
import java.lang.reflect.InvocationTargetException;
29
import java.net.URI;
30
import java.util.ArrayList;
31
import java.util.Arrays;
32
import java.util.Collections;
33
import java.util.Date;
34
import java.util.Enumeration;
35
import java.util.Iterator;
36
import java.util.List;
37

    
38
import javax.swing.SwingUtilities;
39

    
40
import org.apache.commons.io.FileUtils;
41
import org.gvsig.andami.Arguments;
42

    
43
import org.gvsig.andami.Launcher;
44
import org.gvsig.andami.PluginServices;
45
import org.gvsig.andami.PluginsManager;
46
import org.gvsig.andami.Utilities;
47
import org.gvsig.andami.config.generate.AndamiConfig;
48
import org.gvsig.andami.config.generate.Plugin;
49
import org.gvsig.andami.firewall.FirewallConfiguration;
50
import org.gvsig.andami.plugins.ExclusiveUIExtension;
51
import org.gvsig.andami.plugins.Extension;
52
import org.gvsig.andami.plugins.IExtension;
53
import org.gvsig.andami.plugins.PluginClassLoader;
54
import org.gvsig.andami.plugins.status.IExtensionStatus;
55
import org.gvsig.andami.plugins.status.IUnsavedData;
56
import org.gvsig.installer.lib.api.PackageInfo;
57
import org.gvsig.installer.lib.api.Version;
58
import org.gvsig.tools.ToolsLocator;
59
import org.gvsig.tools.packageutils.PackageManager;
60

    
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63

    
64
public class DefaultPluginsManager implements PluginsManager {
65

    
66
    private class Task implements Comparable, Runnable {
67

    
68
        private String type = "";
69
        private Runnable task = null;
70
        private boolean in_event_thread = false;
71
        private int priority = 0;
72
        private String name = null;
73

    
74
        public Task(String type, String name, Runnable task, boolean in_event_thread, int priority) {
75
            this.type = type;
76
            this.in_event_thread = in_event_thread;
77
            this.task = task;
78
            this.priority = priority;
79
            this.name = name;
80
        }
81

    
82
        public int compareTo(Object t) {
83
            return this.priority - ((Task) t).priority;
84
        }
85

    
86
        public boolean equals(Object t) {
87
            return this.compareTo(t) == 0;
88
        }
89

    
90
        public void run() {
91
            if ( this.in_event_thread ) {
92
                if ( !SwingUtilities.isEventDispatchThread() ) {
93
                    try {
94
                        SwingUtilities.invokeAndWait(new Runnable() {
95
                            public void run() {
96
                                Task.this.run();
97
                            }
98
                        });
99
                    } catch (InterruptedException ex) {
100
                        // Do nothing
101
                    } catch (InvocationTargetException ex) {
102
                        logger.warn("Errors in execution of " + type + " task '" + name + "'.", ex);
103

    
104
                    }
105
                    return;
106
                }
107
            }
108
            logger.info("Running " + type + " task '" + name + "' (priority " + priority + ").");
109
            try {
110
                task.run();
111
                logger.info("Terminated " + type + " task '" + name + "'.");
112
            } catch (Throwable ex) {
113
                // Catch Exceptions and Errors (class not found)
114
                logger.warn("Errors in execution of " + type + " task '" + name + "'.", ex);
115
            }
116
        }
117

    
118
    }
119

    
120
    private static Logger logger
121
            = LoggerFactory.getLogger(DefaultPluginsManager.class);
122

    
123
    private List<File> pluginsFolders = null;
124
    private List<Task> startupTasks = new ArrayList<Task>();
125
    private List<Task> shutdownTasks = new ArrayList<Task>();
126
    
127
    public ExclusiveUIExtension getExclusiveUIExtension() {
128
        return PluginServices.getExclusiveUIExtension();
129
    }
130

    
131
    public IExtension getExtension(Class<? extends IExtension> extension) {
132
        return PluginServices.getExtension(extension);
133
    }
134

    
135
    public IExtension getExtension(String extension) {
136
        return Launcher.getExtensionByName(extension);
137
    }
138
    
139
    @SuppressWarnings("unchecked")
140
    public Iterator<IExtension> getExtensions() {
141
        return PluginServices.getExtensions();
142
    }
143

    
144
    /**
145
     * Return the associated pluginServices to the extension class passed as
146
     * parameter.
147
     *
148
     */
149
    public PluginServices getPlugin(Class<? extends IExtension> extension) {
150
        if (!(extension.getClassLoader() instanceof PluginClassLoader)) {
151
            return null;
152
        }
153
        String pluginName = ((PluginClassLoader) extension.getClassLoader()).getPluginName();
154
        return this.getPlugin(pluginName);
155
    }
156

    
157
    public PluginServices getPlugin(Object obj) {
158
        if ( obj instanceof Extension ) {
159
            return ((Extension)obj).getPlugin();
160
        }
161
        if ( obj instanceof IExtension ) {
162
            Class<? extends IExtension> klass = (Class<? extends IExtension>) obj.getClass();
163
            return this.getPlugin(klass);
164
        }
165
        PluginClassLoader loader = (PluginClassLoader) obj.getClass().getClassLoader();
166
        String pluginName = loader.getPluginName();
167
        return this.getPlugin(pluginName);
168
    }
169

    
170
    @Override
171
    public PluginServices getPlugin(String pluginName) {
172
        return Launcher.getPluginServices(pluginName);
173
    }
174
    
175
    @Override
176
        public File getPluginHomeFolder(String pluginName) {
177
        File folder = FileUtils.getFile( 
178
            this.getApplicationHomeFolder(), "plugins", pluginName
179
        );
180
                if (!folder.exists()) {
181
                        folder.mkdirs();
182
                }
183
                return folder;
184
        }    
185

    
186
    @Override
187
    public PackageInfo getPackageInfo(Class<? extends IExtension> extension) {
188
        PackageManager pkgmgr = ToolsLocator.getPackageManager();
189
        File pinfo_file = new File(this.getPlugin(extension).getPluginDirectory(), "package.info");
190

    
191
        PackageInfo packageInfo = null;
192
        try {
193
            packageInfo = pkgmgr.createPackageInfo(pinfo_file);
194
        } catch (Exception e) {
195
            logger.info("Error while reading package info file from "
196
                    + pinfo_file.toString(), e);
197
        }
198
        return packageInfo;
199
    }
200

    
201
    public PackageInfo getPackageInfo(String pluginName) {
202
        PackageManager pkgmgr = ToolsLocator.getPackageManager();
203
        File pinfo_file = new File(this.getPlugin(pluginName)
204
                .getPluginDirectory(), "package.info");
205

    
206
        PackageInfo packageInfo = null;
207
        try {
208
            packageInfo = pkgmgr.createPackageInfo(pinfo_file);
209
        } catch (Exception e) {
210
            logger.info("Error while reading package info file from "
211
                    + pinfo_file.toString(), e);
212
        }
213
        return packageInfo;
214
    }
215

    
216
    public PackageInfo getPackageInfo() {
217
        PackageManager pkgmgr = ToolsLocator.getPackageManager();
218
        File pinfo_file = new File(
219
                this.getApplicationFolder(), "package.info");
220
        PackageInfo packageInfo = null;
221
        try {
222
            packageInfo = pkgmgr.createPackageInfo(pinfo_file);
223
        } catch (Exception e) {
224
            logger.info("Error while reading package info file from "
225
                    + pinfo_file.toString(), e);
226
        }
227
        return packageInfo;
228
    }
229

    
230
    @SuppressWarnings("unchecked")
231
    public List<PluginServices> getPlugins() {
232
        List<PluginServices> pluginServices = new ArrayList<PluginServices>();
233

    
234
        AndamiConfig config = Launcher.getAndamiConfig();
235
        Enumeration<Plugin> plugins = config.enumeratePlugin();
236
        while ( plugins.hasMoreElements() ) {
237
            Plugin plugin = plugins.nextElement();
238
            pluginServices.add(PluginServices.getPluginServices(plugin.getName()));
239
        }
240
        return pluginServices;
241
    }
242

    
243
    public void setExclusiveUIExtension(ExclusiveUIExtension extension) {
244
        PluginServices.setExclusiveUIExtension(extension);
245
    }
246

    
247
    public String getText(Object obj, String msg) {
248
        return PluginServices.getText(obj, msg);
249
    }
250

    
251
    public String translate(String msg) {
252
        return org.gvsig.i18n.Messages.translate(msg);
253
    }
254

    
255
    public File getApplicationFolder() {
256
        return Launcher.getApplicationFolder();
257
    }
258

    
259
    /**
260
     * @deprecated use {@link #getPluginsFolders()}
261
     */
262
    public File getPluginsDirectory() {
263
        return getPluginsFolder();
264
    }
265

    
266
    /**
267
     * @deprecated use {@link #getPluginsFolders()}
268
     */
269
    public File getPluginsFolder() {
270
        List<File> l = this.getPluginsFolders();
271
        if ( l == null || l.size() < 1 ) {
272
            return null;
273
        }
274
        return l.get(0);
275
    }
276

    
277
    public List<File> getPluginsFolders() {
278
        if ( this.pluginsFolders != null ) {
279
            return this.pluginsFolders;
280
        }
281
        File folder;
282
        String folderPath = "gvSIG/extensiones";
283
        if ( !(Launcher.getAndamiConfig() == null || Launcher.getAndamiConfig().getPluginsDirectory() == null) ) {
284
            folderPath = Launcher.getAndamiConfig().getPluginsDirectory();
285
        }
286

    
287
        this.pluginsFolders = new ArrayList<File>();
288

    
289
        folder = new File(this.getApplicationFolder(), folderPath);
290
        if( !folder.exists() ) {
291
            try {
292
                FileUtils.forceMkdir(folder);
293
            } catch (IOException ex) {
294
                logger.warn("The plugins folder '"+folder.getAbsolutePath()+"' don't exist and can't create.",ex);
295
            }
296
        }
297
        this.pluginsFolders.add(folder);
298

    
299
        folder = new File(this.getApplicationHomeFolder(), "installation");
300
        folder = new File(folder, folderPath);
301
        if( !folder.exists() ) {
302
            try {
303
                FileUtils.forceMkdir(folder);
304
            } catch (IOException ex) {
305
                logger.warn("The plugins folder '"+folder.getAbsolutePath()+"' don't exist and can't create.",ex);
306
            }
307
        }
308
        this.pluginsFolders.add(folder);
309

    
310
        return this.pluginsFolders;
311
    }
312

    
313
    public File getInstallFolder() {
314
        return new File(getApplicationFolder(), "install");
315
    }
316

    
317
    public File getApplicationHomeFolder() {
318
        return Launcher.getApplicationHomeFolder();
319
    }
320

    
321
    public void addStartupTask(String name, Runnable task, boolean in_event_thread, int priority) {
322
        this.startupTasks.add(new Task("startup", name, task, in_event_thread, priority));
323
    }
324

    
325
    public void addShutdownTask(String name, Runnable task, boolean in_event_thread, int priority) {
326
        this.shutdownTasks.add(new Task("shutdown", name, task, in_event_thread, priority));
327
    }
328

    
329
    public void executeStartupTasks() {
330
        logger.info("Executing startup tasks.");
331
        Thread th = new Thread(new Runnable() {
332
            public void run() {
333
                try {
334
                    Thread.sleep(3);
335
                } catch (Exception exc) {
336
                    // Ignore error
337
                }
338
                Collections.sort(startupTasks);
339
                for ( int i = startupTasks.size() - 1; i >= 0; i-- ) {
340
                    Task task = startupTasks.get(i);
341
                    logger.info("Task ["+i+"] "+task.priority+", "+task.name+", in event thread "+task.in_event_thread);
342
                }
343
                for ( int i = startupTasks.size() - 1; i >= 0; i-- ) {
344
                    Task task = startupTasks.get(i);
345
                    task.run();
346
                }
347
                logger.info("Running startup tasks terminated.");
348
            }
349
        });
350
        th.start();
351
    }
352

    
353
    public void executeShutdownTasks() {
354
        logger.info("Executing shutdown tasks.");
355
        Collections.sort(shutdownTasks);
356
        for ( int i = shutdownTasks.size() - 1; i >= 0; i-- ) {
357
            Task task = shutdownTasks.get(i);
358
            task.run();
359
        }
360
    }
361

    
362
    public File getApplicationI18nFolder() {
363
        return new File(this.getApplicationFolder(), "i18n");
364
    }
365

    
366
    public FirewallConfiguration getFirewallConfiguration() {
367
            return (FirewallConfiguration) ToolsLocator.getFirewallManager();
368
    }
369

    
370
    public Version getApplicationVersion() {
371
        PackageInfo pinfo = this.getPackageInfo();
372
        Version version = pinfo.getVersion();
373
        return version;
374
    }
375

    
376
    public List<IUnsavedData> getUnsavedData() {
377
        List<IUnsavedData> unsavedDatas = new ArrayList<IUnsavedData>();
378
        Iterator<IExtension> extensions = getExtensions();
379
        while(extensions.hasNext()){
380
            IExtension extension = extensions.next();
381
            IExtensionStatus status = extension.getStatus();
382
            if(status != null && status.hasUnsavedData()){
383
              IUnsavedData[] unsavedData = status.getUnsavedData();
384
              if (unsavedData != null){
385
                  unsavedDatas.addAll(Arrays.asList(unsavedData));
386
              }
387
            }
388
        }
389
        return unsavedDatas;
390
    }
391

    
392
    public void saveUnsavedData(List<IUnsavedData> unsavedData) throws UnsavedDataException {
393
        List<IUnsavedData> errors = new ArrayList<IUnsavedData>();
394

    
395
        for (Iterator iterator = unsavedData.iterator(); iterator.hasNext();) {
396
            IUnsavedData itemUnsavedData = (IUnsavedData) iterator.next();
397
            try {
398
                itemUnsavedData.saveData();
399
            } catch (Exception e) {
400
                errors.add(itemUnsavedData);
401
                logger.warn("Can't save "+itemUnsavedData.getResourceName());
402
            }
403
        }
404
        if(!errors.isEmpty()){
405
            throw new UnsavedDataException(errors);
406
        }
407
    }
408

    
409
    @Override
410
    public String getApplicationName() {
411
        return Launcher.getApplicationName();
412
    }
413

    
414
    @Override
415
    public File getTempFolder() {
416
        return new File(Utilities.TEMPDIRECTORYPATH);
417
    }
418

    
419
    @Override
420
    public File getTempFile(String name) {
421
        return new File(Utilities.TEMPDIRECTORYPATH, name);
422
    }
423

    
424
    @Override
425
    public File getTempFile(String name, String sufix) {
426
        File tempFolder = new File(Utilities.TEMPDIRECTORYPATH);
427
        if( !tempFolder.exists() ) {
428
            try {
429
                FileUtils.forceMkdir(tempFolder);
430
            } catch(Throwable th) {
431
                throw new RuntimeException(th);
432
            }
433
        }
434
        long t = new Date().getTime();
435
        String fname = String.format("%s-%x%x%s", name,t,sufix);
436
        return new File(tempFolder,fname);
437
    }
438

    
439
    @Override
440
    public boolean desktopBrowse(URI uri){
441
        return DesktopApi.browse(uri);
442
    }
443

    
444
    @Override
445
    public boolean desktopOpen(File file){
446
        return DesktopApi.open(file);
447
    }
448

    
449
    @Override
450
    public Arguments getArguments() {
451
        return Launcher.getArguments();
452
    }    
453
}