Statistics
| Revision:

gvsig-desktop-customize / trunk / org.gvsig.customize.app / org.gvsig.customize.app.mainplugin / src / main / java / org / gvsig / customize / CustomizeTask.java @ 3

History | View | Annotate | Download (28.5 KB)

1
package org.gvsig.customize;
2

    
3
import java.io.File;
4
import java.io.IOException;
5
import java.util.ArrayList;
6
import java.util.Date;
7
import java.util.HashSet;
8
import java.util.Iterator;
9
import java.util.List;
10
import java.util.Locale;
11
import java.util.Set;
12
import java.util.logging.Level;
13
import java.util.regex.Matcher;
14
import java.util.regex.Pattern;
15
import javax.swing.JComponent;
16
import javax.swing.JOptionPane;
17
import javax.swing.SwingUtilities;
18
import org.apache.commons.io.FileUtils;
19
import org.apache.commons.lang.BooleanUtils;
20
import org.apache.commons.lang3.LocaleUtils;
21
import org.apache.commons.lang3.StringUtils;
22
import org.cresques.cts.IProjection;
23
import org.gvsig.andami.LocaleManager;
24
import org.gvsig.andami.PluginServices;
25
import org.gvsig.andami.PluginsLocator;
26
import org.gvsig.andami.PluginsManager;
27
import org.gvsig.andami.actioninfo.ActionInfo;
28
import org.gvsig.andami.actioninfo.ActionInfoManager;
29
import org.gvsig.andami.firewall.FirewallConfiguration;
30
import org.gvsig.andami.persistence.serverData.ServerDataPersistence;
31
import org.gvsig.andami.ui.mdiFrame.MainFrame;
32
import org.gvsig.app.ApplicationLocator;
33
import org.gvsig.app.ApplicationManager;
34
import org.gvsig.app.project.ProjectManager;
35
import org.gvsig.app.project.ProjectPreferences;
36
import org.gvsig.app.project.documents.view.ViewManager;
37
import org.gvsig.installer.lib.api.InstallerLocator;
38
import org.gvsig.installer.lib.api.InstallerManager;
39
import org.gvsig.installer.lib.api.PackageInfo;
40
import org.gvsig.installer.lib.api.execution.InstallPackageService;
41
import org.gvsig.tools.ToolsLocator;
42
import org.gvsig.tools.dynobject.DynObject;
43
import org.gvsig.tools.observer.ObservableHelper;
44
import org.gvsig.tools.packageutils.PackageManager;
45
import org.gvsig.tools.swing.api.ToolsSwingLocator;
46
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
47
import org.gvsig.tools.task.SimpleTaskStatus;
48
import org.gvsig.tools.task.impl.BaseTaskStatus;
49
import org.gvsig.utils.swing.jcomboServer.ServerData;
50
import org.slf4j.Logger;
51
import org.slf4j.LoggerFactory;
52

    
53
public class CustomizeTask implements Runnable {
54

    
55
    private final static Logger logger = LoggerFactory.getLogger(CustomizeExtension.class);
56

    
57
    private static final String PROXY_SECTION = "httpproxy";
58
    private static final String CRS_SECTION = "crs";
59
    private static final String THEME_SECTION = "theme";
60

    
61
    private int errorCount = 0;
62
    private DynObject pluginProperties = null;
63
    private Class scriptingExtension = null;
64
    private PluginServices plugin = null;
65

    
66
    public CustomizeTask() {
67
    }
68

    
69
    private void showWindow(final JComponent component, final String title, final WindowManager.MODE mode) {
70
        if (!SwingUtilities.isEventDispatchThread()) {
71
            SwingUtilities.invokeLater(new Runnable() {
72
                @Override
73
                public void run() {
74
                    showWindow(component, title, mode);
75
                }
76
            });
77
            try {
78
                Thread.sleep(10);
79
            } catch (InterruptedException ex) {
80
                // Do nothing
81
            }
82
            return;
83
        }
84
        ToolsSwingLocator.getWindowManager().showWindow(
85
                component,
86
                title,
87
                mode
88
        );
89
    }
90

    
91
    private static class MyServerData {
92

    
93
        private final ServerDataPersistence serversDataPersistence;
94

    
95
        public MyServerData(ServerDataPersistence serversDataPersistence) {
96
            this.serversDataPersistence = serversDataPersistence;
97
        }
98

    
99
        public List<ServerData> getServerData() {
100
            return this.serversDataPersistence.getServerData();
101
        }
102

    
103
        public void remove(String serverAddress) {
104
            if (StringUtils.isBlank(serverAddress)) {
105
                return;
106
            }
107
            Iterator<ServerData> it = getServerData().iterator();
108
            while (it.hasNext()) {
109
                ServerData x = it.next();
110
                if (serverAddress.equalsIgnoreCase(x.getServerAddress())) {
111
                    it.remove();
112
                    return;
113
                }
114
            }
115
        }
116

    
117
        public void add(String server, String protocol) {
118
            if (StringUtils.isBlank(server)) {
119
                return;
120
            }
121
            this.add(new ServerData(server, protocol));
122
        }
123

    
124
        public void add(ServerData server) {
125
            String address = server.getServerAddress().trim();
126
            for (int i = 0; i < getServerData().size(); i++) {
127
                ServerData sd = getServerData().get(i);
128
                if (sd.getServerAddress().trim().equals(address)) {
129
                    getServerData().set(i, server);
130
                    return;
131
                }
132
            }
133
            getServerData().add(server);
134
        }
135

    
136
        public boolean contains(String serverAddress) {
137
            if (StringUtils.isBlank(serverAddress)) {
138
                return false;
139
            }
140
            serverAddress = serverAddress.trim();
141
            for (int i = 0; i < getServerData().size(); i++) {
142
                String address = getServerData().get(i).getServerAddress().trim();
143
                if (serverAddress.equalsIgnoreCase(address)) {
144
                    return true;
145
                }
146
            }
147
            return false;
148
        }
149
    }
150

    
151
    private PluginServices getPlugin() {
152
        if (this.plugin == null) {
153
            PluginsManager pluginsManager = PluginsLocator.getManager();
154
            this.plugin = pluginsManager.getPlugin(this);
155
        }
156
        return this.plugin;
157
    }
158

    
159
    protected PluginServices getPlugin(String name) {
160
        PluginsManager pluginsManager = PluginsLocator.getManager();
161
        return pluginsManager.getPlugin(name);
162
    }
163

    
164
    private Class getScriptingExtension() {
165
        if (this.scriptingExtension == null) {
166
            try {
167
                this.scriptingExtension = Class.forName("org.gvsig.scripting.app.extension.ScriptingExtension");
168
            } catch (Throwable ex) {
169
                return null;
170
            }
171
        }
172
        return this.scriptingExtension;
173
    }
174

    
175
    protected void errors_add(String message, Throwable th) {
176
        errorCount++;
177
        logger.warn(message, th);
178
    }
179

    
180
    protected int errors_count() {
181
        return errorCount;
182
    }
183

    
184
    protected void errors_reset() {
185
        this.errorCount = 0;
186
    }
187

    
188
    protected DynObject getPluginProperties() {
189
        if (this.pluginProperties == null) {
190
            this.pluginProperties = this.getPlugin().getPluginProperties();
191
        }
192
        return this.pluginProperties;
193
    }
194

    
195
    protected void setProperty(String name, Object value) {
196
        this.getPluginProperties().setDynValue(name, value);
197
    }
198

    
199
    protected Object getProperty(String name) {
200
        return this.getPluginProperties().getDynValue(name);
201
    }
202

    
203
    protected String getPropertyString(String name) {
204
        return (String) this.getProperty(name);
205
    }
206

    
207
    protected int getPropertyInt(String name) {
208
        return ((Integer) this.getProperty(name)).intValue();
209
    }
210

    
211
    protected boolean getPropertyBoolean(String name) {
212
        return ((Boolean) this.getProperty(name)).booleanValue();
213
    }
214

    
215
    protected void setValue(DynObject config, String section, String option, String value) {
216
        Object subconfig = config.getDynValue(section);
217
        if (subconfig instanceof DynObject) {
218
            ((DynObject) subconfig).setDynValue(option, value);
219
        } else {
220
            config.setDynValue(option, value);
221
        }
222
    }
223

    
224
    protected String getValue(DynObject config, String section, String option, String defaultValue) {
225
        String value = null;
226
        Object subconfig = null;
227
        if (!StringUtils.isBlank(section)) {
228
            subconfig = config.getDynValue(section);
229
        }
230
        if (subconfig instanceof DynObject) {
231
            Object v = ((DynObject) subconfig).getDynValue(option);
232
            if (v != null) {
233
                value = v.toString();
234
            }
235
        } else {
236
            Object v = config.getDynValue(option);
237
            if (v != null) {
238
                value = v.toString();
239
            }
240
        }
241
        if (StringUtils.isBlank(value)) {
242
            return defaultValue;
243
        }
244
        if (THEME_SECTION.equalsIgnoreCase(section)) {
245
            return value;
246
        }
247
        if (value.contains("${")) {
248
            value = expand(config, section, value);
249
        }
250
        return value;
251
    }
252
    private static final Pattern VARIABLE = Pattern.compile("[$][{]([a-zA-Z0-9_/]+)[}]");
253

    
254
    private String expand(DynObject config, String section, String s) {
255
        String s2 = s;
256
        String v = null;
257
        Matcher m = VARIABLE.matcher(s);
258
        while (m.find()) {
259
            String name = m.group(1);
260
            String[] ss = name.split("/");
261
            switch (ss.length) {
262
                case 2:
263
                    v = getValue(config, ss[0], ss[1], "");
264
                    break;
265
                case 1:
266
                    v = getValue(config, section, ss[0], "");
267
                    break;
268
                default:
269
                    v = name;
270
            }
271
            s2 = m.replaceFirst(v);
272
            m = VARIABLE.matcher(s2);
273
        }
274

    
275
        return s2;
276
    }
277

    
278
    private void configureLocale(DynObject config) {
279
        if (!BooleanUtils.isTrue((Boolean) getProperty("configureLocale"))) {
280
            return;
281
        }
282
        try {
283
            LocaleManager localeManager = PluginsLocator.getLocaleManager();
284
            String localeCode = getValue(config, null, "default_locale", "en");
285
            Locale locale = LocaleUtils.toLocale(localeCode);
286
            localeManager.setCurrentLocale(locale);
287

    
288
            logger.info("Set default locale to '" + localeCode + "'.");
289
            setProperty("configureLocale", Boolean.FALSE);
290
        } catch (Exception ex) {
291
            errors_add("Can't apply locale configuration.", ex);
292
        }
293
    }
294

    
295
    private void configureHttpproxy(DynObject config) {
296
        if (!BooleanUtils.isTrue((Boolean) getProperty("configureHTTPPproxy"))) {
297
            return;
298
        }
299
        try {
300
            FirewallConfiguration conf = getFirewallConfiguration();
301
            String host = getValue(config, "httpproxy", "host", "");
302
            String port = getValue(config, "httpproxy", "port", "");
303
            String nonProxyHosts = getValue(config, "httpproxy", "nonProxyHosts", "");
304
            String userName = getValue(config, "httpproxy", "username", "");
305
            String password = getValue(config, "httpproxy", "password", "");
306
            String enabled = getValue(config, "httpproxy", "enabled", "false");
307
            conf.setHost(host, port);
308
            conf.setNonProxyHosts(nonProxyHosts);
309
            if (!StringUtils.isBlank(userName)) {
310
                conf.setUserName(userName);
311
            }
312
            if (!StringUtils.isBlank(password)) {
313
                conf.setPassword(password);
314
            }
315
            conf.setEnabled(BooleanUtils.toBoolean(enabled));
316
            conf.apply();
317
            logger.info("Set httpproxy host:port to '" + host + ":" + port + "', enabled " + BooleanUtils.toBoolean(enabled) + ".");
318
            setProperty("configureHTTPPproxy", Boolean.FALSE);
319
        } catch (Exception ex) {
320
            errors_add("Can't apply proxy configuration.", ex);
321
        }
322
    }
323

    
324
    private FirewallConfiguration getFirewallConfiguration() {
325
        FirewallConfiguration conf = (FirewallConfiguration) ToolsLocator.getInstance().get(ToolsLocator.FIREWALL_MANAGER_NAME);
326
//        FirewallConfiguration conf = PluginsLocator.getManager().getFirewallConfiguration();
327
        return conf;
328
    }
329

    
330
    private boolean configureHttpproxyUser(DynObject config) {
331
        try {
332
            FirewallConfiguration conf = getFirewallConfiguration();
333
            String userName = conf.getUserName();
334
            String password = conf.getPassword();
335

    
336
            HttpProxyLoginDialog dialog = new HttpProxyLoginDialog();
337
            if (StringUtils.isBlank(userName)) {
338
                userName = getValue(config, "httpproxy", "username", "");
339
            }
340
            if (StringUtils.isBlank(password)) {
341
                password = getValue(config, "httpproxy", "password", "");
342
            }
343

    
344
            dialog.setUserName(userName);
345
            dialog.setPassword(password);
346
            if (dialog.login()) {
347
                conf.setUserName(dialog.getUserName());
348
                conf.setPassword(dialog.getPassword());
349
                conf.setEnabled(true);
350
                conf.apply();
351
            } else {
352
                conf.setUserName(dialog.getUserName());
353
                conf.setPassword("");
354
                conf.setEnabled(false);
355
                conf.apply();
356
            }
357
            logger.info("Set httpproxy user to '" + conf.getUserName() + "'.");
358
            logger.info("Set httpproxy password.");
359
            // Set values in config to allow variable sustitution
360
            setValue(config, "httpproxy", "username", conf.getUserName());
361
            setValue(config, "httpproxy", "password", conf.getPassword());
362
            return true;
363
        } catch (Exception ex) {
364
            errors_add("Can't apply username/password proxy configuration.", ex);
365
            return false;
366
        }
367
    }
368

    
369
    private void configureCRS(DynObject config) {
370
        if (!BooleanUtils.isTrue((Boolean) getProperty("configureProjection"))) {
371
            return;
372
        }
373
        try {
374
            ProjectManager projectManager = ApplicationLocator.getProjectManager();
375
            ProjectPreferences projectPreferences = projectManager.getProjectPreferences();
376
            DynObject crsOptions = (DynObject) config.getDynValue("CRS");
377
            IProjection proj = (IProjection) crsOptions.getDynValue("default_projection");
378
            projectPreferences.setDefaultProjection(proj.getFullCode());
379
            logger.info("Set default projection to '" + proj.getFullCode() + "'.");
380
            setProperty("configureProjection", Boolean.FALSE);
381
        } catch (Exception ex) {
382
            errors_add("Can't apply CRS configuration.", ex);
383
        }
384
    }
385

    
386
    private void configureServers(String protocol, String pluginName, List<DynObject> servers) {
387
        if (!getPropertyBoolean("configureOGCServers_" + protocol)) {
388
            return;
389
        }
390
        if (pluginName == null) {
391
            logger.info("Skip '" + pluginName + "' servers configurations..");
392
            return;
393
        }
394
        PluginServices plugin = getPlugin(pluginName);
395
        if (plugin == null) {
396
            logger.info("Skip '" + pluginName + "' servers configurations. Plugin not installed.");
397
            return;
398
        }
399
        ServerDataPersistence serversDataPersistence = (ServerDataPersistence) plugin.getPluginProperties().getDynValue("Servers");
400
        if (serversDataPersistence == null) {
401
            serversDataPersistence = new ServerDataPersistence(protocol);
402
            plugin.getPluginProperties().setDynValue("Servers", serversDataPersistence);
403
        }
404
        MyServerData serversData = new MyServerData(serversDataPersistence);
405

    
406
        for (int i = 0; i < servers.size(); i++) {
407
            String server = (String) servers.get(i).getDynValue("url");
408
            boolean remove = BooleanUtils.isTrue((Boolean) servers.get(i).getDynValue("remove"));
409
            if (remove) {
410
                serversData.remove(server);
411
                logger.info("Remove '" + protocol + "' server '" + server + "'.");
412
            } else {
413
                if (!serversData.contains(server)) {
414
                    serversData.add(server, protocol);
415
                    logger.info("Insert '" + protocol + "' server '" + server + "'.");
416
                }
417
            }
418
        }
419
        plugin.savePluginProperties();
420
        logger.info("Save properties of plugin '" + pluginName + "'.");
421
        setProperty("configureOGCServers_" + protocol, Boolean.FALSE);
422

    
423
    }
424

    
425
    private void createActionsScripts(DynObject config) {
426
        List<DynObject> scriptActions = (List<DynObject>) config.getDynValue("scriptActions");
427
        if (scriptActions == null) {
428
            return;
429
        }
430
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
431

    
432
        for (int i = 0; i < scriptActions.size(); i++) {
433
            DynObject scriptAction = scriptActions.get(i);
434
            String name = (String) scriptAction.getDynValue("name");
435
            ActionInfo action = actionManager.getAction(name);
436
            if (action == null) {
437
                String script = (String) scriptAction.getDynValue("script");
438
                String label = (String) scriptAction.getDynValue("label");
439
                String icon = (String) scriptAction.getDynValue("icon");
440
                long position = ((Long) (scriptAction.getDynValue("position"))).longValue();
441
                String tip = (String) scriptAction.getDynValue("tip");
442
                createActionScript(name, script, label, icon, position, tip);
443
            } else {
444
                logger.info("Can't create action script, action '" + name + "' already defined.");
445
            }
446
        }
447
    }
448

    
449
    private void addTOCActions(DynObject config) {
450
        List<DynObject> viewTOCActions = (List<DynObject>) config.getDynValue("viewTocActions");
451
        if (viewTOCActions == null) {
452
            return;
453
        }
454
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
455
        ProjectManager projectManager = ApplicationLocator.getProjectManager();
456
        ViewManager viewManager = (ViewManager) projectManager.getDocumentManager(ViewManager.TYPENAME);
457
        for (int i = 0; i < viewTOCActions.size(); i++) {
458
            DynObject viewTOCAction = viewTOCActions.get(i);
459
            String name = (String) viewTOCAction.getDynValue("name");
460
            ActionInfo action = actionManager.getAction(name);
461
            if (action != null) {
462
                String group = (String) viewTOCAction.getDynValue("group");
463
                int grouporder = ((Long) (viewTOCAction.getDynValue("grouporder"))).intValue();
464
                viewManager.addTOCContextAction(action, group, grouporder);
465
            } else {
466
                logger.info("Can't add context menu entry to the view TOC. Action '" + name + "' don't exists.");
467
            }
468
        }
469
    }
470

    
471
    private void addMenuActions(DynObject config) {
472
        List<DynObject> menuActions = (List<DynObject>) config.getDynValue("menuActions");
473
        if (menuActions == null) {
474
            return;
475
        }
476
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
477
        ApplicationManager application = ApplicationLocator.getManager();
478
        for (int i = 0; i < menuActions.size(); i++) {
479
            DynObject menuAction = menuActions.get(i);
480
            String name = (String) menuAction.getDynValue("name");
481
            ActionInfo action = actionManager.getAction(name);
482
            if (action != null) {
483
                String text = (String) menuAction.getDynValue("text");
484
                application.addMenu(action, text);
485
            } else {
486
                logger.info("Can't add menu entry. Action '" + name + "' don't exists.");
487
            }
488
        }
489
    }
490

    
491
    private void addToolActions(DynObject config) {
492
        List<DynObject> toolActions = (List<DynObject>) config.getDynValue("toolActions");
493
        if (toolActions == null) {
494
            return;
495
        }
496
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
497
        ApplicationManager application = ApplicationLocator.getManager();
498
        for (int i = 0; i < toolActions.size(); i++) {
499
            DynObject toolAction = toolActions.get(i);
500
            String name = (String) toolAction.getDynValue("name");
501
            ActionInfo action = actionManager.getAction(name);
502
            if (action != null) {
503
                String toolbarName = (String) toolAction.getDynValue("toolbarName");
504
                application.addTool(action, toolbarName);
505
            } else {
506
                logger.info("Can't add tool entry. Action '" + name + "' don't exists.");
507
            }
508
        }
509
    }
510

    
511
    private ActionInfo createActionScript(String actionName, String scriptName, String label, String iconName, long position, String tip) {
512
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
513

    
514
        Class scriptingExtension = this.getScriptingExtension();
515
        if (scriptingExtension == null) {
516
            logger.warn("Can't create action script '" + actionName + "', can't locate scripting extension");
517
            return null;
518
        }
519
        if (StringUtils.isBlank(iconName)) {
520
            iconName = null;
521
        }
522
        if (StringUtils.isBlank(tip)) {
523
            tip = actionName;
524
        }
525

    
526
        ActionInfo action = actionManager.createAction(scriptingExtension, actionName, label, scriptName, iconName, null, position, tip);
527
        return actionManager.registerAction(action);
528
    }
529

    
530
    @Override
531
    public void run() {
532

    
533
        errors_reset();
534

    
535
        MainFrame mainWindow = PluginsLocator.getMainFrame();
536

    
537
        try {
538
            Configuration configManager = new Configuration();
539
            DynObject config = configManager.load();
540

    
541
            if (config == null) {
542
                PluginsLocator.getMainFrame().messageDialog(
543
                        "_No_se_ha_podido_acceder_a_la_configuracion_de_personalizacion_Consulte_el_registro_de_errores_si_precisa_mas_informacion",
544
                        "_Atencion",
545
                        JOptionPane.WARNING_MESSAGE
546
                );
547
                return;
548
            }
549

    
550
            configureLocale(config);
551
            configureHttpproxy(config);
552
            DynObject httpProxyConfiguration = (DynObject) config.getDynValue("httpproxy");
553
            if (((Boolean) (httpProxyConfiguration.getDynValue("promptUserAndPassword"))).booleanValue()) {
554
                configureHttpproxyUser(config);
555
            }
556

    
557
            configureCRS(config);
558

    
559
            mainWindow.message("_Updating_server_information", JOptionPane.INFORMATION_MESSAGE);
560
            configureServers(
561
                    "WMS",
562
                    "org.gvsig.raster.wms.app.wmsclient",
563
                    (List<DynObject>) config.getDynValue("wmsUrls")
564
            );
565
            configureServers(
566
                    "WMTS",
567
                    "org.gvsig.raster.wmts.app.wmtsclient",
568
                    (List<DynObject>) config.getDynValue("wmsUrls")
569
            );
570
            configureServers(
571
                    "WCS",
572
                    "org.gvsig.raster.wcs.app.wcsclient",
573
                    (List<DynObject>) config.getDynValue("wmsUrls")
574
            );
575
            configureServers(
576
                    "WFS",
577
                    "org.gvsig.wfs.app.mainplugin",
578
                    (List<DynObject>) config.getDynValue("wmsUrls")
579
            );
580

    
581
//
582
//            configureAllPlugins(config);
583
//
584
            createActionsScripts(config);
585

    
586
            addTOCActions(config);
587
            addMenuActions(config);
588
            addToolActions(config);
589

    
590
        } catch (Exception ex) {
591
            errors_add("Problems apply defaut configuration.", ex);
592
        }
593

    
594
        if (errors_count() > 0) {
595
            mainWindow.messageDialog(
596
                    "_Se_han_producido_errores_actualizando_la_configuracion_por_defecto_Consulte_el_registro_de_errores_si_precisa_mas_informacion",
597
                    "_Setting_custom_configuration",
598
                    JOptionPane.WARNING_MESSAGE
599
            );
600
        }
601
        installAdditionalPackages();
602
        mainWindow.message(null, JOptionPane.INFORMATION_MESSAGE);
603
    }
604

    
605
    private Set loadDefaultPackages(File packages) throws IOException {
606
        Set defaultPackages = new HashSet<String>();
607

    
608
        List<String> lines = FileUtils.readLines(packages);
609
        defaultPackages.clear();
610
        for (String line : lines) {
611
            line = line.trim();
612
            if (line.startsWith("#") || line.startsWith(";")) {
613
                continue;
614
            }
615
            defaultPackages.add(line.toLowerCase());
616
        }
617
        return defaultPackages;
618
    }
619

    
620
    /**
621
     * Workaround to bug in SimpleTaskStatus of gvSIG 2.2.0
622
     */
623
    private static class MyTaskStatus extends BaseTaskStatus {
624

    
625
        public MyTaskStatus(String title) {
626
            super(title);
627
        }
628

    
629
        public MyTaskStatus(String tittle, long minValue, long maxValue) {
630
            super(tittle, minValue, maxValue);
631
        }
632

    
633
        public void message(String message) {
634
            this.lastModification = new Date();
635
            super.message(message);
636
        }
637

    
638
    }
639

    
640
    private void installAdditionalPackages() {
641
        if (!BooleanUtils.isTrue((Boolean) getProperty("installAdditionalComponents"))) {
642
            return;
643
        }
644

    
645
        File defaultPackagesFile = new File(getPlugin().getPluginDirectory(), "defaultPackages");
646
        if (!defaultPackagesFile.exists()) {
647
            logger.info("Skip additional package instalation (don't exists " + defaultPackagesFile.getAbsolutePath() + ").");
648
            return;
649
        }
650

    
651
        boolean needRestart = false;
652
        SimpleTaskStatus taskStatus = new MyTaskStatus("Installing additional components");
653
        InstallPackagesPanel dialog = new InstallPackagesPanel(taskStatus);
654
        try {
655
            taskStatus.add();
656
            taskStatus.setAutoremove(true);
657

    
658
            showWindow(
659
                    dialog,
660
                    "Terminating installation",
661
                    WindowManager.MODE.WINDOW
662
            );
663
            taskStatus.message("Preparing additional components installation");
664

    
665
            PluginsManager pluginsManmager = PluginsLocator.getManager();
666
            InstallerManager installerManager = InstallerLocator.getInstallerManager();
667
            InstallPackageService installer = null;
668
            List<PackageInfo> packagesToInstall = new ArrayList<PackageInfo>();
669
            Set<String> defaultSelectedPacakgeCodes = loadDefaultPackages(
670
                    defaultPackagesFile
671
            );
672

    
673
            installer = installerManager.getInstallPackageService();
674

    
675
            taskStatus.message("Searching available packages");
676
            installer.addBundlesFromDirectory(pluginsManmager.getInstallFolder());
677

    
678
            taskStatus.message("Filtering packages");
679
            for (String packageCode : defaultSelectedPacakgeCodes) {
680
                PackageInfo pkg = installer.getPackageInfo(packageCode);
681
                if (pkg != null) {
682
                    File folder = installerManager.getAddonFolder(pkg.getCode());
683
                    if (folder == null) {
684
                        packagesToInstall.add(pkg);
685
                    }
686
                }
687
            }
688
            if (!packagesToInstall.isEmpty()) {
689
                taskStatus.setRangeOfValues(1, packagesToInstall.size());
690
                for (int i = 0; i < packagesToInstall.size(); i++) {
691
                    PackageInfo pkg = packagesToInstall.get(i);
692
                    taskStatus.setCurValue(i + 1);
693
                    taskStatus.message("Installing " + pkg.getCode());
694
                    try {
695
                        logger.info("install package '" + pkg.getCode() + "'.");
696
                        installer.installPackage(pluginsManmager.getApplicationFolder(), pkg);
697
                        if (needRestart(installer,pkg)) {
698
                            needRestart = true;
699
                        }
700
                    } catch (Throwable th) {
701
                        logger.warn("can't install package '" + pkg.getCode() + "'.", th);
702
                    }
703
                }
704
                taskStatus.message("Installation terminated");
705
                taskStatus.terminate();
706
                setProperty("installAdditionalComponents", Boolean.FALSE);
707
                if (needRestart) {
708
                    dialog.message("Additional components installed succesfully. Restart applicaction.");
709
                } else {
710
                    dialog.message("Additional components installed succesfully.");
711
                }
712
            } else {
713
                taskStatus.message("Installation terminated");
714
                taskStatus.terminate();
715
                dialog.message("Additional components installed succesfully.");
716
            }
717
            setProperty("installAdditionalComponents", Boolean.FALSE);
718
        } catch (Throwable th) {
719
            taskStatus.cancel();
720
            dialog.message("Problems installing additional components");
721
            logger.warn("can't install additional packages.", th);
722

    
723
        } finally {
724
            taskStatus.remove();
725
        }
726
    }
727

    
728
    private boolean needRestart(InstallPackageService installer, PackageInfo pkg) {
729
//        return installer.needRestart(pkg);
730
        if( "plugin".equalsIgnoreCase(pkg.getType()) ) {
731
            return true;
732
        } else if( "symbols".equalsIgnoreCase(pkg.getType()) ) {
733
            return false;
734
        } else if( "jCRS_EPSG".equalsIgnoreCase(pkg.getType()) ) {
735
            return true;
736
        } else {
737
            return true;
738
        }
739
        
740
    }
741
}