Statistics
| Revision:

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

History | View | Annotate | Download (29.2 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.i18n.I18nManager;
44
import org.gvsig.tools.observer.ObservableHelper;
45
import org.gvsig.tools.packageutils.PackageManager;
46
import org.gvsig.tools.swing.api.ToolsSwingLocator;
47
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
48
import org.gvsig.tools.task.SimpleTaskStatus;
49
import org.gvsig.tools.task.impl.BaseTaskStatus;
50
import org.gvsig.utils.swing.jcomboServer.ServerData;
51
import org.slf4j.Logger;
52
import org.slf4j.LoggerFactory;
53

    
54
public class CustomizeTask implements Runnable {
55

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

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

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

    
67
    public CustomizeTask() {
68
    }
69

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

    
92
    private static class MyServerData {
93

    
94
        private final ServerDataPersistence serversDataPersistence;
95

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
276
        return s2;
277
    }
278

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

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

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

    
327
    private FirewallConfiguration getFirewallConfiguration() {
328
        FirewallConfiguration conf = (FirewallConfiguration) ToolsLocator.getInstance().get(ToolsLocator.FIREWALL_MANAGER_NAME);
329
//        FirewallConfiguration conf = PluginsLocator.getManager().getFirewallConfiguration();
330
        return conf;
331
    }
332

    
333
    private boolean configureHttpproxyUser(DynObject config) {
334
        try {
335
            FirewallConfiguration conf = getFirewallConfiguration();
336
            String userName = conf.getUserName();
337
            String password = conf.getPassword();
338

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

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

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

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

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

    
430
    }
431

    
432
    private void createActionsScripts(DynObject config) {
433
        List<DynObject> scriptActions = (List<DynObject>) config.getDynValue("scriptActions");
434
        if (scriptActions == null) {
435
            return;
436
        }
437
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
438

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

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

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

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

    
518
    private ActionInfo createActionScript(String actionName, String scriptName, String label, String iconName, long position, String tip) {
519
        ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
520

    
521
        Class scriptingExtension = this.getScriptingExtension();
522
        if (scriptingExtension == null) {
523
            logger.warn("Can't create action script '" + actionName + "', can't locate scripting extension");
524
            return null;
525
        }
526
        if (StringUtils.isBlank(iconName)) {
527
            iconName = null;
528
        }
529
        if (StringUtils.isBlank(tip)) {
530
            tip = actionName;
531
        }
532

    
533
        ActionInfo action = actionManager.createAction(scriptingExtension, actionName, label, scriptName, iconName, null, position, tip);
534
        return actionManager.registerAction(action);
535
    }
536

    
537
    @Override
538
    public void run() {
539

    
540
        errors_reset();
541

    
542
        MainFrame mainWindow = PluginsLocator.getMainFrame();
543

    
544
        try {
545
            Configuration configManager = new Configuration();
546
            DynObject config = configManager.load();
547

    
548
            if (config == null) {
549
                PluginsLocator.getMainFrame().messageDialog(
550
                        "_No_se_ha_podido_acceder_a_la_configuracion_de_personalizacion_Consulte_el_registro_de_errores_si_precisa_mas_informacion",
551
                        "_Atencion",
552
                        JOptionPane.WARNING_MESSAGE
553
                );
554
                return;
555
            }
556

    
557
            configureLocale(config);
558
            configureHttpproxy(config);
559
            DynObject httpProxyConfiguration = (DynObject) config.getDynValue("httpproxy");
560
            if (((Boolean) (httpProxyConfiguration.getDynValue("promptUserAndPassword"))).booleanValue()) {
561
                configureHttpproxyUser(config);
562
            }
563

    
564
            configureCRS(config);
565

    
566
            mainWindow.message("_Updating_server_information", JOptionPane.INFORMATION_MESSAGE);
567
            configureServers(
568
                    "WMS",
569
                    "org.gvsig.raster.wms.app.wmsclient",
570
                    (List<DynObject>) config.getDynValue("wmsUrls")
571
            );
572
            configureServers(
573
                    "WMTS",
574
                    "org.gvsig.raster.wmts.app.wmtsclient",
575
                    (List<DynObject>) config.getDynValue("wmtsUrls")
576
            );
577
            configureServers(
578
                    "WCS",
579
                    "org.gvsig.raster.wcs.app.wcsclient",
580
                    (List<DynObject>) config.getDynValue("wcsUrls")
581
            );
582
            configureServers(
583
                    "WFS",
584
                    "org.gvsig.wfs.app.mainplugin",
585
                    (List<DynObject>) config.getDynValue("wfsUrls")
586
            );
587

    
588

    
589
//
590
//            configureAllPlugins(config);
591
//
592
            createActionsScripts(config);
593

    
594
            addTOCActions(config);
595
            addMenuActions(config);
596
            addToolActions(config);
597

    
598
        } catch (Exception ex) {
599
            errors_add("Problems apply defaut configuration.", ex);
600
        }
601

    
602
        if (errors_count() > 0) {
603
            mainWindow.messageDialog(
604
                    "_Se_han_producido_errores_actualizando_la_configuracion_por_defecto_Consulte_el_registro_de_errores_si_precisa_mas_informacion",
605
                    "_Setting_custom_configuration",
606
                    JOptionPane.WARNING_MESSAGE
607
            );
608
        }
609
        installAdditionalPackages();
610
        mainWindow.message(null, JOptionPane.INFORMATION_MESSAGE);
611
    }
612

    
613
    private Set loadDefaultPackages(File packages) throws IOException {
614
        Set defaultPackages = new HashSet<String>();
615

    
616
        List<String> lines = FileUtils.readLines(packages);
617
        defaultPackages.clear();
618
        for (String line : lines) {
619
            line = line.trim();
620
            if (line.startsWith("#") || line.startsWith(";")) {
621
                continue;
622
            }
623
            defaultPackages.add(line.toLowerCase());
624
        }
625
        return defaultPackages;
626
    }
627

    
628
    /**
629
     * Workaround to bug in SimpleTaskStatus of gvSIG 2.2.0
630
     */
631
    private static class MyTaskStatus extends BaseTaskStatus {
632

    
633
        public MyTaskStatus(String title) {
634
            super(title);
635
        }
636

    
637
        public MyTaskStatus(String tittle, long minValue, long maxValue) {
638
            super(tittle, minValue, maxValue);
639
        }
640

    
641
        public void message(String message) {
642
            this.lastModification = new Date();
643
            super.message(message);
644
        }
645

    
646
    }
647

    
648
    private void installAdditionalPackages() {
649
        if (!BooleanUtils.isTrue((Boolean) getProperty("installAdditionalComponents"))) {
650
            return;
651
        }
652

    
653
        File defaultPackagesFile = new File(getPlugin().getPluginDirectory(), "defaultPackages");
654
        if (!defaultPackagesFile.exists()) {
655
            logger.info("Skip additional package instalation (don't exists " + defaultPackagesFile.getAbsolutePath() + ").");
656
            return;
657
        }
658

    
659
        I18nManager i18nManager = ToolsLocator.getI18nManager();
660
        boolean needRestart = false;
661
        SimpleTaskStatus taskStatus = new MyTaskStatus(i18nManager.getTranslation("_Installing_additional_components"));
662
        InstallPackagesPanel dialog = new InstallPackagesPanel(taskStatus);
663
        try {
664
            taskStatus.add();
665
            taskStatus.setAutoremove(true);
666

    
667
            showWindow(
668
                    dialog,
669
                    i18nManager.getTranslation("_Terminating_installation"),
670
                    WindowManager.MODE.WINDOW
671
            );
672
            taskStatus.message(i18nManager.getTranslation("_Preparing_additional_components_installation"));
673

    
674
            PluginsManager pluginsManmager = PluginsLocator.getManager();
675
            InstallerManager installerManager = InstallerLocator.getInstallerManager();
676
            InstallPackageService installer = null;
677
            List<PackageInfo> packagesToInstall = new ArrayList<PackageInfo>();
678
            Set<String> defaultSelectedPacakgeCodes = loadDefaultPackages(
679
                    defaultPackagesFile
680
            );
681

    
682
            installer = installerManager.getInstallPackageService();
683

    
684
            taskStatus.message(i18nManager.getTranslation("_Searching_available_packages"));
685
            installer.addBundlesFromDirectory(pluginsManmager.getInstallFolder(),taskStatus);
686

    
687
            taskStatus.message(i18nManager.getTranslation("_Filtering_packages"));
688
            for (String packageCode : defaultSelectedPacakgeCodes) {
689
                PackageInfo pkg = installer.getPackageInfo(packageCode);
690
                if (pkg != null) {
691
                    File folder = installerManager.getAddonFolder(pkg.getCode());
692
                    if (folder == null) {
693
                        packagesToInstall.add(pkg);
694
                    }
695
                }
696
            }
697
            if (!packagesToInstall.isEmpty()) {
698
                taskStatus.setRangeOfValues(1, packagesToInstall.size());
699
                for (int i = 0; i < packagesToInstall.size(); i++) {
700
                    PackageInfo pkg = packagesToInstall.get(i);
701
                    taskStatus.setCurValue(i + 1);
702
                    taskStatus.message(i18nManager.getTranslation("_Installing_{0}",
703
                            new String[] { pkg.getCode() }
704
                    ));
705
                    try {
706
                        logger.info("install package '" + pkg.getCode() + "'.");
707
                        installer.installPackage(pluginsManmager.getApplicationFolder(), pkg);
708
                        if (needRestart(installer,pkg)) {
709
                            needRestart = true;
710
                        }
711
                    } catch (Throwable th) {
712
                        logger.warn("can't install package '" + pkg.getCode() + "'.", th);
713
                    }
714
                }
715
                taskStatus.message(i18nManager.getTranslation("_Installation_terminated"));
716
                taskStatus.terminate();
717
                setProperty("installAdditionalComponents", Boolean.FALSE);
718
                if (needRestart) {
719
                    dialog.message(i18nManager.getTranslation("_Additional_components_installed_succesfully_Restart_applicaction"));
720
                } else {
721
                    dialog.message(i18nManager.getTranslation("_Additional_components_installed_succesfully"));
722
                }
723
            } else {
724
                taskStatus.message(i18nManager.getTranslation("_Installation_terminated"));
725
                taskStatus.terminate();
726
                dialog.message(i18nManager.getTranslation("_Additional_components_installed_succesfully"));
727
            }
728
            setProperty("installAdditionalComponents", Boolean.FALSE);
729
        } catch (Throwable th) {
730
            taskStatus.cancel();
731
            dialog.message(i18nManager.getTranslation("_Problems_installing_additional_components"));
732
            logger.warn("can't install additional packages.", th);
733

    
734
        } finally {
735
            taskStatus.remove();
736
        }
737
    }
738

    
739
    private boolean needRestart(InstallPackageService installer, PackageInfo pkg) {
740
//        return installer.needRestart(pkg);
741
        if( "plugin".equalsIgnoreCase(pkg.getType()) ) {
742
            return true;
743
        } else if( "symbols".equalsIgnoreCase(pkg.getType()) ) {
744
            return false;
745
        } else if( "jCRS_EPSG".equalsIgnoreCase(pkg.getType()) ) {
746
            return true;
747
        } else {
748
            return true;
749
        }
750

    
751
    }
752
}