Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.installer / org.gvsig.installer.lib / org.gvsig.installer.lib.impl / src / main / java / org / gvsig / installer / lib / impl / DefaultInstallerManager.java @ 41916

History | View | Annotate | Download (22.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
/*
25
 * AUTHORS (In addition to CIT):
26
 * 2010 {Prodevelop}   {Task}
27
 */
28
package org.gvsig.installer.lib.impl;
29

    
30
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.net.URL;
35
import java.nio.file.FileSystems;
36
import java.nio.file.Files;
37
import java.nio.file.Path;
38
import java.text.MessageFormat;
39
import java.util.ArrayList;
40
import java.util.Collection;
41
import java.util.HashMap;
42
import java.util.HashSet;
43
import java.util.Iterator;
44
import java.util.List;
45
import java.util.Map;
46
import java.util.Set;
47
import org.apache.commons.lang3.StringUtils;
48

    
49
import org.gvsig.installer.lib.api.DependenciesCalculator;
50
import org.gvsig.installer.lib.api.Dependency;
51
import org.gvsig.installer.lib.api.InstallerManager;
52
import org.gvsig.installer.lib.api.PackageInfo;
53
import org.gvsig.installer.lib.api.PackageInfoReader;
54
import org.gvsig.installer.lib.api.PackageInfoWriter;
55
import org.gvsig.installer.lib.api.Version;
56
import org.gvsig.installer.lib.api.creation.MakePackageService;
57
import org.gvsig.installer.lib.api.creation.MakePluginPackageService;
58
import org.gvsig.installer.lib.api.creation.MakePluginPackageServiceException;
59
import org.gvsig.installer.lib.api.execution.InstallPackageService;
60
import org.gvsig.installer.lib.api.execution.InstallPackageServiceException;
61
import org.gvsig.installer.lib.impl.creation.DefaultMakePackageService;
62
import org.gvsig.installer.lib.impl.info.InstallerInfoFileReader;
63
import org.gvsig.installer.lib.impl.info.InstallerInfoFileWriter;
64
import org.gvsig.installer.lib.spi.InstallerProviderManager;
65
import org.gvsig.tools.ToolsLocator;
66
import org.gvsig.tools.dynobject.DynObject;
67
import org.gvsig.tools.exception.BaseException;
68
import org.gvsig.tools.extensionpoint.ExtensionPoint;
69
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
70
import org.gvsig.tools.service.AbstractManager;
71
import org.gvsig.tools.service.Service;
72
import org.gvsig.tools.service.ServiceException;
73
import org.slf4j.Logger;
74
import org.slf4j.LoggerFactory;
75

    
76
/**
77
 * @author <a href="mailto:jpiera@gvsig.org">Jorge Piera Llodr&aacute;</a>
78
 */
79
public class DefaultInstallerManager extends AbstractManager implements
80
        InstallerManager {
81

    
82
    private static Logger logger = LoggerFactory.getLogger(DefaultInstallerManager.class);
83
            
84
    private static class LocalRepositoryLocation {
85

    
86
        private File location;
87
        private Set<String> types;
88

    
89
        public LocalRepositoryLocation(File localtion, String type) {
90
            this.location = localtion;
91
            this.types = new HashSet<String>();
92
            this.addType(type);
93
        }
94

    
95
        public LocalRepositoryLocation(File localtion) {
96
            this(localtion, null);
97
        }
98

    
99
        public void addType(String type) {
100
            if ( !StringUtils.isBlank(type) ) {
101
                this.types.add(type);
102
            }
103
        }
104

    
105
        public void addType(LocalRepositoryLocation location) {
106
            this.types.addAll(location.getTypes());
107
        }
108

    
109
        public Collection<String> getTypes() {
110
            return this.types;
111
        }
112

    
113
        public File getLocation() {
114
            return this.location;
115
        }
116

    
117
        public String getDefaultType() {
118
            if ( this.types.isEmpty() ) {
119
                return null;
120
            }
121
            return this.types.iterator().next();
122
        }
123

    
124
        public boolean is(File location) {
125
            if ( location.equals(this.location) ) {
126
                return true;
127
            }
128
            return false;
129
        }
130

    
131
        public boolean contains(File file) {
132
            if ( file.getAbsolutePath().startsWith(this.location.getAbsolutePath()) ) {
133
                return true;
134
            }
135
            return false;
136
        }
137
        
138
        public boolean contains(PackageInfo packageInfo) {
139
            if( !this.support(packageInfo.getType()) ) {
140
                return false;
141
            }
142
            String packageInfoName = packageInfo.getCode() + File.separator + PACKAGE_INFO_FILE_NAME;
143
            File packageInfoFile = new File(this.location,packageInfoName);
144
            return packageInfoFile.exists();
145
        }
146
        
147
        public boolean support(String type) {
148
            for( String atype : this.types ) {
149
                if( atype != null ) {
150
                    if( atype.equalsIgnoreCase(type) ) {
151
                        return true;
152
                    }
153
                }
154
            }
155
            return false;
156
        }
157
    }
158

    
159
    private static class LocalRepositoriesLocations extends ArrayList<LocalRepositoryLocation> {
160

    
161
        public LocalRepositoryLocation getLocation(File location) {
162
            Iterator<LocalRepositoryLocation> it = super.iterator();
163
            while ( it.hasNext() ) {
164
                LocalRepositoryLocation x = it.next();
165
                if ( x.is(location) ) {
166
                    return x;
167
                }
168
            }
169
            return null;
170
        }
171

    
172
        public boolean add(LocalRepositoryLocation location) {
173
            LocalRepositoryLocation old = this.getLocation(location.getLocation());
174
            if ( old != null ) {
175
                old.addType(location);
176
                return true;
177
            }
178
            return super.add(location);
179
        }
180

    
181
    }
182

    
183
    private static final String INSTALLER_MANAGER_EXTENSION_POINT = "InstallerManagerExtensionPoint";
184
    private static final String INSTALLER_CREATION_SERVICE_NAME = "InstallerCreationService";
185
    private static final String INSTALLER_EXECUTION_SERVICE_NAME = "InstallerExecutionService";
186
    private ExtensionPointManager extensionPoints = ToolsLocator
187
            .getExtensionPointManager();
188

    
189
    private String packageSetNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspks";
190
    private String packageNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspkg";
191
    private String packageIndexNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspki";
192

    
193
    private URL BaseDownloadURL = null;
194
    private Version version = null;
195
    private List<LocalRepositoryLocation> localRepositoriesLocation = null;
196
    private Map<String,File> defaultRepositoryLocation = null;
197

    
198
    public DefaultInstallerManager() {
199
        super(new DefaultInstallerProviderManager());
200
        this.defaultRepositoryLocation = new HashMap<String,File>();
201
        localRepositoriesLocation = new LocalRepositoriesLocations();
202
    }
203

    
204
    public String getPackageSetNameFormat() {
205
        return packageSetNameFormat;
206
    }
207

    
208
    public void setPackageSetNameFormat(String packageSetNameFormat) {
209
        this.packageSetNameFormat = packageSetNameFormat;
210
    }
211

    
212
    public String getPackageNameFormat() {
213
        return packageNameFormat;
214
    }
215

    
216
    public void setPackageNameFormat(String packageNameFormat) {
217
        this.packageNameFormat = packageNameFormat;
218
    }
219

    
220
    public String getPackageIndexNameFormat() {
221
        return packageIndexNameFormat;
222
    }
223

    
224
    public void setPackageIndexNameFormat(String packageIndexNameFormat) {
225
        this.packageIndexNameFormat = packageIndexNameFormat;
226
    }
227

    
228
    public MakePluginPackageService getMakePluginPackageService()
229
            throws MakePluginPackageServiceException {
230
        ExtensionPoint ep = extensionPoints
231
                .add(INSTALLER_MANAGER_EXTENSION_POINT);
232
        try {
233
            Object[] args = new Object[]{this};
234
            return (MakePluginPackageService) ep.create(
235
                    INSTALLER_CREATION_SERVICE_NAME, args);
236
        } catch (Exception e) {
237
            throw new MakePluginPackageServiceException(
238
                    "Exception creating the installer service to create installers",
239
                    e);
240
        }
241
    }
242

    
243
    public class InstallerCreationException extends
244
            InstallPackageServiceException {
245

    
246
        private static final long serialVersionUID = 759329820705535873L;
247

    
248
        private static final String message = "Error creating the installer service to install plugins";
249

    
250
        private static final String KEY = "_Error_creating_the_installer_service_to_install_plugins";
251

    
252
        public InstallerCreationException(Exception e) {
253
            super(message, e, KEY, serialVersionUID);
254
        }
255

    
256
    }
257

    
258
    public InstallPackageService getInstallPackageService()
259
            throws InstallPackageServiceException {
260
        ExtensionPoint ep = extensionPoints
261
                .add(INSTALLER_MANAGER_EXTENSION_POINT);
262
        try {
263
            Object[] args = new Object[1];
264
            args[0] = this;
265
            return (InstallPackageService) ep.create(
266
                    INSTALLER_EXECUTION_SERVICE_NAME, args);
267
        } catch (Exception e) {
268
            throw new InstallerCreationException(e);
269
        }
270
    }
271

    
272
    public void registerMakePluginPackageService(
273
            Class<? extends MakePluginPackageService> clazz) {
274
        ExtensionPoint extensionPoint = extensionPoints.add(
275
                INSTALLER_MANAGER_EXTENSION_POINT, "");
276
        extensionPoint.append(INSTALLER_CREATION_SERVICE_NAME, "", clazz);
277
    }
278

    
279
    public void registerInstallPackageService(
280
            Class<? extends InstallPackageService> clazz) {
281
        ExtensionPoint extensionPoint = extensionPoints.add(
282
                INSTALLER_MANAGER_EXTENSION_POINT, "");
283
        extensionPoint.append(INSTALLER_EXECUTION_SERVICE_NAME, "", clazz);
284
    }
285

    
286
    public Service getService(DynObject parameters) throws ServiceException {
287
        return null;
288
    }
289

    
290
    public String getPackageSetFileName(PackageInfo info) {
291
        Object[] parameters = getPackageNameFormatParameters(info);
292
        return MessageFormat.format(getPackageSetNameFormat(), parameters);
293
    }
294

    
295
    public String getPackageFileName(PackageInfo info) {
296
        Object[] parameters = getPackageNameFormatParameters(info);
297
        return MessageFormat.format(getPackageNameFormat(), parameters);
298
    }
299

    
300
    public String getPackageIndexFileName(PackageInfo info) {
301
        Object[] parameters = getPackageNameFormatParameters(info);
302
        return MessageFormat.format(getPackageIndexNameFormat(), parameters);
303
    }
304

    
305
    private Object[] getPackageNameFormatParameters(PackageInfo info) {
306
        Object[] parameters = new Object[8];
307
        parameters[PACKAGE_FILE_NAME_FIELDS.GVSIG_VERSION] = info
308
                .getGvSIGVersion();
309
        parameters[PACKAGE_FILE_NAME_FIELDS.NAME] = info.getCode();
310
        parameters[PACKAGE_FILE_NAME_FIELDS.VERSION] = info.getVersion();
311
        parameters[PACKAGE_FILE_NAME_FIELDS.BUILD] = info.getBuild();
312
        parameters[PACKAGE_FILE_NAME_FIELDS.STATE] = info.getState();
313
        parameters[PACKAGE_FILE_NAME_FIELDS.OS] = info.getOperatingSystem();
314
        parameters[PACKAGE_FILE_NAME_FIELDS.ARCH] = info.getArchitecture();
315
        parameters[PACKAGE_FILE_NAME_FIELDS.JVM] = info.getJavaVM();
316
        return parameters;
317
    }
318

    
319
    public PackageInfo[] getInstalledPackages(File pluginsDirectory)
320
            throws MakePluginPackageServiceException {
321
        MakePluginPackageService service = getMakePluginPackageService();
322
        return service.getInstalledPackages();
323
    }
324

    
325
    public PackageInfo[] getInstalledPackages()
326
            throws MakePluginPackageServiceException {
327
        MakePluginPackageService service = getMakePluginPackageService();
328
        return service.getInstalledPackages();
329
    }
330

    
331
    public String getDefaultPackageFileExtension() {
332
        return "gvspkg";
333
    }
334

    
335
    public String getDefaultPackageSetFileExtension() {
336
        return "gvspks";
337
    }
338

    
339
    public String getDefaultIndexSetFileExtension() {
340
        return "gvspki";
341
    }
342

    
343
    public String getOperatingSystem() {
344
        String osname = System.getProperty("os.name");
345
        if ( osname.toLowerCase().startsWith("linux") ) {
346
            return InstallerManager.OS.LINUX;
347
        }
348
        if ( osname.toLowerCase().startsWith("window") ) {
349
            return InstallerManager.OS.WINDOWS;
350
        }
351
        return osname;
352
    }
353

    
354
    public String getArchitecture() {
355
        String osarch = System.getProperty("os.arch");
356
        if ( osarch.toLowerCase().startsWith("i386") ) {
357
            return InstallerManager.ARCH.X86;
358
        }
359
        if ( osarch.toLowerCase().startsWith("x86") ) {
360
            return InstallerManager.ARCH.X86;
361
        }
362
        if ( osarch.toLowerCase().startsWith("amd64") ) {
363
            return InstallerManager.ARCH.X86_64;
364
        }
365
        return osarch;
366
    }
367

    
368
    public Dependency createDependency(PackageInfo packageInfo) {
369
        return new DefaultDependency(packageInfo);
370
    }
371

    
372
    public Dependency createDependency() {
373
        return new DefaultDependency();
374
    }
375

    
376
    public DependenciesCalculator createDependenciesCalculator(
377
            InstallPackageService installService) {
378
        return new DefaultDependenciesCalculator(installService);
379
    }
380

    
381
    public Version createVersion() {
382
        if ( version == null ) {
383
            return new DefaultVersion();
384
        }
385
        Version v = null;
386
        try {
387
            v = (Version) version.clone();
388
        } catch (CloneNotSupportedException e) {
389
            // Version clone can't trow exception
390
        }
391
        return v;
392
    }
393

    
394
    public PackageInfoReader getDefaultPackageInfoReader() {
395
        return new InstallerInfoFileReader();
396
    }
397

    
398
    public PackageInfoWriter getDefaultPackageInfoWriter() {
399
        return new InstallerInfoFileWriter();
400
    }
401

    
402
    public MakePackageService createMakePackage(File packageFolder,
403
            PackageInfo packageInfo) {
404
        return new DefaultMakePackageService(this, packageFolder, packageInfo);
405
    }
406

    
407
    public PackageInfo createPackageInfo() {
408
        return new DefaultPackageInfo();
409
    }
410

    
411
    public PackageInfo createPackageInfo(InputStream stream) throws BaseException {
412
        PackageInfo pkg = new DefaultPackageInfo();
413
        PackageInfoReader reader = this.getDefaultPackageInfoReader();
414
        reader.read(pkg, stream);
415
        return pkg;
416
    }
417

    
418
    public PackageInfo createPackageInfo(File file) throws BaseException {
419
        FileInputStream fis = null;
420
        PackageInfo pkg = null;
421
        try {
422
            fis = new FileInputStream(file);
423
            pkg = this.createPackageInfo(fis);
424
            fis.close();
425
        } catch (Exception ex) {
426

    
427
        } finally {
428
            try {
429
                fis.close();
430
            } catch (IOException ex) {
431
                //
432
            }
433
        }
434
        return pkg;
435
    }
436

    
437
    public URL getDownloadBaseURL() {
438
        return this.BaseDownloadURL;
439
    }
440

    
441
    public String getVersion() {
442
        return this.version.toString();
443
    }
444

    
445
    public void setVersion(Version version) {
446
        try {
447
            this.version = (Version) version.clone();
448
        } catch (CloneNotSupportedException e) {
449
            // This should not happen
450
        }
451

    
452
    }
453

    
454
    public Version getVersionEx() {
455
        try {
456
            return (Version) this.version.clone();
457
        } catch (CloneNotSupportedException e) {
458
            // This should not happen
459
            return null;
460
        }
461
    }
462

    
463
    public void setDownloadBaseURL(URL url) {
464
        this.BaseDownloadURL = url;
465
    }
466

    
467
    public void setVersion(String version) {
468
        if ( this.version == null ) {
469
            this.version = new DefaultVersion();
470
        }
471
        this.version.parse(version);
472
    }
473

    
474
    public File getDefaultLocalAddonRepository() {
475
        File f = this.defaultRepositoryLocation.get("plugin");
476
        return f;
477
    }
478

    
479
    public void setDefaultLocalAddonRepository(File defaultAddonsRepository) {
480
        this.defaultRepositoryLocation.put("plugin", defaultAddonsRepository);
481
        this.localRepositoriesLocation.add(new LocalRepositoryLocation(defaultAddonsRepository, "plugin"));
482
    }
483

    
484
    public void addLocalAddonRepository(File path) {
485
        this.addLocalAddonRepository(path, "plugin");
486
    }
487

    
488
    public File getDefaultLocalAddonRepository(String packageType) {
489
        return this.getDefaultLocalAddonRepository(packageType,ACCESS_READ);
490
    }
491

    
492
    public boolean needAdminRights() {
493
       List<File> folders = getLocalAddonRepositories(); 
494
       for( File folder : folders) {
495
           if( !canWrite(folder) ) {
496
               return true;
497
           }
498
       }
499
       return false;
500
    }
501
    
502
    private boolean canWrite(File f) {
503
        if( !f.canWrite() ) {
504
            return false;
505
        }
506
        // Esto requiere java 1.7 o superior y aun debemos ejecutar con 1.6
507
//        Path path = FileSystems.getDefault().getPath(f.getAbsolutePath());
508
//        boolean b = Files.isWritable(path);
509
//        return b;
510
        
511
//        En MS Windows File.canWrite retorna true aunque luego no se pueden crear 
512
//        escribir en esa carpeta, asi que probamos a crear una carpeta para 
513
//        asegurarnos si se puede escribir realmente.
514
        File f2 = new File(f,"test.dir");
515
        if( f2.mkdir() ) {
516
            f2.delete();
517
            return true;
518
        }
519
        return false;
520
    }
521
    
522
    public File getDefaultLocalAddonRepository(String packageType, int access) {
523
        File f = this.defaultRepositoryLocation.get(packageType);
524
        switch(access) {
525
        case ACCESS_WRITE:
526
            if( canWrite(f) ) {
527
                return f;
528
            }
529
            break;
530
        case ACCESS_READ:
531
        default:
532
            if( f.canRead()) {
533
                return f;
534
            }
535
            break;
536
        }
537
        List<File> repositoriesLocaltions = this.getLocalAddonRepositories(packageType);
538
        for( File repositoryLocation : repositoriesLocaltions ) {
539
            switch(access) {
540
            case ACCESS_WRITE:
541
                if( canWrite(repositoryLocation) ) {
542
                    return repositoryLocation;
543
                }
544
                break;
545
            case ACCESS_READ:
546
            default:
547
                if( repositoryLocation.canRead()) {
548
                    return repositoryLocation;
549
                }
550
                break;
551
            }
552
        }
553
        return null;
554
    }
555

    
556
    public void setDefaultLocalAddonRepository(File defaultAddonsRepository, String packageType) {
557
        this.defaultRepositoryLocation.put(packageType, defaultAddonsRepository);
558
        this.localRepositoriesLocation.add(new LocalRepositoryLocation(defaultAddonsRepository, packageType));
559
    }
560

    
561
    public void addLocalAddonRepository(File path, String type) {
562
        localRepositoriesLocation.add(new LocalRepositoryLocation(path, type));
563
    }
564

    
565
    public String getDefaultLocalRepositoryType(File file) {
566
        Iterator<LocalRepositoryLocation> it = localRepositoriesLocation.iterator();
567
        while ( it.hasNext() ) {
568
            LocalRepositoryLocation location = it.next();
569
            if ( location.contains(file) ) {
570
                return location.getDefaultType();
571
            }
572
        }
573
        return null;
574
    }
575

    
576
    public List<File> getLocalAddonRepositories() {
577
        return this.getLocalAddonRepositories(null);
578
    }
579

    
580
    public List<File> getLocalAddonRepositories(String type) {
581
        List<File> l = new ArrayList<File>();
582
        Iterator<LocalRepositoryLocation> it = localRepositoriesLocation.iterator();
583
        while ( it.hasNext() ) {
584
            LocalRepositoryLocation location = it.next();
585
            if( type==null || location.support(type) ) {
586
                l.add(location.getLocation());
587
            }
588
        }
589
        return l;
590
    }
591

    
592
    public List<File> getAddonFolders() {
593
        return this.getAddonFolders(null);
594
    }
595
    
596
    public List<File> getAddonFolders(String type) {
597
        List<File> addonFolders = new ArrayList<File>();
598

    
599
        // Para cada directorio en la lista de repositorios locales
600
        List<File> localAddonRepositories = this.getLocalAddonRepositories(type);
601
        for ( int i = 0; i < localAddonRepositories.size(); i++ ) {
602
            File repoPath = localAddonRepositories.get(i);
603
            if ( repoPath.isDirectory() && repoPath.exists() ) {
604
                File[] folderRepoList = repoPath.listFiles();
605

    
606
                // recorrer los directorios que haya dentro
607
                for ( int j = 0; j < folderRepoList.length; j++ ) {
608
                    File addonFolder = folderRepoList[j];
609
                    if ( addonFolder.isDirectory() ) {
610
                        File pkginfofile = new File(addonFolder, "package.info");
611
                        if ( pkginfofile.exists() ) {
612
                            addonFolders.add(addonFolder);
613
                        }
614
                    }
615

    
616
                }
617
            }
618
        }
619

    
620
        return addonFolders;
621
    }
622

    
623
    public File getAddonFolder(String code) {
624
        List<File> packagePaths = this.getAddonFolders();
625
        for ( int i = 0; i < packagePaths.size(); i++ ) {
626
            try {
627
                File pkgfile = new File(packagePaths.get(i), "package.info");
628
                PackageInfo pkg = this.createPackageInfo(pkgfile);
629
                if ( pkg.getCode().equalsIgnoreCase(code) ) {
630
                    return packagePaths.get(i);
631
                }
632
            } catch (Exception ex) {
633
                
634
            }
635
        }
636
        return null;
637
    }
638

    
639
    public List<byte[]> getPublicKeys() {
640
        byte[] rawkey;
641
        try {
642
            InputStream is = this.getClass().getResourceAsStream("/org/gvsig/installer/lib/keys/key.public");
643
            rawkey = new byte[is.available()];
644
            is.read(rawkey);
645
            is.close();
646
        } catch (IOException e) {
647
            return null;
648
        }
649
        List<byte[]> keys = new ArrayList<byte[]>();
650
        keys.add(rawkey);
651
        return keys;
652
    }
653

    
654
    public boolean hasProviderToThisPackage(PackageInfo packageInfo) {
655
        InstallerProviderManager provmgr = (InstallerProviderManager) this.getProviderManager();
656
        try {
657
            return provmgr.getProviderFactory(packageInfo.getType()) != null;
658
        } catch (Exception e) {
659
            return false;
660
        }
661
    }
662

    
663
}