-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathPackageManager.java
2394 lines (2098 loc) · 95.7 KB
/
PackageManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* File PackageManager.java
*
* Copyright (C) 2010 Remco Bouckaert [email protected]
*
* This file is part of BEAST2.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*
* Parts copied from WEKA ClassDiscovery.java
* Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
*
*/
package beast.pkgmgmt;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* This class is used to manage beast 2 packages, and can
* - install a new package
* - un-install an package
* - list directories that may contain packages
* - load jars from installed packages
* - discover classes in packages that implement a certain interface or a derived from a certain class
*/
// TODO: on windows allow installation on drive D: and pick up add-ons in drive C:
public class PackageManager {
public static final BEASTVersion beastVersion = BEASTVersion.INSTANCE;
public enum UpdateStatus {AUTO_CHECK_AND_ASK, AUTO_UPDATE, DO_NOT_CHECK};
// public final static String[] IMPLEMENTATION_DIR = {"beast", "snap"};
public final static String TO_DELETE_LIST_FILE = "toDeleteList";
public final static String TO_INSTALL_LIST_FILE = "toInstallList";
public final static String BEAST_PACKAGE_NAME = "BEAST";
public final static String BEAST_BASE_PACKAGE_NAME = "BEAST.base";
public final static String BEAST_APP_PACKAGE_NAME = "BEAST.app";
public final static String PACKAGES_XML = "https://raw.githubusercontent.com/CompEvol/CBAN/master/packages" +
BEASTVersion.INSTANCE.getMajorVersion() +".xml";
private final static Set<String> RECOMMENDED_PACKAGES = new HashSet<>(Arrays.asList("ORC", "starbeast3"));
public final static String ARCHIVE_DIR = "archive";
// flag to indicate archive directory and version numbers in directories are required
private static boolean useArchive = false;
public static void useArchive(boolean _useArchive) {
useArchive = _useArchive;
}
public static final String INSTALLED = "installed";
public static final String NOT_INSTALLED = "not installed";
public static final String NO_CONNECTION_MESSAGE = "Could not get an internet connection. "
+ "The " + BEAST_PACKAGE_NAME + " Package Manager needs internet access in order to list available packages and download them for installation. "
+ "Possibly, some software (like security software, or a firewall) blocks the " + BEAST_PACKAGE_NAME + " Package Manager. "
+ "If so, you need to reconfigure such software to allow access.";
/**
* Exception thrown when reading a package repository fails.
*/
public static class PackageListRetrievalException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Constructor for new exception.
*
* @param message Message explaining what went wrong
* @param cause First exception thrown when processing package repositories
*/
public PackageListRetrievalException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Exception thrown when an operation fails due to package dependency issues.
*/
public static class DependencyResolutionException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Constructor for new exception
*
* @param message message explaining what the dependency problem was.
*/
public DependencyResolutionException(String message) {
super(message);
}
}
/**
* flag indicating add ons have been loaded at least once *
*/
static boolean externalJarsLoaded = false;
/**
* list of all classes found in the class path *
*/
private static List<String> all_classes;
/**
* @return URLs containing list of downloadable packages.
* @throws java.net.MalformedURLException
*/
public static List<URL> getRepositoryURLs() throws MalformedURLException {
List<URL> URLs = new ArrayList<URL>();
URLs.add(new URL(PACKAGES_XML));
//# url
//packages.url=http://...
String urls = Utils6.getBeautiProperty("packages.url");
if (urls != null) {
for (String userURLString : urls.split(",")) {
URLs.add(new URL(userURLString));
}
}
return URLs;
}
/**
* Write any third-party package repository URLs to the options file.
*
* @param urls List of URLs. The first is assumed to be the central
* package repository and is thus ignored.
*/
public static void saveRepositoryURLs(List<URL> urls) {
// RRB: if all urls removed, the old urls still pop up when restarting?
if (urls.size()<1)
return;
// Modify property
if (urls.size()>1) {
StringBuilder sb = new StringBuilder("");
for (int i=1; i<urls.size(); i++) {
if (i>1)
sb.append(",");
sb.append(urls.get(i));
}
Utils6.saveBeautiProperty("packages.url", sb.toString());
} else {
Utils6.saveBeautiProperty("packages.url", null);
}
}
/**
* Look through BEAST directories for installed packages and add these
* to the package database.
*
* @param packageMap package database
*/
public static void addInstalledPackages(Map<String, Package> packageMap) {
for (String dir : getBeastDirectories()) {
File versionXML = new File(dir + "/version.xml");
if (!versionXML.exists())
continue;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(versionXML);
doc.normalize();
// get name and version of package
Element packageElement = doc.getDocumentElement();
String packageName = packageElement.getAttribute("name");
String packageVersionString = packageElement.getAttribute("version");
Package pkg;
if (packageMap.containsKey(packageName)) {
pkg = packageMap.get(packageName);
} else {
pkg = new Package(packageName);
packageMap.put(packageName, pkg);
}
if (packageElement.hasAttribute("projectURL"))
pkg.setProjectURL(new URL(packageElement.getAttribute("projectURL")));
PackageVersion installedVersion = new PackageVersion(packageVersionString);
if (packageElement.hasAttribute("projectURL") &&
!(pkg.getLatestVersion() != null && installedVersion.compareTo(pkg.getLatestVersion())<0))
pkg.setProjectURL(new URL(packageElement.getAttribute("projectURL")));
Set<PackageDependency> installedVersionDependencies =
new TreeSet<PackageDependency>(new Comparator<PackageDependency>() {
@Override
public int compare(PackageDependency o1, PackageDependency o2) {
return o1.dependencyName.compareTo(o2.dependencyName);
}
});
// get dependencies of add-n
NodeList nodes = doc.getElementsByTagName("depends");
for (int i = 0; i < nodes.getLength(); i++) {
Element dependson = (Element) nodes.item(i);
String dependencyName = dependson.getAttribute("on");
String atLeastString = dependson.getAttribute("atleast");
String atMostString = dependson.getAttribute("atmost");
PackageDependency dependency = new PackageDependency(
dependencyName,
atLeastString.isEmpty() ? null : new PackageVersion(atLeastString),
atMostString.isEmpty() ? null : new PackageVersion(atMostString));
installedVersionDependencies.add(dependency);
}
pkg.setInstalled(installedVersion, installedVersionDependencies);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Manually set currently-installed BEAST 2 version if not already set
// This can happen when the BEAST package is not installed (perhaps due to
// file access issues)
Package beastPkg;
if (packageMap.containsKey(BEAST_BASE_PACKAGE_NAME)) {
beastPkg = packageMap.get(BEAST_BASE_PACKAGE_NAME);
} else {
beastPkg = new Package(BEAST_BASE_PACKAGE_NAME);
packageMap.put(BEAST_BASE_PACKAGE_NAME, beastPkg);
}
if (!beastPkg.isInstalled()) {
PackageVersion beastPkgVersion = new PackageVersion(beastVersion.getVersion());
Set<PackageDependency> beastPkgDeps = new TreeSet<PackageDependency>();
beastPkg.setInstalled(beastPkgVersion, beastPkgDeps);
}
}
/**
* Look through the packages defined in the XML files reached by the repository URLs
* and add these packages to the package database.
*
* @param packageMap package database
* @throws PackageListRetrievalException when one or more XMLs cannot be retrieved
*/
public static void addAvailablePackages(Map<String, Package> packageMap) throws PackageListRetrievalException {
List<URL> urls;
try {
urls = getRepositoryURLs();
} catch (MalformedURLException e) {
throw new PackageListRetrievalException("Error parsing one or more repository URLs.", e);
}
List<URL> brokenPackageRepositories = new ArrayList<URL>();
Exception firstException = null;
for (URL url : urls) {
InputStream is = null;
try {
is = url.openStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(is));
Element rootElement = document.getDocumentElement(); // <packages>
NodeList nodes = rootElement.getChildNodes();
for(int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if(node instanceof Element){
Element element = (Element) node;
String packageName = element.getAttribute("name");
Package pkg;
if (packageMap.containsKey(packageName)) {
pkg = packageMap.get(packageName);
} else {
pkg = new Package(packageName);
// packageMap.put(packageName, pkg); // issue 754
}
pkg.setDescription(element.getAttribute("description"));
PackageVersion packageVersion = new PackageVersion(element.getAttribute("version"));
if (element.hasAttribute("projectURL") &&
!(pkg.getLatestVersion() != null && packageVersion.compareTo(pkg.getLatestVersion())<0))
pkg.setProjectURL(new URL(element.getAttribute("projectURL")));
Set<PackageDependency> packageDependencies = new HashSet<PackageDependency>();
NodeList depNodes = element.getElementsByTagName("depends");
for (int j = 0; j < depNodes.getLength(); j++) {
Element dependson = (Element) depNodes.item(j);
String dependencyName = dependson.getAttribute("on");
String atLeastString = dependson.getAttribute("atleast");
String atMostString = dependson.getAttribute("atmost");
PackageDependency dependency = new PackageDependency(
dependencyName,
atLeastString.isEmpty() ? null : new PackageVersion(atLeastString),
atMostString.isEmpty() ? null : new PackageVersion(atMostString));
packageDependencies.add(dependency);
}
URL packageURL = new URL(element.getAttribute("url"));
pkg.addAvailableVersion(packageVersion, packageURL, packageDependencies);
// issue 754 Package manager should make project links compulsory
if (pkg.isValidFormat()) {
packageMap.put(packageName, pkg);
} else{
String urlStr = pkg.getProjectURL()==null ? "null" : pkg.getProjectURL().toString();
System.err.println("Warning: filter " + packageName + " from package manager " +
" because of invalid project URL " + urlStr + " !");
}
}
}
is.close();
} catch (IOException e) {
if (brokenPackageRepositories.isEmpty())
firstException = e;
brokenPackageRepositories.add(url);
} catch (ParserConfigurationException e) {
if (brokenPackageRepositories.isEmpty())
firstException = e;
brokenPackageRepositories.add(url);
} catch (SAXException e) {
if (brokenPackageRepositories.isEmpty())
firstException = e;
brokenPackageRepositories.add(url);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (!brokenPackageRepositories.isEmpty()) {
String message = "Error reading the following package repository URLs:";
for (URL url : brokenPackageRepositories)
message += " " + url;
throw new PackageListRetrievalException(message, firstException);
}
}
/**
* Looks through packages to be installed and uninstalls any that are already installed but
* do not match the version that is to be installed. Packages that are already installed and do
* match the version required are removed from packagesToInstall.
*
* @param packagesToInstall map from packages to versions to install
* @param useAppDir if fause, use user directory, otherwise use application directory
* @param customDir custom installation directory.
* @throws IOException thrown if packages cannot be deleted and delete list file cannot be written
*/
public static void prepareForInstall(Map<Package, PackageVersion> packagesToInstall, boolean useAppDir, String customDir) throws IOException {
if (useArchive) {
return;
}
Map<Package, PackageVersion> ptiCopy = new HashMap<Package, PackageVersion>(packagesToInstall);
for (Map.Entry<Package, PackageVersion> entry : ptiCopy.entrySet()) {
Package thisPkg = entry.getKey();
PackageVersion thisPkgVersion = entry.getValue();
if (thisPkg.isInstalled()) {
if (thisPkg.getInstalledVersion().equals(thisPkgVersion))
packagesToInstall.remove(thisPkg);
else
uninstallPackage(thisPkg, useAppDir, customDir);
}
}
if (getToDeleteListFile().exists()) {
// Write to-install file
// RRB: what are the following two lines for?
//File toDeleteList = getToDeleteListFile();
//FileWriter outfile = new FileWriter(toDeleteList, true);
PrintStream ps = null;
try {
ps = new PrintStream(getToInstallListFile());
for (Map.Entry<Package, PackageVersion> entry : packagesToInstall.entrySet()) {
ps.println(entry.getKey() + ":" + entry.getValue());
}
ps.close();
} catch (IOException ex) {
message("Error writing to-install file: " + ex.getMessage() +
" Installation may not resume successfully after restart.");
}
}
}
/**
* Download and install specified versions of packages. Note that
* this method does not check dependencies. It is assumed the contents
* of packagesToInstall has been assembled by fillOutDependencies.
*
* It is further assumed that the URL points to a zip file containing
* a directory lib containing jars used by the package, as well as
* a directory named templates containing BEAUti XML templates.
*
* @param packagesToInstall map from packages to versions to install
* @param useAppDir if false, use user directory, otherwise use application directory
* @param customDir custom installation directory.
* @return list of strings representing directories into which packages were installed
* @throws IOException if URL cannot be accessed for some reason
*/
public static Map<String, String> installPackages(Map<Package, PackageVersion> packagesToInstall, boolean useAppDir, String customDir) throws IOException {
closeClassLoader();
Map<String, String> dirList = new HashMap<String, String>();
for (Map.Entry<Package, PackageVersion> entry : packagesToInstall.entrySet()) {
Package thisPkg = entry.getKey();
PackageVersion thisPkgVersion = entry.getValue();
URL templateURL = thisPkg.getVersionURL(thisPkgVersion);
// check the URL exists
HttpURLConnection huc = (HttpURLConnection) templateURL.openConnection();
huc.setRequestMethod("HEAD");
int responseCode = huc.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
// RRB: should be "if (responseCode != HttpURLConnection.HTTP_OK)"
// but package file hosted on github (which are most of them)
// produce a HttpURLConnection.HTTP_FORBIDDEN for some reason
throw new IOException("Could not find package at URL\n" + templateURL + "\n"
+ "The server may be bussy, or network may be down.\n"
+ "If you suspect there is a problem with the URL \n"
+ "(the URL may have a typo, or the file was removed)\n"
+ "please contact the package maintainer.\n");
}
// create directory
ReadableByteChannel rbc = Channels.newChannel(templateURL.openStream());
String dirName = getPackageDir(thisPkg, thisPkgVersion, useAppDir, customDir);
File dir = new File(dirName);
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new IOException("Could not create directory " + dirName);
}
}
// grab file from URL
String zipFile = dirName + "/" + thisPkg.getName() + ".zip";
FileOutputStream fos = new FileOutputStream(zipFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
// unzip archive
doUnzip(zipFile, dirName);
fos.close();
// sanity check: does this package contains services that clash
// TODO: what if this is an update, not a fresh package installation
String nameSpaceCheck = null;
try {
nameSpaceCheck = hasNamespaceClash(thisPkg.getName(), dirName);
} catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}
if (nameSpaceCheck != null) {
// remove all files from the package and abort installation
deleteRecursively(dir, new ArrayList<>());
throw new RuntimeException(nameSpaceCheck);
}
dirList.put(thisPkg.getName(), dirName);
}
// make sure the class path is updated next time BEAST is started
Utils6.saveBeautiProperty("package.path", null);
return dirList;
}
private static String hasNamespaceClash(String packageName, String dirName) throws SAXException, IOException, ParserConfigurationException {
// load services from version.xml
File versionFile = new File(dirName + "/version.xml");
Map<String,Set<String>> services = null;
if (versionFile.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(versionFile);
services = parseServices(doc);
}
// check none of the services clashes with already loaded services
for (String service : services.keySet()) {
Set<String> s = services.get(service);
String existingNamespace = BEASTClassLoader.usesExistingNamespaces(s);
if (existingNamespace != null) {
return "Programmer error: One of the services (" + service + ") in package "
+ packageName + " uses a namespace that is already in use: " + existingNamespace
+ ". Package " + packageName + " is NOT loaded and will be removed";
}
}
return null;
}
public static String getPackageDir(Package thisPkg, PackageVersion thisPkgVersion, boolean useAppDir, String customDir) {
String dirName = (useAppDir ? getPackageSystemDir() : getPackageUserDir()) +
(useArchive ? "/" + ARCHIVE_DIR : "") +
"/" + thisPkg.getName() +
(useArchive ? "/" + thisPkgVersion.versionString : "");
if (customDir != null) {
dirName = customDir +
(useArchive ? "/" + ARCHIVE_DIR : "") +
"/" + thisPkg.getName() +
(useArchive ? "/" + thisPkgVersion.versionString : "");
}
return dirName;
}
/**
* Get list of installed packages that depend on pkg.
*
* @param pkg package for which to retrieve installed dependencies
* @param packageMap package database
* @return list of names of installed packages dependent on pkg.
*/
public static List<String> getInstalledDependencyNames(Package pkg, Map<String, Package> packageMap) {
List<String> dependencies = new ArrayList<String>();
for (Package thisPkg : packageMap.values()) {
if (thisPkg.equals(pkg))
continue;
if (!thisPkg.isInstalled())
continue;
for (PackageDependency dependency : thisPkg.getInstalledVersionDependencies()) {
if (dependency.dependencyName.equals(pkg.getName()))
dependencies.add(thisPkg.getName());
}
}
return dependencies;
}
/**
* Uninstall the given package. Like installPackages(), this method does not perform any dependency
* checking - it just blindly removes the specified package. This is so that the method can be called
* while an installation is in process without falling over because of broken intermediate states.
*
* Before using, call getInstalledDependencies() to check for potential problems.
*
* @param pkg package to uninstall
* @param useAppDir if false, use user directory, otherwise use application directory
* @param customDir custom installation directory.
* @return name of directory package was removed from, or null if the package was not removed.
* @throws IOException thrown if packages cannot be deleted and delete list file cannot be written
*/
public static String uninstallPackage(Package pkg, boolean useAppDir, String customDir) throws IOException {
return uninstallPackage(pkg, null, useAppDir, customDir);
}
public static String uninstallPackage(Package pkg, PackageVersion pkgVersion, boolean useAppDir, String customDir) throws IOException {
closeClassLoader();
if (pkgVersion == null) {
pkgVersion = pkg.getInstalledVersion();
}
String dirName = getPackageDir(pkg, pkgVersion, useAppDir, customDir);
File dir = new File(dirName);
if (!dir.exists()) {
useArchive = !useArchive;
dirName = getPackageDir(pkg, pkgVersion, useAppDir, customDir);
dir = new File(dirName);
useArchive = !useArchive;
}
unloadPackage(dir);
List<File> deleteFailed = new ArrayList<File>();
deleteRecursively(dir, deleteFailed);
if (useArchive) {
// delete package directory, if it is empty
File parent = dir.getParentFile();
if (parent.list().length == 0) {
parent.delete();
}
}
// write deleteFailed to file
if (deleteFailed.size() > 0) {
File toDeleteList = getToDeleteListFile();
FileWriter outfile = new FileWriter(toDeleteList, true);
for (File file : deleteFailed) {
outfile.write(file.getAbsolutePath() + "\n");
}
outfile.close();
}
// make sure the class path is updated next time BEAST is started
Utils6.saveBeautiProperty("package.path", null);
return dirName;
}
/**
* Close class loader so that locks on jar files are released, which may prevent
* files being replaced on Windows.
* http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html#close%28%29
*
* This allows smooth upgrading of BEAST versions using the package manager. Without
* this, there is no way to upgrade BEAST since the PackageManager is part of the
* BEAST.jar file that is loaded and needs to be replaced.
*
* Side effect is that after installing a package, opening a new BEAUti instance
* will fail (Windows only).
*
*/
private static void closeClassLoader() {
try {
if (Utils6.isWindows() && Utils6.getMajorJavaVersion() == 8) {
// this class cast exception works on java 8, but not java 9 or above
URLClassLoader sysLoader = (URLClassLoader) PackageManager.class.getClassLoader();
// sysLoader.close(); // <= only since Java 1.7, so should be commented out for
// build of launcher.jar with java 6 compatibility
}
//} catch (IOException e) {
// System.err.println("Could not close ClassLoader: " + e.getMessage());
} catch (ClassCastException e) {
System.err.println("Could not close ClassLoader: " + e.getMessage());
}
}
private static void unloadPackage(File dir) {
File versionFile = new File(dir.getPath() + "/version.xml");
if (versionFile.exists()) {
try {
// print name and version of package
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(versionFile);
Element packageElement = doc.getDocumentElement();
String packageName = packageElement.getAttribute("name");
Map<String,Set<String>> services = parseServices(doc);
BEASTClassLoader.delService(services, packageName);
} catch (Exception e) {
// ignore
e.printStackTrace();
}
}
}
private static void deleteRecursively(File file, List<File> deleteFailed) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
deleteRecursively(f, deleteFailed);
}
}
if (!file.delete()) {
deleteFailed.add(file);
}
}
/**
* unzip zip archive *
*/
public static void doUnzip(String inputZip, String destinationDirectory) throws IOException {
int BUFFER = 2048;
File sourceZipFile = new File(inputZip);
File unzipDestinationDirectory = new File(destinationDirectory);
// Open Zip file for reading
ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
// Create an enumeration of the entries in the zip file
Enumeration<?> zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(unzipDestinationDirectory + "/" + currentEntry);
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
zipFile.close();
}
/**
* @return directory where to install packages for users *
*/
public static String getPackageUserDir() {
return Utils6.getPackageUserDir(BEAST_PACKAGE_NAME);
}
/**
* @return directory where system wide packages reside *
*/
public static String getPackageSystemDir() {
return Utils6.getPackageSystemDir(BEAST_PACKAGE_NAME);
}
/**
* Returns directory where BEAST installation resides, based on the location of the jar containing the
* beast.pkgmgmt.PackageManager class file. This assumes that the parent directory of the launcher.jar is the base install
* directory.
*
* @return string representation of BEAST install directory or null if this directory cannot be identified.
*/
public static String getBEASTInstallDir() {
return getInstallDir(BEAST_PACKAGE_NAME, "beast.pkgmgmt.PackageManager");
}
public static String getInstallDir(String application, String mainClass) {
String prefix = application.toLowerCase();
// Allow users to explicitly set install directory - handy for programmers
if (System.getProperty(prefix + ".install.dir") != null)
return System.getProperty(prefix + ".install.dir");
URL u;
try {
u = BEASTClassLoader.forName(mainClass).getProtectionDomain().getCodeSource().getLocation();
} catch (ClassNotFoundException e) {
// e.printStackTrace();
return null;
}
String s = u.getPath();
File beastJar = new File(s);
// Log.trace.println("BeastMain found in " + beastJar.getPath());
if (!beastJar.getName().toLowerCase().endsWith(".jar")) {
return null;
}
if (beastJar.getParentFile() != null) {
return beastJar.getParentFile().getParent();
} else {
return null;
}
}
/**
* @return file containing list of files that need to be deleted
* but could not be deleted. This can happen when uninstalling packages
* on windows, which locks jar files loaded by java.
*/
public static File getToDeleteListFile() {
return new File(getPackageUserDir() + "/" + TO_DELETE_LIST_FILE);
}
/**
* Delete files that could not be deleted earlier due to jar locking.
*/
private static void processDeleteList() {
File toDeleteListFile = getToDeleteListFile();
if (toDeleteListFile.exists()) {
try {
BufferedReader fin = new BufferedReader(new FileReader(toDeleteListFile));
while (fin.ready()) {
String str = fin.readLine();
File file = new File(str);
file.delete();
}
fin.close();
toDeleteListFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Obtain file containing list of packages that need to be installed
* at startup. This file only exists when packages have failed to upgrade
* due to jar file locking on Windows.
*
* @return to-install file
*/
public static File getToInstallListFile() {
return new File(getPackageUserDir() + "/" + TO_INSTALL_LIST_FILE);
}
/**
* Completes installation procedure if packages could not be upgraded due to
* Windows preventing the deletion of jar files.
*
* @param packageMap package database
*/
private static void processInstallList(Map<String, Package> packageMap) {
File toInstallListFile = getToInstallListFile();
if (toInstallListFile.exists()) {
try {
addAvailablePackages(packageMap);
} catch (PackageListRetrievalException e) {
message("Failed to resume package installation due to package list retrieval error: " + e.getMessage());
toInstallListFile.delete();
return;
}
Map<Package, PackageVersion> packagesToInstall = new HashMap<Package, PackageVersion>();
BufferedReader fin = null;
try {
fin = new BufferedReader(new FileReader(toInstallListFile));
String line;
while ((line = fin.readLine()) != null) {
String[] nameVerPair = line.split(":");
Package pkg = packageMap.get(nameVerPair[0]);
PackageVersion ver = new PackageVersion(nameVerPair[1]);
packagesToInstall.put(pkg, ver);
}
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
installPackages(packagesToInstall, false, null);
} catch (IOException e) {
message("Failed to install packages due to I/O error: " + e.getMessage());
}
toInstallListFile.delete();
}
}
/**
* return list of directories that may contain packages *
*/
public static List<String> getBeastDirectories() {
List<String> dirs = new ArrayList<String>();
// check if there is the BEAST environment variable is set
if (PackageManager.getBeastPackagePathProperty() != null) {
String BEAST = PackageManager.getBeastPackagePathProperty();
for (String dirName : BEAST.split(":")) {
dirs.add(dirName);
}
}
// add user package directory
dirs.add(getPackageUserDir());
// add application package directory
dirs.add(getPackageSystemDir());
// add BEAST installation directory
if (getBEASTInstallDir() != null)
dirs.add(getBEASTInstallDir());
// pick up directories in class path, useful when running in an IDE
String strClassPath = System.getProperty("java.class.path");
String [] paths = strClassPath.split(":");
for (String path : paths) {
if (!path.endsWith(".jar")) {
path = path.replaceAll("\\\\","/");
if (path.contains("/")) {
path = path.substring(0, path.lastIndexOf("/"));
// deal with the way Mac's appbundler sets up paths
path = path.replaceAll("/[^/]*/Contents/Java", "");
// exclude Intellij build path out/production
if (!dirs.contains(path) && !path.contains("production")) {
dirs.add(path);
}
}
}
}
// subdirectories that look like they may contain an package
// this is detected by checking the subdirectory contains a lib or
// templates directory
List<String> subDirs = new ArrayList<String>();
for (String dirName : dirs) {
File dir = new File(dirName);
if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files == null)
continue;
for (File file : files) {
if (file.isDirectory()) {
File versionFile = new File(file, "version.xml");
if (versionFile.exists())
subDirs.add(file.getAbsolutePath());
}
}
}
}
subDirs.addAll(dirs);
dirs = subDirs;
dirs.addAll(getLatestBeastArchiveDirectories(dirs));
return dirs;
}
/*
* Get directories from archive, if not already loaded when traversing visitedDirs.
* Only add the latest version from the archive.
*/
private static List<String> getLatestBeastArchiveDirectories(List<String> visitedDirs) {
List<String> dirs = new ArrayList<String>();
String FILESEPARATOR = "/"; //(Utils6.isWindows() ? "\\" : "/");
String dir = getPackageUserDir() + FILESEPARATOR + ARCHIVE_DIR;
File archiveDir = new File(dir);
if (archiveDir.exists()) {
// determine which packages will already be loaded
Set<String> alreadyLoaded = new HashSet<String>();