Statistics
| Revision:

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

History | View | Annotate | Download (29.1 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", "en");
286
            Locale locale = LocaleUtils.toLocale(localeCode);
287
            localeManager.setCurrentLocale(locale);
288

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

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

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

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

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

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

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

    
387
    private void configureServers(String protocol, String pluginName, List<DynObject> servers) {
388
        if (!getPropertyBoolean("configureOGCServers_" + protocol)) {
389
            return;
390
        }
391
        if( servers==null ) {
392
            logger.info("No servers specifieds for protocol "+protocol+".");
393
            return;
394
        }
395
        if (pluginName == null) {
396
            logger.info("Skip '" + pluginName + "' servers configurations..");
397
            return;
398
        }
399
        PluginServices plugin = getPlugin(pluginName);
400
        if (plugin == null) {
401
            logger.info("Skip '" + pluginName + "' servers configurations. Plugin not installed.");
402
            return;
403
        }
404
        ServerDataPersistence serversDataPersistence = (ServerDataPersistence) plugin.getPluginProperties().getDynValue("Servers");
405
        if (serversDataPersistence == null) {
406
            serversDataPersistence = new ServerDataPersistence(protocol);
407
            plugin.getPluginProperties().setDynValue("Servers", serversDataPersistence);
408
        }
409
        MyServerData serversData = new MyServerData(serversDataPersistence);
410
        
411
        for (int i = 0; i < servers.size(); i++) {
412
            String server = (String) servers.get(i).getDynValue("url");
413
            boolean remove = BooleanUtils.isTrue((Boolean) servers.get(i).getDynValue("remove"));
414
            if (remove) {
415
                serversData.remove(server);
416
                logger.info("Remove '" + protocol + "' server '" + server + "'.");
417
            } else {
418
                if (!serversData.contains(server)) {
419
                    serversData.add(server, protocol);
420
                    logger.info("Insert '" + protocol + "' server '" + server + "'.");
421
                }
422
            }
423
        }
424
        plugin.savePluginProperties();
425
        logger.info("Save properties of plugin '" + pluginName + "'.");
426
        setProperty("configureOGCServers_" + protocol, Boolean.FALSE);
427

    
428
    }
429

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

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

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

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

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

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

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

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

    
535
    @Override
536
    public void run() {
537

    
538
        errors_reset();
539

    
540
        MainFrame mainWindow = PluginsLocator.getMainFrame();
541

    
542
        try {
543
            Configuration configManager = new Configuration();
544
            DynObject config = configManager.load();
545

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

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

    
562
            configureCRS(config);
563

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

    
587
//
588
//            configureAllPlugins(config);
589
//
590
            createActionsScripts(config);
591

    
592
            addTOCActions(config);
593
            addMenuActions(config);
594
            addToolActions(config);
595

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

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

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

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

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

    
631
        public MyTaskStatus(String title) {
632
            super(title);
633
        }
634

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

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

    
644
    }
645

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

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

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

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

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

    
680
            installer = installerManager.getInstallPackageService();
681

    
682
            taskStatus.message(i18nManager.getTranslation("_Searching_available_packages"));
683
            installer.addBundlesFromDirectory(pluginsManmager.getInstallFolder());
684

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

    
732
        } finally {
733
            taskStatus.remove();
734
        }
735
    }
736

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