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 @ 43941

History | View | Annotate | Download (14.9 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
        String pluginName = ((PluginClassLoader) extension.getClassLoader()).getPluginName();
151
        return this.getPlugin(pluginName);
152
    }
153

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

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

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

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

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

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

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

    
227
    @SuppressWarnings("unchecked")
228
    public List<PluginServices> getPlugins() {
229
        List<PluginServices> pluginServices = new ArrayList<PluginServices>();
230

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

    
240
    public void setExclusiveUIExtension(ExclusiveUIExtension extension) {
241
        PluginServices.setExclusiveUIExtension(extension);
242
    }
243

    
244
    public String getText(Object obj, String msg) {
245
        return PluginServices.getText(obj, msg);
246
    }
247

    
248
    public String translate(String msg) {
249
        return org.gvsig.i18n.Messages.translate(msg);
250
    }
251

    
252
    public File getApplicationFolder() {
253
        return Launcher.getApplicationFolder();
254
    }
255

    
256
    /**
257
     * @deprecated use {@link #getPluginsFolders()}
258
     */
259
    public File getPluginsDirectory() {
260
        return getPluginsFolder();
261
    }
262

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

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

    
284
        this.pluginsFolders = new ArrayList<File>();
285

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

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

    
307
        return this.pluginsFolders;
308
    }
309

    
310
    public File getInstallFolder() {
311
        return new File(getApplicationFolder(), "install");
312
    }
313

    
314
    public File getApplicationHomeFolder() {
315
        return Launcher.getApplicationHomeFolder();
316
    }
317

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

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

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

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

    
358
    public File getApplicationI18nFolder() {
359
        return new File(this.getApplicationFolder(), "i18n");
360
    }
361

    
362
    public FirewallConfiguration getFirewallConfiguration() {
363
            return (FirewallConfiguration) ToolsLocator.getFirewallManager();
364
    }
365

    
366
    public Version getApplicationVersion() {
367
        PackageInfo pinfo = this.getPackageInfo();
368
        Version version = pinfo.getVersion();
369
        return version;
370
    }
371

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

    
388
    public void saveUnsavedData(List<IUnsavedData> unsavedData) throws UnsavedDataException {
389
        List<IUnsavedData> errors = new ArrayList<IUnsavedData>();
390

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

    
405
    @Override
406
    public String getApplicationName() {
407
        return Launcher.getApplicationName();
408
    }
409

    
410
    @Override
411
    public File getTempFolder() {
412
        return new File(Utilities.TEMPDIRECTORYPATH);
413
    }
414

    
415
    @Override
416
    public File getTempFile(String name) {
417
        return new File(Utilities.TEMPDIRECTORYPATH, name);
418
    }
419

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

    
435
    @Override
436
    public boolean desktopBrowse(URI uri){
437
        return DesktopApi.browse(uri);
438
    }
439

    
440
    @Override
441
    public boolean desktopOpen(File file){
442
        return DesktopApi.open(file);
443
    }
444

    
445
    @Override
446
    public Arguments getArguments() {
447
        return Launcher.getArguments();
448
    }    
449
}