Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.framework / org.gvsig.andami / src / main / java / org / gvsig / andami / PluginServices.java @ 45098

History | View | Annotate | Download (31.2 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;
25

    
26
import java.awt.Component;
27
import java.awt.Frame;
28
import java.awt.KeyEventDispatcher;
29
import java.awt.Toolkit;
30
import java.awt.datatransfer.DataFlavor;
31
import java.awt.datatransfer.StringSelection;
32
import java.awt.event.ActionListener;
33
import java.io.File;
34
import java.io.FileInputStream;
35
import java.io.FileNotFoundException;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
38
import java.lang.reflect.InvocationTargetException;
39
import java.util.ArrayList;
40
import java.util.HashMap;
41
import java.util.Iterator;
42
import java.util.Properties;
43

    
44
import javax.swing.JOptionPane;
45
import javax.swing.KeyStroke;
46
import javax.swing.SwingUtilities;
47
import javax.swing.Timer;
48
import org.apache.commons.lang3.StringUtils;
49

    
50
import org.gvsig.andami.messages.NotificationManager;
51
import org.gvsig.andami.plugins.ExclusiveUIExtension;
52
import org.gvsig.andami.plugins.ExtensionDecorator;
53
import org.gvsig.andami.plugins.IExtension;
54
import org.gvsig.andami.plugins.PluginClassLoader;
55
import org.gvsig.andami.preferences.DlgPreferences;
56
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
57
import org.gvsig.andami.ui.mdiFrame.MainFrame;
58
import org.gvsig.andami.ui.mdiManager.MDIManager;
59
import org.gvsig.i18n.Messages;
60
import org.gvsig.tools.ToolsLocator;
61
import org.gvsig.tools.dynobject.DynObject;
62
import org.gvsig.tools.dynobject.DynStruct;
63
import org.gvsig.tools.exception.BaseRuntimeException;
64
import org.gvsig.tools.persistence.PersistenceManager;
65
import org.gvsig.tools.persistence.PersistentState;
66
import org.gvsig.tools.persistence.exception.AddDefinitionException;
67
import org.gvsig.tools.swing.api.ToolsSwingLocator;
68
import org.gvsig.tools.swing.icontheme.IconTheme;
69
import org.gvsig.tools.swing.icontheme.IconThemeManager;
70
import org.gvsig.utils.XMLEntity;
71
import org.gvsig.utils.swing.threads.IMonitorableTask;
72
import org.gvsig.utils.swing.threads.IProgressMonitorIF;
73
import org.gvsig.utils.swing.threads.TaskMonitorTimerListener;
74
import org.gvsig.utils.swing.threads.UndefinedProgressMonitor;
75
import org.slf4j.Logger;
76
import org.slf4j.LoggerFactory;
77

    
78
/**
79
 * Provides services to Plugins. Each plugin has an associated PluginServices
80
 * object, which provides specific services. Main of them: translations,
81
 * logging, access to plugin's resources, background tasks, clipboard access
82
 * and data persistence.
83
 * 
84
 */
85
@SuppressWarnings("UseSpecificCatch")
86
public class PluginServices {
87

    
88
    private static Logger logger =
89
        LoggerFactory.getLogger(PluginServices.class);
90

    
91
    private static String[] arguments;
92

    
93
    private static ExclusiveUIExtension exclusiveUIExtension = null;
94

    
95
    private PluginClassLoader loader;
96

    
97
    private XMLEntity persistentXML;
98

    
99
    private DynObject pluginPersistence = null;
100

    
101
    private String[] alternativeNames = null;
102
    /**
103
     * Creates a new PluginServices objetct.
104
     * 
105
     * @param loader
106
     *            The Plugin's ClassLoader.
107
     */
108
    public PluginServices(PluginClassLoader loader) {
109
        this.loader = loader;
110
    }
111

    
112
    public PluginServices(PluginClassLoader loader, String[] alternativeNames) {
113
            this(loader);
114
        this.alternativeNames = alternativeNames;
115
    }
116

    
117
    public String[] getAlternativeNames() {
118
            return this.alternativeNames;
119
    }
120
    
121
    /**
122
     * Returns the message in the current's locale language
123
     * corresponding to the provided translation key.
124
     * The key-message pairs are obtained from the plugin's
125
     * translation files (text_xx.properties files).
126
     * 
127
     * @param key
128
     *            Translation key whose associated message is to be obtained
129
     * 
130
     * @return The message associated with the provided key, in one of the
131
     *         current locale languages, or the key if the translation is not
132
     *         found.
133
     * @deprecated use I18NManager
134
     */
135
    public String getText(String key) {
136
        if (key == null)
137
            return null;
138
        String translation = org.gvsig.i18n.Messages.getText(key, false);
139
        if (translation != null)
140
            return translation;
141
        else {
142
            logger.debug("Can't find translation for ''{}'' in plugin ''{}''.",
143
                key,
144
                getPluginName());
145
            return key;
146
        }
147
    }
148

    
149
    /**
150
     * Gets the plugin's classloader.
151
     * 
152
     * @return Returns the loader.
153
     */
154
    public PluginClassLoader getClassLoader() {
155
        return loader;
156
    }
157

    
158
    /**
159
     * Gets the plugin's name
160
     * 
161
     * @return The plugin's name
162
     */
163
    public String getPluginName() {
164
        return loader.getPluginName();
165
    }
166

    
167
    /**
168
     * Gets a reference to the PluginServices object associated with the
169
     * plugin containing the provided class.
170
     * 
171
     * Obtienen una referencia al PluginServices del plugin cuyo nombre se pasa
172
     * como par�metro
173
     * 
174
     * @param pluginClassInstance
175
     *            An instance of a class. This class is contained in a plugin,
176
     *            whose
177
     *            services are to be obtained
178
     * 
179
     * @return The PluginServices object associated to the containing plugin
180
     * 
181
     * @throws RuntimeException
182
     *             If the parameter was not loaded from a plugin
183
     */
184
    @Deprecated
185
    public static PluginServices getPluginServices(Object pluginClassInstance) {
186
        try {
187
                PluginClassLoader loader;
188
                    if( pluginClassInstance instanceof Class ) {
189
                            loader = (PluginClassLoader) ((Class) pluginClassInstance).getClassLoader();
190
                    } else {
191
                            loader = (PluginClassLoader) pluginClassInstance.getClass().getClassLoader();
192
                    }
193
            return Launcher.getPluginServices(loader.getPluginName());
194
        } catch (ClassCastException e) {
195
            /*
196
             * throw new RuntimeException( "Parameter is not a plugin class
197
             * instance");
198
             */
199
            return null;
200
        }
201
    }
202

    
203
    /**
204
     * Gets a reference to the PluginServices object associated with the
205
     * provided plugin.
206
     * 
207
     * @param pluginName
208
     *            Plugin's name whose services are going to be used
209
     * 
210
     * @return The PluginServices object associated with the provided plugin.
211
     */
212
    @Deprecated
213
    public static PluginServices getPluginServices(String pluginName) {
214
        return Launcher.getPluginServices(pluginName);
215
    }
216

    
217
    /**
218
     * Gets the window manager (MDIManager).
219
     * 
220
     * @return A reference to the window manager (MDIManager).
221
     */
222
    @Deprecated
223
    public static MDIManager getMDIManager() {
224
        return Launcher.getFrame().getMDIManager();
225
    }
226

    
227
    /**
228
     * Gets the application's main frame.
229
     * 
230
     * @return A reference to the application's main window
231
     */
232
    @Deprecated
233
    public static MainFrame getMainFrame() {
234
        return Launcher.getFrame();
235
    }
236

    
237
    public static void registerKeyStroke(KeyStroke key, KeyEventDispatcher a) {
238
        GlobalKeyEventDispatcher.getInstance().registerKeyStroke(key, a);
239
    }
240

    
241
    public static void unRegisterKeyStroke(KeyStroke key) {
242
        GlobalKeyEventDispatcher.getInstance().removeKeyStrokeBinding(key);
243
    }
244

    
245
    /**
246
     * Gets the instance of the extension whose class is provided.
247
     * 
248
     * @param extensionClass
249
     *            Class of the extension whose instance is to be returned
250
     * 
251
     * @return The instance of the extension, or null if the instance does
252
     *         not exist.Instancia de la extensi�n o null en caso de que no haya
253
     *         una
254
     */
255
    @Deprecated
256
    public static IExtension getExtension(Class extensionClass) {
257
        ExtensionDecorator extAux =
258
            (ExtensionDecorator) Launcher.getClassesExtensions()
259
            .get(extensionClass);
260
        try {
261
            return extAux.getExtension();
262
        } catch (NullPointerException ex) {
263
            return null;
264
        }
265
    }
266

    
267
    /**
268
     * Gets a reference to the Extension Decorator which adds some extra options
269
     * to the basic extension interface.
270
     * 
271
     * @param extensionClass
272
     *            The class of the extension whose decorator is to be returned
273
     * @return The ExtensionDecorator associated with the provided extension,
274
     *         or null if the extension does not exist.
275
     */
276
    @Deprecated
277
    public static ExtensionDecorator getDecoratedExtension(Class extensionClass) {
278
        return (ExtensionDecorator) Launcher.getClassesExtensions()
279
        .get(extensionClass);
280
    }
281

    
282
    /**
283
     * Returns an array containing references to all the loaded extensions.
284
     * 
285
     * @return ExtensionDecorator[] An array of ExtensionDecorators (each
286
     *         Decorator contains one extension).
287
     */
288
    @Deprecated
289
    public static ExtensionDecorator[] getDecoratedExtensions() {
290
        HashMap map = Launcher.getClassesExtensions();
291
        ExtensionDecorator[] extensions =
292
            (ExtensionDecorator[]) map.values()
293
            .toArray(new ExtensionDecorator[0]);
294
        return extensions;
295
    }
296

    
297
    /**
298
     * Gets an iterator with all the loaded Extensions.
299
     * 
300
     * @return Iterator over the decorated extensions (each member of
301
     *         the iterator is an ExtensionDecorator, which in turn contains
302
     *         one IExtension object).
303
     */
304
    @Deprecated
305
    public static Iterator getExtensions() {
306
        return Launcher.getClassesExtensions().values().iterator();
307
    }
308

    
309
    /**
310
     * Returns the message in the current's locale language
311
     * corresponding to the provided translation key.
312
     * The key-message pairs are obtained from the plugin's
313
     * translation files (text_xx.properties files).
314
     * 
315
     * @param pluginObject
316
     *            Any object which was loaded from a plugin
317
     * 
318
     * @param key
319
     *            Translation key whose associated message is to be obtained
320
     * 
321
     * @return The message associated with the provided key, in one of the
322
     *         current locale languages, or the key if the translation is not
323
     *         found.
324
     * @deprecated use I18NManager
325
     */
326
    public static String getText(Object pluginObject, String key) {
327
        if (key == null)
328
            return null;
329
        String translation = org.gvsig.i18n.Messages.getText(key, false);
330
        if (translation != null)
331
            return translation;
332
        else {
333
            logger.debug("Can't find translation for ''{}''.", key);
334
            return key;
335
        }
336
    }
337

    
338
    /**
339
     * Sets the XML data which should be saved on disk for this plugin. This
340
     * data can be retrieved on following sessions.
341
     * 
342
     * @param The
343
     *            XMLEntity object containing the data to be persisted.
344
     * 
345
     * @see PluginServices.getPersistentXML()
346
     * @see XMLEntity
347
     */
348
    public void setPersistentXML(XMLEntity entity) {
349
        persistentXML = entity;
350
    }
351

    
352
    /**
353
     * Gets the XML data which was saved on previous sessions for this
354
     * plugins.
355
     * 
356
     * @return An XMLEntity object containing the persisted data
357
     */
358
    @Deprecated
359
    public XMLEntity getPersistentXML() {
360
        if (persistentXML == null) {
361
            persistentXML = new XMLEntity();
362
        }
363
        return persistentXML;
364
    }
365

    
366
    /**
367
     * A�ade un listener a un popup menu registrado en el config.xml de alg�n
368
     * plugin
369
     * 
370
     * @param name
371
     *            Nombre del men� contextual
372
     * @param c
373
     *            Componente que desplegar� el men� cuando se haga click con el
374
     *            bot�n derecho
375
     * @param listener
376
     *            Listener que se ejecutar� cuando se seleccione cualquier
377
     *            entrada del men�
378
     * 
379
     * @throws RuntimeException
380
     *             Si la interfaz no est� preparada todav�a. S�lo puede darse
381
     *             durante el arranque
382
     */
383
    public void addPopupMenuListener(String name,
384
        Component c,
385
        ActionListener listener) {
386
        MDIFrame frame = Launcher.getFrame();
387

    
388
        if (frame == null) {
389
            throw new RuntimeException("MDIFrame not loaded yet");
390
        }
391

    
392
        frame.addPopupMenuListener(name, c, listener, loader);
393
    }
394

    
395
    /**
396
     * Gets the plugin's root directory.
397
     * 
398
     * @return A File pointing to the plugin's root directory.
399
     */
400
    public File getPluginDirectory() {
401
        return Launcher.getPluginFolder(this.getPluginName());
402
    }
403

    
404
    /**
405
     * Runs a background task. The events produced on the main frame will
406
     * be inhibited.
407
     * 
408
     * @param r
409
     *            The task to run.
410
     * 
411
     * @return The Thread on which the task is executed.
412
     */
413
    public static Thread backgroundExecution(Runnable r) {
414
        Thread t = new Thread(new RunnableDecorator(r));
415
        t.start();
416

    
417
        return t;
418
    }
419

    
420
    /**
421
     * Runs a backbround task. This task may be monitored and canceled, and
422
     * does not inhibit any event.
423
     * 
424
     * @param task
425
     *            The task to run.
426
     */
427
    public static void cancelableBackgroundExecution(final IMonitorableTask task) {
428
        final org.gvsig.utils.swing.threads.SwingWorker worker =
429
            new org.gvsig.utils.swing.threads.SwingWorker() {
430

    
431
            public Object construct() {
432
                try {
433
                    task.run();
434
                    return task;
435
                } catch (Exception e) {
436
                    NotificationManager.addError(null, e);
437
                }
438
                return null;
439
            }
440

    
441
            /**
442
             * Called on the event dispatching thread (not on the worker
443
             * thread)
444
             * after the <code>construct</code> method has returned.
445
             */
446
            public void finished() {
447
                task.finished();
448
            }
449
        };
450

    
451
        Component mainFrame = (Component) PluginServices.getMainFrame();
452

    
453
        IProgressMonitorIF progressMonitor = null;
454
        String title = getText(null, "PluginServices.Procesando");
455
        progressMonitor =
456
            new UndefinedProgressMonitor((Frame) mainFrame, title);
457
        progressMonitor.setIndeterminated(!task.isDefined());
458
        progressMonitor.setInitialStep(task.getInitialStep());
459
        progressMonitor.setLastStep(task.getFinishStep());
460
        progressMonitor.setCurrentStep(task.getCurrentStep());
461
        progressMonitor.setMainTitleLabel(task.getStatusMessage());
462
        progressMonitor.setNote(task.getNote());
463
        progressMonitor.open();
464
        int delay = 500;
465
        TaskMonitorTimerListener timerListener =
466
            new TaskMonitorTimerListener(progressMonitor, task);
467
        Timer timer = new Timer(delay, timerListener);
468
        timerListener.setTimer(timer);
469
        timer.start();
470

    
471
        worker.start();
472

    
473
    }
474

    
475
    /**
476
     * Closes the application. Cleanly exits from the application:
477
     * terminates all the extensions, then exits.
478
     * 
479
     */
480
    public static void closeApplication() {
481
        Launcher.closeApplication();
482
    }
483

    
484
    /**
485
     * DOCUMENT ME!
486
     * 
487
     * @author Fernando Gonz�lez Cort�s
488
     */
489
    private static class RunnableDecorator implements Runnable {
490

    
491
        private Runnable r;
492

    
493
        /**
494
         * Crea un nuevo RunnableDecorator.
495
         * 
496
         * @param r
497
         *            DOCUMENT ME!
498
         */
499
        public RunnableDecorator(Runnable r) {
500
            this.r = r;
501
        }
502

    
503
        /**
504
         * @see java.lang.Runnable#run()
505
         */
506
        public void run() {
507
            try {
508
                SwingUtilities.invokeAndWait(new Runnable() {
509

    
510
                    public void run() {
511
                        try {
512
                            r.run();
513
                        } catch (RuntimeException e) {
514
                            NotificationManager.addError(Messages.getText("PluginServices.Bug_en_el_codigo"),
515
                                e);
516
                        } catch (Error e) {
517
                            NotificationManager.addError(Messages.getText("PluginServices.Error_grave_de_la_aplicaci�n"),
518
                                e);
519
                        }
520
                    }
521
                });
522
            } catch (InterruptedException e) {
523
                NotificationManager.addWarning(Messages.getText("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
524
                    e);
525
            } catch (InvocationTargetException e) {
526
                NotificationManager.addWarning(Messages.getText("PluginServices.No_se_pudo_poner_el_reloj_de_arena"),
527
                    e);
528
            }
529
        }
530
    }
531

    
532
    /**
533
     * Gets an array containing the application's startup arguments. <br>
534
     * <br>
535
     * Usually: <code>appName plugins-directory [locale] [other args]</code>
536
     * 
537
     * @return the original arguments that Andami received. (app-name
538
     *         plugins-directory, locale, etc)
539
     */
540
    @Deprecated
541
    public static String[] getArguments() {
542
        return arguments;
543
    }
544

    
545
    /**
546
     * Replaces the original Andami arguments with the provided arguments.
547
     * 
548
     * @param arguments
549
     *            An array of String, each element of the array
550
     *            represents one
551
     *            argument.
552
     */
553
    @Deprecated
554
    public static void setArguments(String[] arguments) {
555
        PluginServices.arguments = arguments;
556
    }
557

    
558
    /**
559
     * Returns the value of a command line named argument. <br>
560
     * <br>
561
     * The argument format is: <br>
562
     * -{argumentName}={argumentValue} <br>
563
     * <br>
564
     * example: <br>
565
     * ' -language=en '
566
     * 
567
     * @return String The value of the argument
568
     * @deprecated use PluginManager.getArguments
569
     */
570
    public static String getArgumentByName(String name) {
571
        name = StringUtils.removeStart(name, "-");
572
        name = StringUtils.removeStart(name, "-");
573
        for (int i = 2; i < PluginServices.arguments.length; i++) {
574
            String arg = PluginServices.arguments[i];
575
            arg = StringUtils.removeStart(arg, "-");
576
            arg = StringUtils.removeStart(arg, "-");
577
            int n = arg.indexOf('=');
578
            if (n > 0) {
579
                String argname = arg.substring(0, n);
580
                if (StringUtils.equalsIgnoreCase(argname, name)) {
581
                    if (n == arg.length()) {
582
                        return "";
583
                    }
584
                    return arg.substring(n + 1);
585
                }
586
            } else {
587
                if (StringUtils.equalsIgnoreCase(arg, name)) {
588
                    return "true";
589
                }
590
            }
591
        }
592
        return null;
593
    }
594

    
595
    /**
596
     * Gets the logger. The logger is used to register important
597
     * events (errors, etc), which are stored on a file which
598
     * can be checked later.
599
     * 
600
     * @return A Logger object.
601
     * @see Logger object from the Log4j library.
602
     * 
603
     */
604
    @Deprecated
605
    public static Logger getLogger() {
606
        return logger;
607
    }
608

    
609
    @Deprecated
610
    public static DlgPreferences getDlgPreferences() {
611
        return DlgPreferences.getInstance();
612
    }
613

    
614
    /**
615
     * Stores the provided text data on the clipboard.
616
     * 
617
     * @param data
618
     *            An String containing the data to be stored
619
     *            on the clipboard.
620
     */
621
    public static void putInClipboard(String data) {
622
        StringSelection ss = new StringSelection(data);
623

    
624
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
625
    }
626

    
627
    /**
628
     * Gets text data from the Clipboard, if available.
629
     * 
630
     * @return An String containing the clipboard's data, or <code>null</code>
631
     *         if the data was not available.
632
     */
633
    @Deprecated
634
    public static String getFromClipboard() {
635

    
636
        try {
637
            return (String) Toolkit.getDefaultToolkit()
638
            .getSystemClipboard()
639
            .getContents(null)
640
            .getTransferData(DataFlavor.stringFlavor);
641
        } catch (Exception e) {
642
            return null;
643
        }
644
    }
645

    
646
    /**
647
     * Gets the ExclusiveUIExtension, an special extension which
648
     * will take
649
     * control over the UI and will decide which extensions may be
650
     * enable/disabled or visible/hidden.
651
     * 
652
     * @return If an ExclusiveUIExtension was set, return this extension.
653
     *         Otherwise, return <code>null</code>.
654
     * 
655
     * @see org.gvsig.andami.Launcher#initializeExclusiveUIExtension()
656
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
657
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
658
     */
659
    @Deprecated
660
    public static ExclusiveUIExtension getExclusiveUIExtension() {
661
        return PluginServices.exclusiveUIExtension;
662
    }
663

    
664
    /**
665
     * Sets the ExclusiveUIExtension, an special extension which
666
     * will take
667
     * control over the UI and will decide which extensions may be
668
     * enable/disabled or visible/hidden. <br>
669
     * <br>
670
     * The ExclusiveUIExtension is normally set by the following
671
     * Andami startup argument: <br>
672
     * <br>
673
     * <code>ExclusiveUIExtension=ExtensionName</code>
674
     * 
675
     * @see org.gvsig.andami.Launcher#initializeExclusiveUIExtension()
676
     * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
677
     * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
678
     */
679
    @Deprecated
680
    public static void setExclusiveUIExtension(ExclusiveUIExtension extension) {
681
        PluginServices.exclusiveUIExtension = extension;
682
    }
683

    
684
    public static void addLoaders(ArrayList classLoaders) {
685
        PluginClassLoader.addLoaders(classLoaders);
686
    }
687

    
688
    /**
689
     * @deprecated use ToolsSwingLocator.getIconThemeManager()
690
     */
691
    public static IconThemeManager getIconThemeManager() {
692
            return ToolsSwingLocator.getIconThemeManager();
693
    }
694

    
695
    /**
696
     * @deprecated use  ToolsSwingLocator.getIconThemeManager().getCurrent()
697
     */
698
    public static IconTheme getIconTheme() {
699
            return getIconThemeManager().getCurrent(); 
700
    }
701

    
702
    /**
703
     * Try to detect if the application is running in a development
704
     * environment. <br>
705
     * This look for <b>.project</b> and <b>.classpath</b> files in the starts
706
     * path of the application.
707
     * 
708
     * @return true if <b>.project</b> and <b>.classpath</b> are in the
709
     *         development path
710
     */
711
    public static boolean runningInDevelopment() {
712
        String andamiPath;
713
        Properties props = System.getProperties();
714

    
715
        try {
716
            try {
717
                andamiPath =
718
                    (new File(Launcher.class.getResource(".").getFile()
719
                        + File.separator + ".." + File.separator + ".."
720
                        + File.separator + ".." + File.separator + "..")).getCanonicalPath();
721
            } catch (IOException e) {
722
                andamiPath =
723
                    (new File(Launcher.class.getResource(".").getFile()
724
                        + File.separator + ".." + File.separator + ".."
725
                        + File.separator + ".." + File.separator + "..")).getAbsolutePath();
726
            }
727
        } catch (Exception e1) {
728
            andamiPath = (String) props.get("user.dir");
729
        }
730

    
731
        File andamiJar = new File(andamiPath + File.separator + "andami.jar");
732
        if (!andamiJar.exists())
733
            return false;
734
        File projectFile = new File(andamiPath + File.separator + ".project");
735
        File classpathFile =
736
            new File(andamiPath + File.separator + ".classpath");
737
        return projectFile.exists() && classpathFile.exists();
738

    
739
    }
740

    
741
    @Deprecated    
742
    public PluginsManager getManager() {
743
        return PluginsLocator.getManager();
744
    }
745

    
746
    private String[] getAllPluginNames() {
747
            String[] names = new String[this.alternativeNames.length+1];
748
            names[0] = this.getPluginName();
749
            for( int n=0; n<this.alternativeNames.length; n++ ) {
750
                names[n+1] = this.alternativeNames[n];
751
            }
752
            return names;
753
    }
754
    
755
    public DynObject getPluginProperties() {
756
        if (this.pluginPersistence == null) {
757
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
758
            DynStruct dynStruct = manager.getDynObjectDefinition(getPluginName());
759
            if ( dynStruct == null) {
760
                File persistenceDefinitionFile =
761
                    new File(this.getPluginDirectory(), "plugin-persistence.def");
762
                String[] names = getAllPluginNames(); 
763
                for( int i=0; i<names.length ; i++ ) {
764
                        try {
765
                            dynStruct = manager.addDefinition(DynObject.class,
766
                                names[i],
767
                                new FileInputStream(persistenceDefinitionFile),
768
                                this.getClassLoader(),
769
                                null,
770
                                null);
771
                            break;
772
                        } catch (FileNotFoundException e) {
773
                            throw new PluginPersistenceNeedDefinitionException(this.getPluginName(), e);
774
                        } catch (AddDefinitionException e) {
775
                                if( i+1 >= names.length ) { // Si ya no hay mas nombres peta
776
                                        throw new PluginPersistenceAddDefinitionException(this.getPluginName(), e);
777
                                }
778
                        }
779
                }
780
            }
781

    
782
            File persistenceFile = getPluginPersistenceFile();
783
            if (persistenceFile.exists()) {
784
                PersistentState state;
785

    
786
                try {
787
                    state = manager.loadState(new FileInputStream(persistenceFile));
788
                    pluginPersistence = (DynObject) manager.create(state);
789
                } catch (Throwable e) {
790
                        
791
                    logger.info("Can't retrieve persistent values from plugin "+
792
                    getPluginName(), e);
793
                    showMessageDialogDelayed(Messages.getText("_Unable_to_read_persistence_for_plugin")
794
                                    + ": " + getPluginName() + "\n" +
795
                                    Messages.getText("_Perhaps_saved_data_refers_to_missing_plugin"),
796
                                    Messages.getText("_Persistence"),
797
                                    JOptionPane.WARNING_MESSAGE);
798
                }
799
            }
800
            if (this.pluginPersistence == null) {
801
                logger.info("Creating default values for plugin persistence ("+this.getPluginName()+").");
802
                this.pluginPersistence =
803
                    ToolsLocator.getDynObjectManager()
804
                    .createDynObject(dynStruct); 
805
            }
806
        }
807
        return pluginPersistence;
808
    }
809

    
810
    private void showMessageDialogDelayed(final String msg, final String title, final int type) {
811
        PluginsManager pluginManger = PluginsLocator.getManager();
812
        pluginManger.addStartupTask("Persistence_"+getPluginName(), new Runnable() {
813
           public void run() {
814
                JOptionPane.showMessageDialog(
815
                                (Component) PluginServices.getMainFrame(),
816
                                msg,
817
                                title,
818
                                type);
819
                    }
820
        }, true, 100);
821
    }
822
    
823
    public void savePluginProperties() {
824
        if (this.pluginPersistence == null) {
825
            return;
826
        }
827
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
828
                File persistenceFile = getPluginPersistenceFile();
829
        PersistentState state;
830
        FileOutputStream fos;
831
        try {
832
            state = manager.getState(pluginPersistence);
833
            manager.saveState(state, new FileOutputStream(persistenceFile));
834
        } catch (Exception e) {
835
            throw new PluginSaveDataException(this.getPluginName(), e);
836
        }
837

    
838

    
839
    }
840

    
841
        /**
842
         * Returns the plugin persistence file.
843
         * 
844
         * @return the plugin persistence file
845
         */
846
        private File getPluginPersistenceFile() {
847
                return new File(getPluginHomeFolder(), "plugin-persistence.dat");
848
        }
849

    
850
        /**
851
         * Returns the folder where the plugin stores its resources. That folder
852
         * will be usually a subfolder into the application folder in the user home
853
         * folder.
854
         * 
855
         * @return the folder where the plugin stores its resources
856
         */
857
        public File getPluginHomeFolder() {
858
        return PluginsLocator.getManager().getPluginHomeFolder(this.getPluginName());
859
        }
860

    
861
    public class PluginPersistenceNeedDefinitionException extends
862
    BaseRuntimeException {
863

    
864
        /**
865
         * 
866
         */
867
        private static final long serialVersionUID = -2036279527440882712L;
868

    
869
        PluginPersistenceNeedDefinitionException(String name, Throwable cause) {
870
            super("Can't load persistence definition of plugin %(name).",
871
                "_cant_load_persistence_definition_of_plugin_XnameX",
872
                serialVersionUID);
873
            initCause(cause);
874
            setValue("name", name);
875
        }
876
    }
877

    
878
    public class PluginPersistenceAddDefinitionException extends
879
    BaseRuntimeException {
880

    
881
        /**
882
         * 
883
         */
884
        private static final long serialVersionUID = 2227722796640780361L;
885

    
886
        PluginPersistenceAddDefinitionException(String name, Throwable cause) {
887
            super("Can't add persistence definition of plugin %(name).",
888
                "_cant_add_persistence_definition_of_plugin_XnameX",
889
                serialVersionUID);
890
            this.initCause(cause);
891
            setValue("name", name);
892
        }
893
    }
894

    
895
    public class PluginLoadDataException extends
896
    BaseRuntimeException {
897

    
898
        /**
899
         * 
900
         */
901
        private static final long serialVersionUID = 1168749231143949111L;
902

    
903
        PluginLoadDataException(String name) {
904
            super("Can't load data of plugin %(name).",
905
                "_cant_load_data_of_plugin_XnameX",
906
                serialVersionUID);
907
            setValue("name", name);
908
        }
909
    }
910

    
911
    public class PluginSaveDataException extends
912
    BaseRuntimeException {
913

    
914
        /**
915
         * 
916
         */
917
        private static final long serialVersionUID = 4893241183911774542L;
918
        private final static String MESSAGE_FORMAT = "Can't save data of plugin %(name).";
919
        private final static String MESSAGE_KEY = "_cant_save_data_of_plugin_XnameX";
920

    
921
        PluginSaveDataException(String name) {
922
            super(MESSAGE_FORMAT,
923
                MESSAGE_KEY,
924
                serialVersionUID);
925
            setValue("name", name);
926
        }
927

    
928
        public PluginSaveDataException(String name, Throwable cause) {
929
            super(MESSAGE_FORMAT, cause, MESSAGE_KEY, serialVersionUID);
930
            setValue("name", name);
931

    
932
        }
933
    }
934
    
935
    @Override
936
    public String toString() {
937
        return super.toString()+" "+this.getPluginName();
938
    }
939
    
940
    public void addDependencyWithPlugin(PluginServices otherPlugin) {
941
        if( otherPlugin==null ) {
942
            return;
943
        }
944
        this.getClassLoader().addPluginClassLoader(otherPlugin.getClassLoader());
945
    }
946
}