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 @ 42044

History | View | Annotate | Download (22.2 KB)

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

    
25
package org.gvsig.installer.lib.impl;
26

    
27
import java.io.File;
28
import java.io.FileInputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.net.URL;
32
import java.text.MessageFormat;
33
import java.util.ArrayList;
34
import java.util.Collection;
35
import java.util.HashMap;
36
import java.util.HashSet;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.Map;
40
import java.util.Set;
41
import org.apache.commons.lang3.StringUtils;
42

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

    
70
/**
71
 * @author <a href="mailto:jpiera@gvsig.org">Jorge Piera Llodr&aacute;</a>
72
 */
73
public class DefaultInstallerManager extends AbstractManager implements
74
        InstallerManager {
75

    
76
    private static Logger logger = LoggerFactory.getLogger(DefaultInstallerManager.class);
77
            
78
    private static class LocalRepositoryLocation {
79

    
80
        private File location;
81
        private Set<String> types;
82

    
83
        public LocalRepositoryLocation(File localtion, String type) {
84
            this.location = localtion;
85
            this.types = new HashSet<String>();
86
            this.addType(type);
87
        }
88

    
89
        public LocalRepositoryLocation(File localtion) {
90
            this(localtion, null);
91
        }
92

    
93
        public void addType(String type) {
94
            if ( !StringUtils.isBlank(type) ) {
95
                this.types.add(type);
96
            }
97
        }
98

    
99
        public void addType(LocalRepositoryLocation location) {
100
            this.types.addAll(location.getTypes());
101
        }
102

    
103
        public Collection<String> getTypes() {
104
            return this.types;
105
        }
106

    
107
        public File getLocation() {
108
            return this.location;
109
        }
110

    
111
        public String getDefaultType() {
112
            if ( this.types.isEmpty() ) {
113
                return null;
114
            }
115
            return this.types.iterator().next();
116
        }
117

    
118
        public boolean is(File location) {
119
            if ( location.equals(this.location) ) {
120
                return true;
121
            }
122
            return false;
123
        }
124

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

    
153
    private static class LocalRepositoriesLocations extends ArrayList<LocalRepositoryLocation> {
154

    
155
        public LocalRepositoryLocation getLocation(File location) {
156
            Iterator<LocalRepositoryLocation> it = super.iterator();
157
            while ( it.hasNext() ) {
158
                LocalRepositoryLocation x = it.next();
159
                if ( x.is(location) ) {
160
                    return x;
161
                }
162
            }
163
            return null;
164
        }
165

    
166
        public boolean add(LocalRepositoryLocation location) {
167
            LocalRepositoryLocation old = this.getLocation(location.getLocation());
168
            if ( old != null ) {
169
                old.addType(location);
170
                return true;
171
            }
172
            return super.add(location);
173
        }
174

    
175
    }
176

    
177
    private static final String INSTALLER_MANAGER_EXTENSION_POINT = "InstallerManagerExtensionPoint";
178
    private static final String INSTALLER_CREATION_SERVICE_NAME = "InstallerCreationService";
179
    private static final String INSTALLER_EXECUTION_SERVICE_NAME = "InstallerExecutionService";
180
    private ExtensionPointManager extensionPoints = ToolsLocator
181
            .getExtensionPointManager();
182

    
183
    private String packageSetNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspks";
184
    private String packageNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspkg";
185
    private String packageIndexNameFormat = "gvSIG-desktop-{0}-{1}-{2}-{4}-{5}-{6}-{7}.gvspki";
186

    
187
    private URL BaseDownloadURL = null;
188
    private Version version = null;
189
    private List<LocalRepositoryLocation> localRepositoriesLocation = null;
190
    private Map<String,File> defaultRepositoryLocation = null;
191

    
192
    public DefaultInstallerManager() {
193
        super(new DefaultInstallerProviderManager());
194
        this.defaultRepositoryLocation = new HashMap<String,File>();
195
        localRepositoriesLocation = new LocalRepositoriesLocations();
196
    }
197

    
198
    public String getPackageSetNameFormat() {
199
        return packageSetNameFormat;
200
    }
201

    
202
    public void setPackageSetNameFormat(String packageSetNameFormat) {
203
        this.packageSetNameFormat = packageSetNameFormat;
204
    }
205

    
206
    public String getPackageNameFormat() {
207
        return packageNameFormat;
208
    }
209

    
210
    public void setPackageNameFormat(String packageNameFormat) {
211
        this.packageNameFormat = packageNameFormat;
212
    }
213

    
214
    public String getPackageIndexNameFormat() {
215
        return packageIndexNameFormat;
216
    }
217

    
218
    public void setPackageIndexNameFormat(String packageIndexNameFormat) {
219
        this.packageIndexNameFormat = packageIndexNameFormat;
220
    }
221

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

    
237
    public class InstallerCreationException extends
238
            InstallPackageServiceException {
239

    
240
        private static final long serialVersionUID = 759329820705535873L;
241

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

    
244
        private static final String KEY = "_Error_creating_the_installer_service_to_install_plugins";
245

    
246
        public InstallerCreationException(Exception e) {
247
            super(message, e, KEY, serialVersionUID);
248
        }
249

    
250
    }
251

    
252
    public InstallPackageService getInstallPackageService()
253
            throws InstallPackageServiceException {
254
        ExtensionPoint ep = extensionPoints
255
                .add(INSTALLER_MANAGER_EXTENSION_POINT);
256
        try {
257
            Object[] args = new Object[1];
258
            args[0] = this;
259
            return (InstallPackageService) ep.create(
260
                    INSTALLER_EXECUTION_SERVICE_NAME, args);
261
        } catch (Exception e) {
262
            throw new InstallerCreationException(e);
263
        }
264
    }
265

    
266
    public void registerMakePluginPackageService(
267
            Class<? extends MakePluginPackageService> clazz) {
268
        ExtensionPoint extensionPoint = extensionPoints.add(
269
                INSTALLER_MANAGER_EXTENSION_POINT, "");
270
        extensionPoint.append(INSTALLER_CREATION_SERVICE_NAME, "", clazz);
271
    }
272

    
273
    public void registerInstallPackageService(
274
            Class<? extends InstallPackageService> clazz) {
275
        ExtensionPoint extensionPoint = extensionPoints.add(
276
                INSTALLER_MANAGER_EXTENSION_POINT, "");
277
        extensionPoint.append(INSTALLER_EXECUTION_SERVICE_NAME, "", clazz);
278
    }
279

    
280
    public Service getService(DynObject parameters) throws ServiceException {
281
        return null;
282
    }
283

    
284
    public String getPackageSetFileName(PackageInfo info) {
285
        Object[] parameters = getPackageNameFormatParameters(info);
286
        return MessageFormat.format(getPackageSetNameFormat(), parameters);
287
    }
288

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

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

    
299
    private Object[] getPackageNameFormatParameters(PackageInfo info) {
300
        Object[] parameters = new Object[8];
301
        parameters[PACKAGE_FILE_NAME_FIELDS.GVSIG_VERSION] = info
302
                .getGvSIGVersion();
303
        parameters[PACKAGE_FILE_NAME_FIELDS.NAME] = info.getCode();
304
        parameters[PACKAGE_FILE_NAME_FIELDS.VERSION] = info.getVersion();
305
        parameters[PACKAGE_FILE_NAME_FIELDS.BUILD] = info.getBuild();
306
        parameters[PACKAGE_FILE_NAME_FIELDS.STATE] = info.getState();
307
        parameters[PACKAGE_FILE_NAME_FIELDS.OS] = info.getOperatingSystem();
308
        parameters[PACKAGE_FILE_NAME_FIELDS.ARCH] = info.getArchitecture();
309
        parameters[PACKAGE_FILE_NAME_FIELDS.JVM] = info.getJavaVM();
310
        return parameters;
311
    }
312

    
313
    public PackageInfo[] getInstalledPackages(File pluginsDirectory)
314
            throws MakePluginPackageServiceException {
315
        MakePluginPackageService service = getMakePluginPackageService();
316
        return service.getInstalledPackages();
317
    }
318

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

    
325
    public String getDefaultPackageFileExtension() {
326
        return "gvspkg";
327
    }
328

    
329
    public String getDefaultPackageSetFileExtension() {
330
        return "gvspks";
331
    }
332

    
333
    public String getDefaultIndexSetFileExtension() {
334
        return "gvspki";
335
    }
336

    
337
    public String getOperatingSystem() {
338
        String osname = System.getProperty("os.name");
339
        if ( osname.toLowerCase().startsWith("linux") ) {
340
            return InstallerManager.OS.LINUX;
341
        }
342
        if ( osname.toLowerCase().startsWith("window") ) {
343
            return InstallerManager.OS.WINDOWS;
344
        }
345
        return osname;
346
    }
347

    
348
    public String getArchitecture() {
349
        String osarch = System.getProperty("os.arch");
350
        if ( osarch.toLowerCase().startsWith("i386") ) {
351
            return InstallerManager.ARCH.X86;
352
        }
353
        if ( osarch.toLowerCase().startsWith("x86") ) {
354
            return InstallerManager.ARCH.X86;
355
        }
356
        if ( osarch.toLowerCase().startsWith("amd64") ) {
357
            return InstallerManager.ARCH.X86_64;
358
        }
359
        return osarch;
360
    }
361

    
362
    public Dependency createDependency(PackageInfo packageInfo) {
363
        return new DefaultDependency(packageInfo);
364
    }
365

    
366
    public Dependency createDependency() {
367
        return new DefaultDependency();
368
    }
369

    
370
    public DependenciesCalculator createDependenciesCalculator(
371
            InstallPackageService installService) {
372
        return new DefaultDependenciesCalculator(installService);
373
    }
374

    
375
    public Version createVersion() {
376
        if ( version == null ) {
377
            return new DefaultVersion();
378
        }
379
        Version v = null;
380
        try {
381
            v = (Version) version.clone();
382
        } catch (CloneNotSupportedException e) {
383
            // Version clone can't trow exception
384
        }
385
        return v;
386
    }
387

    
388
    public PackageInfoReader getDefaultPackageInfoReader() {
389
        return new InstallerInfoFileReader();
390
    }
391

    
392
    public PackageInfoWriter getDefaultPackageInfoWriter() {
393
        return new InstallerInfoFileWriter();
394
    }
395

    
396
    public MakePackageService createMakePackage(File packageFolder,
397
            PackageInfo packageInfo) {
398
        return new DefaultMakePackageService(this, packageFolder, packageInfo);
399
    }
400

    
401
    public PackageInfo createPackageInfo() {
402
        return new DefaultPackageInfo();
403
    }
404

    
405
    public PackageInfo createPackageInfo(InputStream stream) throws BaseException {
406
        PackageInfo pkg = new DefaultPackageInfo();
407
        PackageInfoReader reader = this.getDefaultPackageInfoReader();
408
        reader.read(pkg, stream);
409
        return pkg;
410
    }
411

    
412
    public PackageInfo createPackageInfo(File file) throws BaseException {
413
        FileInputStream fis = null;
414
        PackageInfo pkg = null;
415
        try {
416
            fis = new FileInputStream(file);
417
            pkg = this.createPackageInfo(fis);
418
            fis.close();
419
        } catch (Exception ex) {
420

    
421
        } finally {
422
            try {
423
                fis.close();
424
            } catch (IOException ex) {
425
                //
426
            }
427
        }
428
        return pkg;
429
    }
430

    
431
    public URL getDownloadBaseURL() {
432
        return this.BaseDownloadURL;
433
    }
434

    
435
    public String getVersion() {
436
        return this.version.toString();
437
    }
438

    
439
    public void setVersion(Version version) {
440
        try {
441
            this.version = (Version) version.clone();
442
        } catch (CloneNotSupportedException e) {
443
            // This should not happen
444
        }
445

    
446
    }
447

    
448
    public Version getVersionEx() {
449
        try {
450
            return (Version) this.version.clone();
451
        } catch (CloneNotSupportedException e) {
452
            // This should not happen
453
            return null;
454
        }
455
    }
456

    
457
    public void setDownloadBaseURL(URL url) {
458
        this.BaseDownloadURL = url;
459
    }
460

    
461
    public void setVersion(String version) {
462
        if ( this.version == null ) {
463
            this.version = new DefaultVersion();
464
        }
465
        this.version.parse(version);
466
    }
467

    
468
    public File getDefaultLocalAddonRepository() {
469
        File f = this.defaultRepositoryLocation.get("plugin");
470
        return f;
471
    }
472

    
473
    public void setDefaultLocalAddonRepository(File defaultAddonsRepository) {
474
        this.defaultRepositoryLocation.put("plugin", defaultAddonsRepository);
475
        this.localRepositoriesLocation.add(new LocalRepositoryLocation(defaultAddonsRepository, "plugin"));
476
    }
477

    
478
    public void addLocalAddonRepository(File path) {
479
        this.addLocalAddonRepository(path, "plugin");
480
    }
481

    
482
    public File getDefaultLocalAddonRepository(String packageType) {
483
        return this.getDefaultLocalAddonRepository(packageType,ACCESS_READ);
484
    }
485

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

    
550
    public void setDefaultLocalAddonRepository(File defaultAddonsRepository, String packageType) {
551
        this.defaultRepositoryLocation.put(packageType, defaultAddonsRepository);
552
        this.localRepositoriesLocation.add(new LocalRepositoryLocation(defaultAddonsRepository, packageType));
553
    }
554

    
555
    public void addLocalAddonRepository(File path, String type) {
556
        localRepositoriesLocation.add(new LocalRepositoryLocation(path, type));
557
    }
558

    
559
    public String getDefaultLocalRepositoryType(File file) {
560
        Iterator<LocalRepositoryLocation> it = localRepositoriesLocation.iterator();
561
        while ( it.hasNext() ) {
562
            LocalRepositoryLocation location = it.next();
563
            if ( location.contains(file) ) {
564
                return location.getDefaultType();
565
            }
566
        }
567
        return null;
568
    }
569

    
570
    public List<File> getLocalAddonRepositories() {
571
        return this.getLocalAddonRepositories(null);
572
    }
573

    
574
    public List<File> getLocalAddonRepositories(String type) {
575
        List<File> l = new ArrayList<File>();
576
        Iterator<LocalRepositoryLocation> it = localRepositoriesLocation.iterator();
577
        while ( it.hasNext() ) {
578
            LocalRepositoryLocation location = it.next();
579
            if( type==null || location.support(type) ) {
580
                l.add(location.getLocation());
581
            }
582
        }
583
        return l;
584
    }
585

    
586
    public List<File> getAddonFolders() {
587
        return this.getAddonFolders(null);
588
    }
589
    
590
    public List<File> getAddonFolders(String type) {
591
        List<File> addonFolders = new ArrayList<File>();
592

    
593
        // Para cada directorio en la lista de repositorios locales
594
        List<File> localAddonRepositories = this.getLocalAddonRepositories(type);
595
        for ( int i = 0; i < localAddonRepositories.size(); i++ ) {
596
            File repoPath = localAddonRepositories.get(i);
597
            if ( repoPath.isDirectory() && repoPath.exists() ) {
598
                File[] folderRepoList = repoPath.listFiles();
599

    
600
                // recorrer los directorios que haya dentro
601
                for ( int j = 0; j < folderRepoList.length; j++ ) {
602
                    File addonFolder = folderRepoList[j];
603
                    if ( addonFolder.isDirectory() ) {
604
                        File pkginfofile = new File(addonFolder, "package.info");
605
                        if ( pkginfofile.exists() ) {
606
                            addonFolders.add(addonFolder);
607
                        }
608
                    }
609

    
610
                }
611
            }
612
        }
613

    
614
        return addonFolders;
615
    }
616

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

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

    
648
    public boolean hasProviderToThisPackage(PackageInfo packageInfo) {
649
        InstallerProviderManager provmgr = (InstallerProviderManager) this.getProviderManager();
650
        try {
651
            return provmgr.getProviderFactory(packageInfo.getType()) != null;
652
        } catch (Exception e) {
653
            return false;
654
        }
655
    }
656

    
657
}