forked from bndtools/bnd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProject.java
3695 lines (3191 loc) · 105 KB
/
Project.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
package aQute.bnd.build;
import static aQute.bnd.build.Container.toPaths;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.service.repository.ContentNamespace;
import org.osgi.service.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.build.Container.TYPE;
import aQute.bnd.build.ProjectBuilder.ArtifactInfoImpl;
import aQute.bnd.build.ProjectBuilder.BuildInfoImpl;
import aQute.bnd.exceptions.ConsumerWithException;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.exporter.executable.ExecutableJarExporter;
import aQute.bnd.exporter.runbundles.RunbundlesExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.help.Syntax;
import aQute.bnd.help.instructions.ProjectInstructions;
import aQute.bnd.help.instructions.ProjectInstructions.StaleTest;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Pom;
import aQute.bnd.maven.support.ProjectPom;
import aQute.bnd.memoize.CloseableMemoize;
import aQute.bnd.memoize.Memoize;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Instruction;
import aQute.bnd.osgi.Instructions;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Packages;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.osgi.eclipse.EclipseClasspath;
import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.bnd.osgi.resource.ResourceBuilder;
import aQute.bnd.osgi.resource.ResourceUtils;
import aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability;
import aQute.bnd.service.BndListener;
import aQute.bnd.service.CommandPlugin;
import aQute.bnd.service.DependencyContributor;
import aQute.bnd.service.Deploy;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.RepositoryPlugin.PutOptions;
import aQute.bnd.service.RepositoryPlugin.PutResult;
import aQute.bnd.service.Scripter;
import aQute.bnd.service.Strategy;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.action.NamedAction;
import aQute.bnd.service.export.Exporter;
import aQute.bnd.service.release.ReleaseBracketingPlugin;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.bnd.stream.MapStream;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.collections.Iterables;
import aQute.lib.converter.Converter;
import aQute.lib.io.FileTree;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.command.Command;
import aQute.libg.generics.Create;
import aQute.libg.glob.Glob;
import aQute.libg.qtokens.QuotedTokenizer;
import aQute.libg.reporter.ReporterMessages;
import aQute.libg.sed.Sed;
import aQute.libg.tuple.Pair;
/**
* This class is NOT threadsafe
*/
public class Project extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Project.class);
class RefreshData implements AutoCloseable {
final Memoize<Parameters> installRepositories;
final CloseableMemoize<ProjectGenerate> generate;
RefreshData() {
installRepositories = Memoize.supplier(() -> new Parameters(mergeProperties(BUILDREPO), Project.this));
generate = CloseableMemoize.closeableSupplier(() -> new ProjectGenerate(Project.this));
}
@Override
public void close() {
IO.close(generate);
}
}
final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy";
public final static String BNDFILE = "bnd.bnd";
final static Path BNDPATH = Paths.get(BNDFILE);
public final static String BNDCNF = "cnf";
public final static String SHA_256 = "SHA-256";
final Workspace workspace;
private final AtomicBoolean preparedPaths = new AtomicBoolean();
private final Set<Project> dependenciesFull = new LinkedHashSet<>();
private final Set<Project> dependenciesBuild = new LinkedHashSet<>();
private final Set<Project> dependenciesTest = new LinkedHashSet<>();
private final Set<Project> dependents = new LinkedHashSet<>();
final Collection<Container> classpath = new LinkedHashSet<>();
final Collection<Container> buildpath = new LinkedHashSet<>();
final Collection<Container> testpath = new LinkedHashSet<>();
final Collection<Container> runpath = new LinkedHashSet<>();
final Collection<Container> runbundles = new LinkedHashSet<>();
final Collection<Container> runfw = new LinkedHashSet<>();
File runstorage;
private final RepoCollector repoCollector;
final Map<File, Attrs> sourcepath = new LinkedHashMap<>();
final Collection<File> allsourcepath = new LinkedHashSet<>();
final Collection<Container> bootclasspath = new LinkedHashSet<>();
final Map<String, Version> versionMap = new LinkedHashMap<>();
File output;
File target;
private final AtomicInteger revision = new AtomicInteger();
private File files[];
boolean delayRunDependencies = true;
final ProjectMessages msgs = ReporterMessages
.base(this, ProjectMessages.class);
private Properties ide;
final Packages exportedPackages = new Packages();
final Packages importedPackages = new Packages();
final Packages containedPackages = new Packages();
final PackageInfo packageInfo = new PackageInfo(this);
private Makefile makefile;
private volatile Memoize<List<org.osgi.resource.Resource>> resources = Memoize
.supplier(this::parseBuildResources);
private volatile RefreshData data = new RefreshData();
public Map<String, Container> unreferencedClasspathEntries = new HashMap<>();
public ProjectInstructions instructions = getInstructions(
ProjectInstructions.class);
public Project(Workspace workspace, File unused, File buildFile) {
super(workspace);
this.workspace = workspace;
setFileMustExist(false);
if (buildFile != null)
setProperties(buildFile);
// For backward compatibility reasons, we also read
readBuildProperties();
repoCollector = new RepoCollector(this);
addClose(repoCollector);
}
public Project(Workspace workspace, File buildDir) {
this(workspace, buildDir, new File(buildDir, BNDFILE));
}
private void readBuildProperties() {
try {
File f = getFile("build.properties");
if (f.isFile()) {
Properties p = loadProperties(f);
for (String key : Iterables.iterable(p.propertyNames(), String.class::cast)) {
String newkey = key;
if (key.indexOf('$') >= 0) {
newkey = getReplacer().process(key);
}
setProperty(newkey, p.getProperty(key));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Project getUnparented(File propertiesFile) throws Exception {
propertiesFile = propertiesFile.getAbsoluteFile();
Workspace workspace = new Workspace(propertiesFile.getParentFile());
Project project = new Project(workspace, propertiesFile.getParentFile());
project.setProperties(propertiesFile);
project.setFileMustExist(true);
return project;
}
public boolean isValid() {
if (getBase() == null || !getBase().isDirectory())
return false;
return getPropertiesFile() == null || (!mustFileExist() || getPropertiesFile().isFile());
}
/**
* Return a new builder that is nicely setup for this project. Please close
* this builder after use.
*
* @param parent The project builder to use as parent, use this project if
* null
* @throws Exception
*/
public ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception {
ProjectBuilder builder;
if (parent == null)
builder = new ProjectBuilder(this);
else
builder = new ProjectBuilder(parent);
builder.setBase(getBase());
builder.use(this);
return builder;
}
public int getChanged() {
return revision.get();
}
/*
* Indicate a change in the external world that affects our build. This will
* clear any cached results.
*/
public void setChanged() {
preparedPaths.set(false);
files = null;
revision.getAndIncrement();
}
public Workspace getWorkspace() {
return workspace;
}
@Override
public String toString() {
return getName();
}
/**
* Set up all the paths
*/
public void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
synchronized (preparedPaths) {
if (preparedPaths.get()) {
// ensure output folders exist
getSrcOutput0();
getTarget0();
return;
}
if (!workspace.trail.add(this)) {
throw new CircularDependencyException(workspace.trail.toString() + "," + this);
}
try {
String basePath = IO.absolutePath(getBase());
dependenciesFull.clear();
dependenciesBuild.clear();
dependenciesTest.clear();
dependents.clear();
buildpath.clear();
testpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
// JIT
runpath.clear();
runbundles.clear();
runfw.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", basePath);
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directories
Parameters srces = new Parameters(mergeProperties(Constants.DEFAULT_PROP_SRC_DIR), this);
if (srces.isEmpty())
srces.add(Constants.DEFAULT_PROP_SRC_DIR, new Attrs());
for (Entry<String, Attrs> e : srces.entrySet()) {
File dir = getFile(removeDuplicateMarker(e.getKey()));
if (!IO.absolutePath(dir)
.startsWith(basePath)) {
error("The source directory lies outside the project %s directory: %s", this, dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
try {
IO.mkdirs(dir);
} catch (Exception ex) {
exception(ex, "could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
error("could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
}
if (dir.isDirectory()) {
sourcepath.put(dir, new Attrs(e.getValue()));
allsourcepath.add(dir);
} else
error("the src path (src property) contains an entry that is not a directory %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
}
// Set default bin directory
output = getSrcOutput0();
if (!output.isDirectory()) {
msgs.NoOutputDirectory_(output);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
Set<String> requiredProjectNames = new LinkedHashSet<>(
getMergedParameters(Constants.DEPENDSON).keySet());
// Allow DependencyConstributors to modify requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Collection<Project> projects = getWorkspace().getAllProjects();
projects.remove(this); // since -dependson could use a wildcard
Set<Instruction> unused = new HashSet<>();
Set<Project> buildDeps = new LinkedHashSet<>(is.select(projects, unused, false));
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, buildDeps, parseBuildpath(), bootclasspath, false, BUILDPATH);
Set<Project> testDeps = new LinkedHashSet<>(buildDeps);
doPath(testpath, testDeps, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, testDeps, parseRunFw(), null, false, RUNFW);
doPath(runpath, testDeps, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, testDeps, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> visited = new HashSet<>();
visited.add(this);
for (Project project : testDeps) {
project.traverse(dependenciesFull, this, visited);
}
dependenciesBuild.addAll(dependenciesFull);
dependenciesBuild.retainAll(buildDeps);
dependenciesTest.addAll(dependenciesFull);
dependenciesTest.retainAll(testDeps);
for (Project project : dependenciesFull) {
allsourcepath.addAll(project.getSourcePath());
}
preparedPaths.set(true);
} finally {
workspace.trail.remove(this);
}
}
}
/*
*
*/
private File getSrcOutput0() throws IOException {
File output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
IO.mkdirs(output);
getWorkspace().changedFile(output);
}
return output;
}
private File getTarget0() throws IOException {
File target = getTargetDir();
if (!target.exists()) {
IO.mkdirs(target);
getWorkspace().changedFile(target);
}
return target;
}
/**
* This method is deprecated because this can handle only one source dir.
* Use getSourcePath. For backward compatibility we will return the first
* entry on the source path.
*
* @return first entry on the {@link #getSourcePath()}
*/
@Deprecated
public File getSrc() throws Exception {
prepare();
if (sourcepath.isEmpty())
return getFile("src");
return sourcepath.keySet()
.iterator()
.next();
}
public File getSrcOutput() {
return getSingleFile(Constants.DEFAULT_PROP_BIN_DIR);
}
public File getTestSrc() {
return getSingleFile(Constants.DEFAULT_PROP_TESTSRC_DIR);
}
public File getTestOutput() {
return getSingleFile(Constants.DEFAULT_PROP_TESTBIN_DIR);
}
public File getTargetDir() {
return getSingleFile(Constants.DEFAULT_PROP_TARGET_DIR);
}
private void traverse(Set<Project> dependencies, Project dependent, Set<Project> visited) throws Exception {
if (visited.add(this)) {
for (Project project : getTestDependencies()) {
project.traverse(dependencies, this, visited);
}
dependencies.add(this);
}
dependents.add(dependent);
}
private File getSingleFile(String key) {
String value = getProperty(key);
if (value == null) {
error("project.%s expected value for property %s but got null", key, key);
value = key;
} else if (value.indexOf(',') >= 0) {
error("project.%s expected one file path for property %s but got multiple: %s", key, key, value);
}
return getFile(value);
}
/**
* Iterate over the entries and place the projects on the projects list and
* all the files of the entries on the resultpath.
*
* @param resultpath The list that gets all the files
* @param projects The list that gets any projects that are entries
* @param entries The input list of classpath entries
*/
private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries,
Collection<Container> bootclasspath, boolean noproject, String name) {
for (Container cpe : entries) {
if (cpe.getError() != null)
error("%s", cpe.getError()).header(name)
.context(cpe.getBundleSymbolicName());
else {
if (cpe.getType() == Container.TYPE.PROJECT) {
projects.add(cpe.getProject());
if (noproject //
&& since(About._2_3) //
&& VERSION_ATTR_PROJECT.equals(cpe.getAttributes()
.get(VERSION_ATTRIBUTE))) {
//
// we're trying to put a project's output directory on
// -runbundles list
//
error(
"%s is specified with version=project on %s. This version uses the project's output directory, which is not allowed since it must be an actual JAR file for this list.",
cpe.getBundleSymbolicName(), name).header(name)
.context(cpe.getBundleSymbolicName());
}
}
if (bootclasspath != null && (cpe.getBundleSymbolicName()
.startsWith("ee.")
|| cpe.getAttributes()
.containsKey("boot")))
bootclasspath.add(cpe);
else
resultpath.add(cpe);
}
}
}
/**
* Parse the list of bundles that are a prerequisite to this project.
* Bundles are listed in repo specific names. So we just let our repo
* plugins iterate over the list of bundles and we get the highest version
* from them.
*/
private List<Container> parseBuildpath() throws Exception {
List<Container> bundles = getBundles(Strategy.LOWEST, mergeProperties(Constants.BUILDPATH),
Constants.BUILDPATH);
return bundles;
}
private List<Container> parseRunpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNPATH), Constants.RUNPATH);
}
private List<Container> parseRunbundles() throws Exception {
return parseRunbundles(mergeProperties(Constants.RUNBUNDLES));
}
protected List<Container> parseRunbundles(String spec) throws Exception {
return getBundles(Strategy.HIGHEST, spec, Constants.RUNBUNDLES);
}
private List<Container> parseRunFw() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNFW), Constants.RUNFW);
}
private List<Container> parseTestpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.TESTPATH), Constants.TESTPATH);
}
/**
* Analyze the header and return a list of files that should be on the
* build, test or some other path. The list is assumed to be a list of bsns
* with a version specification. The special case of version=project
* indicates there is a project in the same workspace. The path to the
* output directory is calculated. The default directory ${bin} can be
* overridden with the output attribute.
*
* @param strategyx STRATEGY_LOWEST or STRATEGY_HIGHEST
* @param spec The header
*/
public List<Container> getBundles(Strategy strategyx, String spec, String source) throws Exception {
Parameters bundles = parseHeader(spec);
if (source != null) {
Instructions decorator = new Instructions(mergeProperties(source + "+"));
decorator.decorate(bundles);
decorator = new Instructions(mergeProperties(source + "++"));
decorator.decorate(bundles, true);
}
List<Container> result = new ArrayList<>();
try {
for (Entry<String, Attrs> entry : bundles.entrySet()) {
String bsn = removeDuplicateMarker(entry.getKey());
Map<String, String> attrs = entry.getValue();
Container found = null;
String versionRange = attrs.get("version");
boolean triedGetBundle = false;
if (bsn.indexOf('*') >= 0) {
return getBundlesWildcard(bsn, versionRange, strategyx, attrs);
}
if (versionRange != null) {
if (versionRange.equals(VERSION_ATTR_LATEST) || versionRange.equals(VERSION_ATTR_SNAPSHOT)) {
found = getBundle(bsn, versionRange, strategyx, attrs);
triedGetBundle = true;
}
}
if (found == null) {
//
// TODO This looks like a duplicate
// of what is done in getBundle??
//
if (versionRange != null
&& (versionRange.equals(VERSION_ATTR_PROJECT) || versionRange.equals(VERSION_ATTR_LATEST))) {
//
// Use the bin directory ...
//
Project project = getWorkspace().getProject(bsn);
if (project != null && project.exists()) {
File f = project.getOutput();
found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs,
null);
} else {
msgs.NoSuchProject(bsn, spec)
.context(bsn)
.header(source);
continue;
}
} else if (versionRange != null && versionRange.equals("file")) {
File f = getFile(bsn);
String error = null;
if (!f.exists())
error = "File does not exist: " + IO.absolutePath(f);
if (f.getName()
.endsWith(".lib")) {
found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs, null);
} else {
found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs, null);
}
} else if (!triedGetBundle) {
found = getBundle(bsn, versionRange, strategyx, attrs);
}
}
if (found != null) {
List<Container> libs = found.getMembers();
for (Container cc : libs) {
if (result.contains(cc)) {
if (isPedantic())
warning("Multiple bundles with the same final URL: %s, dropped duplicate", cc);
} else {
result.add(cc);
}
}
} else {
// Oops, not a bundle in sight :-(
Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null,
bsn + ";version=" + versionRange + " not found", attrs, null);
result.add(x);
error("Can not find URL for bsn %s", bsn).context(bsn)
.header(source);
}
}
} catch (CircularDependencyException e) {
String message = e.getMessage();
if (source != null)
message = String.format("%s (from property: %s)", message, source);
msgs.CircularDependencyContext_Message_(getName(), message);
} catch (IOException e) {
exception(e, "Unexpected exception in get bundles", spec);
}
return result;
}
/**
* Just calls a new method with a default parm.
*
* @throws Exception
*/
Collection<Container> getBundles(Strategy strategy, String spec) throws Exception {
return getBundles(strategy, spec, null);
}
/**
* Get all bundles matching a wildcard expression.
*
* @param bsnPattern A bsn wildcard, e.g. "osgi*" or just "*".
* @param range A range to narrow the versions of bundles found, or null to
* return any version.
* @param strategyx The version selection strategy, which may be 'HIGHEST'
* or 'LOWEST' only -- 'EXACT' is not permitted.
* @param attrs Additional search attributes.
* @throws Exception
*/
public List<Container> getBundlesWildcard(String bsnPattern, String range, Strategy strategyx,
Map<String, String> attrs) throws Exception {
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range))
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use snapshot or project version with wildcard matches", null, null));
if (strategyx == Strategy.EXACT)
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use exact version strategy with wildcard matches", null, null));
VersionRange versionRange;
if (range == null || VERSION_ATTR_LATEST.equals(range))
versionRange = new VersionRange("0");
else
versionRange = new VersionRange(range);
RepoFilter repoFilter = parseRepoFilter(attrs);
if (bsnPattern != null) {
bsnPattern = bsnPattern.trim();
if (bsnPattern.length() == 0 || bsnPattern.equals("*"))
bsnPattern = null;
}
SortedMap<String, Pair<Version, RepositoryPlugin>> providerMap = new TreeMap<>();
List<RepositoryPlugin> plugins = workspace.getRepositories();
for (RepositoryPlugin plugin : plugins) {
if (repoFilter != null && !repoFilter.match(plugin))
continue;
List<String> bsns = plugin.list(bsnPattern);
if (bsns != null)
for (String bsn : bsns) {
SortedSet<Version> versions = plugin.versions(bsn);
if (versions != null && !versions.isEmpty()) {
Pair<Version, RepositoryPlugin> currentProvider = providerMap.get(bsn);
Version candidate;
switch (strategyx) {
case HIGHEST :
candidate = versions.last();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) > 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
case LOWEST :
candidate = versions.first();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) < 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
default :
// we shouldn't have reached this point!
throw new IllegalStateException(
"Cannot use exact version strategy with wildcard matches");
}
}
}
}
List<Container> containers = new ArrayList<>(providerMap.size());
for (Entry<String, Pair<Version, RepositoryPlugin>> entry : providerMap.entrySet()) {
String bsn = entry.getKey();
Version version = entry.getValue()
.getFirst();
RepositoryPlugin repo = entry.getValue()
.getSecond();
DownloadBlocker downloadBlocker = new DownloadBlocker(this);
File bundle = repo.get(bsn, version, attrs, downloadBlocker);
if (bundle != null && !bundle.getName()
.endsWith(".lib")) {
containers
.add(new Container(this, bsn, range, Container.TYPE.REPO, bundle, null, attrs, downloadBlocker));
}
}
return containers;
}
static void mergeNames(String names, Set<String> set) {
StringTokenizer tokenizer = new StringTokenizer(names, ",");
while (tokenizer.hasMoreTokens())
set.add(tokenizer.nextToken()
.trim());
}
static String flatten(Set<String> names) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String name : names) {
if (!first)
builder.append(',');
builder.append(name);
first = false;
}
return builder.toString();
}
static void addToPackageList(Container container, String newPackageNames) {
Set<String> merged = new HashSet<>();
String packageListStr = container.getAttributes()
.get("packages");
if (packageListStr != null)
mergeNames(packageListStr, merged);
if (newPackageNames != null)
mergeNames(newPackageNames, merged);
container.putAttribute("packages", flatten(merged));
}
/**
* The user selected pom in a path. This will place the pom as well as its
* dependencies on the list
*
* @param strategyx the strategy to use.
* @param result The list of result containers
* @throws Exception anything goes wrong
*/
public void doMavenPom(Strategy strategyx, List<Container> result, String action) throws Exception {
File pomFile = getFile("pom.xml");
if (!pomFile.isFile())
msgs.MissingPom();
else {
ProjectPom pom = getWorkspace().getMaven()
.createProjectModel(pomFile);
if (action == null)
action = "compile";
Pom.Scope act = Pom.Scope.valueOf(action);
Set<Pom> dependencies = pom.getDependencies(act);
for (Pom sub : dependencies) {
File artifact = sub.getArtifact();
Container container = new Container(artifact, null);
result.add(container);
}
}
}
/**
* Return the full transitive dependencies of this project.
*
* @return A set of the full transitive dependencies of this project.
* @throws Exception
*/
public Collection<Project> getDependson() throws Exception {
prepare();
return dependenciesFull;
}
/**
* Return the direct build dependencies of this project.
*
* @return A set of the direct build dependencies of this project.
* @throws Exception
*/
public Set<Project> getBuildDependencies() throws Exception {
prepare();
return dependenciesBuild;
}
/**
* Return the direct test dependencies of this project.
* <p>
* The result includes the direct build dependencies of this project as
* well, so the result is a super set of {@link #getBuildDependencies()}.
*
* @return A set of the test build dependencies of this project.
* @throws Exception
*/
public Set<Project> getTestDependencies() throws Exception {
prepare();
return dependenciesTest;
}
/**
* Return the full transitive dependents of this project.
* <p>
* The result includes projects which have build and test dependencies on
* this project.
* <p>
* Since the full transitive dependents of this project is updated during
* the computation of other project dependencies, until all projects are
* prepared, the dependents result may be partial.
*
* @return A set of the transitive set of projects which depend on this
* project.
* @throws Exception
*/
public Set<Project> getDependents() throws Exception {
prepare();
return dependents;
}
public Collection<Container> getBuildpath() throws Exception {
prepare();
return buildpath;
}
public Collection<Container> getTestpath() throws Exception {
prepare();
return testpath;
}
/**
* Handle dependencies for paths that are calculated on demand.
*/
private void justInTime(Collection<Container> path, List<Container> entries, boolean noproject, String name) {
if (delayRunDependencies && path.isEmpty())
doPath(path, dependenciesFull, entries, null, noproject, name);
}
public Collection<Container> getRunpath() throws Exception {
prepare();
justInTime(runpath, parseRunpath(), false, RUNPATH);
return runpath;
}
public Collection<Container> getRunbundles() throws Exception {
prepare();
justInTime(runbundles, parseRunbundles(), true, RUNBUNDLES);
return runbundles;
}
/**
* Return the run framework
*
* @throws Exception
*/
public Collection<Container> getRunFw() throws Exception {
prepare();
justInTime(runfw, parseRunFw(), false, RUNFW);
return runfw;
}
public File getRunStorage() throws Exception {
prepare();
return runstorage;
}
public boolean getRunBuilds() {
boolean result;
String runBuildsStr = getProperty(Constants.RUNBUILDS);
if (runBuildsStr == null)
result = !Strings.endsWithIgnoreCase(getPropertiesFile().getName(), Constants.DEFAULT_BNDRUN_EXTENSION);
else