-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
Launchpad.java
1391 lines (1215 loc) · 37.8 KB
/
Launchpad.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.launchpad;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.Nullable;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.service.EventListenerHook;
import org.osgi.framework.hooks.service.FindHook;
import org.osgi.framework.hooks.service.ListenerHook.ListenerInfo;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
//import org.osgi.service.component.runtime.ServiceComponentRuntime;
//import org.osgi.service.component.runtime.dto.ComponentDescriptionDTO;
import org.osgi.util.tracker.ServiceTracker;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.service.remoteworkspace.RemoteWorkspace;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.launchpad.internal.ProbeImpl;
import aQute.lib.converter.Converter;
import aQute.lib.inject.Injector;
import aQute.lib.io.IO;
import aQute.lib.startlevel.StartLevelRuntimeHandler;
import aQute.lib.strings.Strings;
import aQute.libg.glob.Glob;
import aQute.libg.parameters.ParameterMap;
/**
* This class provides an OSGi framework that is configured with the current bnd
* workspace. A project directory is used to find the workspace. This makes all
* repositories in the workspace available to the framework. To be able to test
* JUnit code against/in this framework it is necessary that all packages on the
* buildpath and testpath are actually exported in the framework. This class
* will ensure that. Once the framework is up and running it will be possible to
* add bundles to it. There are a number of ways that this can be achieved:
* <ul>
* <li>Build a bundle – A bnd Builder is provided to create a bundle and install
* it. This makes it possible to add classes from the src or test directories or
* resources. See {@link #bundle()}. Convenience methods are added to get
* services, see {@link #getService(Class)} et. al. Notice that this framework
* starts in the same process as that the JUnit code runs. This is normally a
* separately started VM.
*/
@ProviderType
public class Launchpad implements AutoCloseable {
public static final String BUNDLE_PRIORITY = "Bundle-Priority";
private static final long SERVICE_DEFAULT_TIMEOUT = 60000L;
final AtomicInteger counter = new AtomicInteger();
final File projectDir;
final Framework framework;
final List<ServiceTracker<?, ?>> trackers = new ArrayList<>();
final List<FrameworkEvent> frameworkEvents = new CopyOnWriteArrayList<>();
final Injector<Service> injector;
final Map<Class<?>, ServiceTracker<?, ?>> injectedDoNotClose = new ConcurrentHashMap<>();
final Set<String> frameworkExports;
final List<String> errors = new ArrayList<>();
final String name;
final String className;
final RunSpecification runspec;
final boolean hasTestBundle;
final StartLevelRuntimeHandler startlevels;
final RemoteWorkspace workspace;
Bundle testbundle;
boolean debug;
final boolean byReference;
PrintStream out = System.err;
ServiceTracker<FindHook, FindHook> hooks;
private long closeTimeout;
private Bundle proxyBundle;
private Probe probe = new ProbeImpl();
Launchpad(RemoteWorkspace workspace, Framework framework, String name, String className, RunSpecification runspec,
long closeTimeout, boolean debug, boolean hasTestBundle, boolean byReference) {
this.workspace = workspace;
this.runspec = runspec;
this.closeTimeout = closeTimeout;
this.hasTestBundle = hasTestBundle;
this.byReference = byReference;
this.proxyBundle = framework;
this.startlevels = StartLevelRuntimeHandler.create(this::report, this.runspec.properties);
try {
this.className = className;
this.name = name;
this.projectDir = IO.work;
this.debug = debug;
this.framework = framework;
this.framework.init();
this.injector = new Injector<>(makeConverter(), this::getService, Service.class);
this.frameworkExports = getExports(framework).keySet();
report("Initialized framework %s", this.framework);
report("Classpath %s", System.getProperty("java.class.path")
.replace(File.pathSeparatorChar, '\n'));
framework.getBundleContext()
.addFrameworkListener(frameworkEvents::add);
hooks = new ServiceTracker<>(framework.getBundleContext(), FindHook.class, null);
hooks.open();
startlevels.beforeStart(framework);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
public void report(String format, Object... args) {
if (!debug)
return;
out.printf(format + "%n", args);
}
/**
* Generate an error so that the test case can check if we found anything
* wrong. This is easy to check with {@link #check(String...)}
*
* @param format the format string used in
* {@link String#format(String, Object...)}
* @param args the arguments to be formatted
*/
public void error(String format, Object... args) {
report(format, args);
String msg = String.format(format, args);
errors.add(msg);
}
/**
* Check the errors found, filtering out any unwanted with globbing patters.
* Each error is filtered against all the patterns. This method return true
* if there are no unfiltered errors, otherwise false.
*
* @param patterns globbing patterns
* @return true if no errors after filtering,otherwise false
*/
public boolean check(String... patterns) {
Glob[] globs = Stream.of(patterns)
.map(Glob::new)
.toArray(Glob[]::new);
boolean[] used = new boolean[globs.length];
String[] unmatched = errors.stream()
.filter(msg -> {
for (int i = 0; i < globs.length; i++) {
if (globs[i].finds(msg) >= 0) {
used[i] = true;
return false;
}
}
return true;
})
.toArray(String[]::new);
if (unmatched.length == 0) {
List<Glob> report = new ArrayList<>();
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
report.add(globs[i]);
}
}
if (report.isEmpty())
return true;
out.println("Missing patterns");
out.println(Strings.join("\n", globs));
return false;
}
out.println("Errors");
out.println(Strings.join("\n", unmatched));
return false;
}
/**
* Add a file as a bundle to the framework. This bundle will not be started.
*
* @param f the file to install
* @return the bundle object
*/
public Bundle bundle(File f) {
try {
report("Installing %s", f);
return framework.getBundleContext()
.installBundle(toInstallURI(f));
} catch (Exception e) {
report("Failed to installing %s : %s", f, e);
throw Exceptions.duck(e);
}
}
/**
* Set the debug flag
*/
public Launchpad debug() {
this.debug = true;
return this;
}
/**
* Install a number of bundles based on their bundle specification. A bundle
* specification is the format used in for example -runbundles.
*
* @param specification the bundle specifications
* @return a list of bundles
*/
public List<Bundle> bundles(String specification) {
try {
return workspace.getLatestBundles(projectDir.getAbsolutePath(), specification)
.stream()
.map(File::new)
.map(this::bundle)
.collect(Collectors.toList());
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a number of bundles
*
* @param runbundles the list of bundles
* @return a list of bundle objects
*/
public List<Bundle> bundles(File... runbundles) {
if (runbundles == null || runbundles.length == 0)
return Collections.emptyList();
try {
List<Bundle> bundles = new ArrayList<>();
for (File f : runbundles) {
Bundle b = bundle(f);
bundles.add(b);
}
return bundles;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Start a bundle
*
* @param b the bundle object
*/
public void start(Bundle b) {
try {
if (!isFragment(b)) {
report("Starting %s", b);
b.start();
Set<String> exports = getExports(b).keySet();
Set<String> imports = getImports(b).keySet();
exports.removeAll(imports);
exports.retainAll(frameworkExports);
if (!exports.isEmpty()) {
error(
"bundle %s is exporting but NOT importing package(s) %s that are/is also exported by the framework.\n"
+ "This means that the test code and the bundle cannot share classes of these package.",
b, exports);
}
} else {
report("Not starting fragment %s", b);
}
} catch (Exception e) {
report("Failed to start %s : %s", b, e);
throw Exceptions.duck(e);
}
}
/**
* Start all bundles
*
* @param bs a collection of bundles
*/
public void start(Collection<Bundle> bs) {
bs.forEach(this::start);
}
/**
* Close this framework
*/
@Override
public void close() throws Exception {
startlevels.close();
report("Stop the framework");
framework.stop();
report("Stopped the framework");
framework.waitForStop(closeTimeout);
report("Framework fully stopped");
}
/**
* Get the Bundle Context. If a test bundle was installed then this is the
* context of the test bundle otherwise it is the context of the framework.
* To be able to proxy services it is necessary to have a test bundle
* installed.
*
* @return the bundle context of the test bundle or the framework
*/
public BundleContext getBundleContext() {
if (testbundle != null)
return testbundle.getBundleContext();
return framework.getBundleContext();
}
/**
* Get a service registered under class. If multiple services are registered
* it will return the first
*
* @param serviceInterface the name of the service
* @return a service
*/
public <T> Optional<T> getService(Class<T> serviceInterface) {
return getService(serviceInterface, null);
}
public <T> Optional<T> getService(Class<T> serviceInterface, @Nullable String target) {
return getServices(serviceInterface, target, 0, 0, false).stream()
.map(this::getService)
.findFirst();
}
/**
* Get a list of services of a given name
*
* @param serviceClass the service name
* @return a list of services
*/
public <T> List<T> getServices(Class<T> serviceClass) {
return getServices(serviceClass, null);
}
/**
* Get a list of services in the current registry
*
* @param serviceClass the type of the service
* @param target the target, may be null
* @return a list of found services currently in the registry
*/
public <T> List<T> getServices(Class<T> serviceClass, @Nullable String target) {
return getServices(serviceClass, target, 0, 0, false).stream()
.map(this::getService)
.collect(Collectors.toList());
}
/**
* Get a service from a reference. If the service is null, then throw an
* exception.
*
* @param ref the reference
* @return the service, never null
*/
public <T> T getService(ServiceReference<T> ref) {
try {
T service = getBundleContext().getService(ref);
if (service == null) {
if (ref.getBundle() == null) {
throw new ServiceException(
"getService(" + ref + ") returns null, the service is no longer registered");
}
throw new ServiceException("getService(" + ref + ") returns null, this probbaly means the \n"
+ "component failed to activate. The cause can \n" + "generally be found in the log.\n" + "");
}
return service;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad gogo() {
try {
bundles("org.apache.felix.gogo.runtime,org.apache.felix.gogo.command,org.apache.felix.gogo.shell");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad snapshot() {
try {
bundles("biz.aQute.bnd.runtime.snapshot");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Inject an object with services and other OSGi specific values.
*
* @param object the object to inject
*/
public Launchpad inject(Object object) {
try {
injector.inject(object);
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a bundle from a file
*
* @param file the file to install
* @return a bundle
*/
public Bundle install(File file) {
try {
if (byReference) {
String installURI = toInstallURI(file);
report("Installing %s", installURI);
return framework.getBundleContext()
.installBundle(installURI);
}
try (InputStream fin = IO.stream(file)) {
return framework.getBundleContext()
.installBundle("-> " + file, fin);
} catch (FileNotFoundException e) {
report("Failed to install %s because file could not be found", file);
throw Exceptions.duck(e);
} catch (IOException e) {
report("Failed to install %s because %s", file, e.getMessage());
throw Exceptions.duck(e);
}
} catch (BundleException e) {
report("Failed to install %s : %s", file, e);
throw Exceptions.duck(e);
}
}
/**
* Create a new synthetic bundle.
*
* @return the bundle builder
*/
public BundleBuilder bundle() {
return new BundleBuilder(this);
}
/**
* Create a new object and inject it.
*
* @param type the type of object
* @return a new object injected and all
*/
public <T> T newInstance(Class<T> type) {
try {
return injector.newInstance(type);
} catch (Exception e) {
report("Failed to create and instance for %s : %s", type, e);
throw Exceptions.duck(e);
}
}
/**
* Show the information of how the framework is setup and is running
*/
public Launchpad report() throws InvalidSyntaxException {
boolean old = debug;
debug = true;
reportBundles();
reportServices();
reportEvents();
debug = old;
return this;
}
/**
* Show the installed bundles
*/
public void reportBundles() {
Stream.of(framework.getBundleContext()
.getBundles())
.forEach(bb -> {
report("%4s %4s %s", bundleStateToString(bb.getState()), startlevels.getBundleStartLevel(bb), bb);
});
}
/**
* Show the registered service
*/
public void reportServices() throws InvalidSyntaxException {
Stream.of(framework.getBundleContext()
.getAllServiceReferences(null, null))
.forEach(sref -> {
report("%s", sref);
});
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs) {
return getServices(class1, null, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs, String target) {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs) {
return this.waitForService(class1, timeoutInMs, null);
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @param target filter, may be null
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs, String target) {
try {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst()
.map(getBundleContext()::getService);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Turn a service reference's properties into a Map
*
* @param reference the reference
* @return a Map with all the properties of the reference
*/
public Map<String, Object> toMap(ServiceReference<?> reference) {
Map<String, Object> map = new HashMap<>();
for (String key : reference.getPropertyKeys()) {
map.put(key, reference.getProperty(key));
}
return map;
}
/**
* Get a bundle by symbolic name
*/
public Optional<Bundle> getBundle(String bsn) {
return Stream.of(getBundleContext().getBundles())
.filter(b -> bsn.equals(b.getSymbolicName()))
.findFirst();
}
/**
* Broadcast a message to many services at once
*/
@SuppressWarnings("unchecked")
public <T> int broadcast(Class<T> type, Consumer<T> consumer) {
ServiceTracker<T, T> tracker = new ServiceTracker<>(getBundleContext(), type, null);
tracker.open();
int n = 0;
try {
for (T instance : (T[]) tracker.getServices()) {
consumer.accept(instance);
n++;
}
} finally {
tracker.close();
}
return n;
}
/**
* Hide a service by registering a hook. This should in general be done
* before you let others look. In general, the Launchpad should be started
* in {@link LaunchpadBuilder#nostart()} mode. This initializes the OSGi
* framework making it possible to register a service before
*/
public Closeable hide(Class<?> type) {
return hide(type, "hide");
}
/**
* Hide a service. This will register a FindHook and an EventHook for the
* type. This will remove the visibility of all services with that type for
* all bundles _except_ the testbundle. Notice that bundles that already
* obtained a references are not affected. If you use this facility it is
* best to not start the framework before you hide a service. You can
* indicate this to the build with {@link LaunchpadBuilder#nostart()}. The
* framework can be started after creation with {@link #start()}. Notice
* that services through the testbundle remain visible for this hide.
*
* @param type the type to hide
* @param reason the reason why it is hidden
* @return a Closeable, when closed it will remove the hooks
*/
public Closeable hide(Class<?> type, String reason) {
ServiceRegistration<EventListenerHook> eventReg = framework.getBundleContext()
.registerService(EventListenerHook.class, new EventListenerHook() {
@Override
public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerInfo>> listeners) {
ServiceReference<?> ref = event.getServiceReference();
if (selectForHiding(type, ref))
listeners.clear();
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
ServiceRegistration<FindHook> findReg = framework.getBundleContext()
.registerService(FindHook.class, new FindHook() {
@Override
public void find(BundleContext context, String name, String filter, boolean allServices,
Collection<ServiceReference<?>> references) {
if (name == null || name.equals(type.getName())) {
references.removeIf(ref -> selectForHiding(type, ref));
}
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
return () -> {
eventReg.unregister();
findReg.unregister();
};
}
/**
* Check of a service reference has one of the given types in its object
* class
*
* @param serviceReference the service reference to check
* @param types the set of types
* @return true if one of the types name is in the service reference's
* objectClass property
*/
public boolean isOneOfType(ServiceReference<?> serviceReference, Class<?>... types) {
String[] objectClasses = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
for (Class<?> type : types) {
String name = type.getName();
for (String objectClass : objectClasses) {
if (objectClass.equals(name))
return true;
}
}
return false;
}
private boolean selectForHiding(Class<?> type, ServiceReference<?> ref) {
//
// We never hide services registered by the testbundle
//
if (ref.getBundle() == testbundle)
return false;
// only hide references when one of their
// service interfaces is of the hidden type
return isOneOfType(ref, type);
}
/**
* Start the framework if not yet started
*/
public void start() {
try {
framework.start();
List<Bundle> toBeStarted = new ArrayList<>();
for (String path : runspec.runbundles) {
File file = new File(path);
if (!file.isFile())
throw new IllegalArgumentException("-runbundle " + file + " does not exist or is not a file");
Bundle b = install(file);
if (!isFragment(b)) {
toBeStarted.add(b);
}
}
FrameworkWiring fw = framework.adapt(FrameworkWiring.class);
fw.resolveBundles(toBeStarted);
Collections.sort(toBeStarted, this::startorder);
if (hasTestBundle)
testbundle();
toBeStarted.forEach(this::start);
startlevels.afterStart();
} catch (BundleException e) {
throw Exceptions.duck(e);
}
}
// reverse ordering. I.e. highest priority is first
int startorder(Bundle a, Bundle b) {
return Integer.compare(getPriority(b), getPriority(a));
}
private int getPriority(Bundle b) {
try {
String h = b.getHeaders()
.get(BUNDLE_PRIORITY);
if (h != null)
return Integer.parseInt(h);
} catch (Exception e) {
// ignore
}
return 0;
}
/**
* Stop the framework if not yet stopped
*/
public void stop() {
try {
report("Stopping the framework");
framework.stop();
} catch (BundleException e) {
report("Could not stop the framework : %s", e);
throw Exceptions.duck(e);
}
}
/**
* Set the test bundle
*/
public void testbundle() {
if (testbundle != null) {
throw new IllegalArgumentException("Test bundle already exists");
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Manifest man = new Manifest();
man.getMainAttributes()
.putValue("Manifest-Version", "1");
String name = projectDir.getName()
.toUpperCase();
report("Creating test bundle %s", name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_SYMBOLICNAME, name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
JarOutputStream jout = new JarOutputStream(bout, man);
jout.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
this.testbundle = framework.getBundleContext()
.installBundle(name, bin);
this.testbundle.start();
} catch (Exception e) {
report("Failed to create test bundle");
throw Exceptions.duck(e);
}
}
/**
* Register a service. You can specify the type and the instance as well as
* the properties. The properties are specified as varargs. That means you
* can define a property by specifying the key (which must be a String) and
* the value consecutively. The value can be any of the types allowed by the
* service properties.
*
* <pre>
* fw.register(Foo.class, instance, "foo", 10, "bar", new long[] {
* 1, 2, 3
* });
* </pre>
*
* @param type the service type
* @param instance the service object
* @param props the service properties specified as a seq of "key", value
* @return the service registration
*/
public <T> ServiceRegistration<T> register(Class<T> type, T instance, Object... props) {
report("Registering service %s %s", type, instance, Arrays.toString(props));
Hashtable<String, Object> ht = new Hashtable<>();
for (int i = 0; i < props.length; i += 2) {
String key = (String) props[i];
Object value = null;
if (i + 1 < props.length) {
value = props[i + 1];
}
ht.put(key, value);
}
return getBundleContext().registerService(type, instance, ht);
}
/**
* Return the framework object
*
* @return the framework object
*/
public Framework getFramework() {
return framework;
}
/**
* Add a component class. This creates a little bundle that holds the
* component class so that bnd adds the DS XML. However, it also imports the
* package of the component class so that in runtime DS will load it from
* the classpath.
*/
public <T> Bundle component(Class<T> type) {
return bundle().addResource(type)
.start();
}
/**
* Runs the given code within the context of a synthetic bundle. Creates a
* synthetic bundle and adds the supplied class to it using
* {@link BundleBuilder#addResourceWithCopy}. It then loads the class using
* the synthetic bundle's class loader and instantiates it using the public,
* no-parameter constructor.
*
* @param clazz the class to instantiate within the context of the
* framework.
* @return The instantiated object.
* @see BundleBuilder#addResourceWithCopy(Class)
*/
public <T> T instantiateInFramework(Class<? extends T> clazz) {
try {
clazz.getConstructor();
} catch (NoSuchMethodException e) {
throw Exceptions.duck(e);
}
Bundle b = bundle().addResourceWithCopy(clazz)
.start();
try {
@SuppressWarnings("unchecked")
Class<? extends T> insideClass = (Class<? extends T>) b.loadClass(clazz.getName());
return insideClass.getConstructor()
.newInstance();
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Check if a bundle is a fragement
*
* @param b the bundle to check
*/
public boolean isFragment(Bundle b) {
return b.getHeaders()
.get(Constants.FRAGMENT_HOST) != null;
}
/**
* Check if a bundle is in the ACTIVE state
*
* @param b the bundle to check
*/
public boolean isActive(Bundle b) {
return b.getState() == Bundle.ACTIVE;
}
/**
* Check if a bundle is in the RESOLVED state
*
* @param b the bundle to check
*/
public boolean isResolved(Bundle b) {
return b.getState() == Bundle.RESOLVED;
}
/**
* Check if a bundle is in the INSTALLED state
*
* @param b the bundle to check
*/
public boolean isInstalled(Bundle b) {
return b.getState() == Bundle.INSTALLED;
}
/**
* Check if a bundle is in the UNINSTALLED state
*
* @param b the bundle to check
*/
public boolean isUninstalled(Bundle b) {
return b.getState() == Bundle.UNINSTALLED;
}
/**
* Check if a bundle is in the STARTING state
*
* @param b the bundle to check
*/
public boolean isStarting(Bundle b) {
return b.getState() == Bundle.STARTING;
}
/**
* Check if a bundle is in the STOPPING state
*
* @param b the bundle to check
*/
public boolean isStopping(Bundle b) {
return b.getState() == Bundle.STOPPING;
}