forked from darranl/jbosgi
/
Provided_Examples.html
executable file
·907 lines (778 loc) · 40.3 KB
/
Provided_Examples.html
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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Provided Examples - JBoss OSGi</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<meta content="Scroll Wiki Publisher" name="generator"/>
<link type="text/css" rel="stylesheet" href="css/blueprint/liquid.css" media="screen, projection"/>
<link type="text/css" rel="stylesheet" href="css/blueprint/print.css" media="print"/>
<!--[if lt IE 8]><link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection"/><![endif]-->
<link type="text/css" rel="stylesheet" href="css/content-style.css" media="screen, projection, print"/>
<link type="text/css" rel="stylesheet" href="css/screen.css" media="screen, projection"/>
<link type="text/css" rel="stylesheet" href="css/print.css" media="print"/>
<link type="text/css" rel="stylesheet" href="css/jbossorg.css"/>
<link type="text/css" rel="stylesheet" href="css/docnav.css"/>
<link type="text/css" rel="stylesheet" href="sh/shCore.css"/>
<link type="text/css" rel="stylesheet" href="sh/shCoreDefault.css"/>
<script type="text/javascript" src="sh/shCore.js"></script>
<script type="text/javascript" src="sh/shBrushAppleScript.js"></script>
<script type="text/javascript" src="sh/shBrushAS3.js"></script>
<script type="text/javascript" src="sh/shBrushBash.js"></script>
<script type="text/javascript" src="sh/shBrushCpp.js"></script>
<script type="text/javascript" src="sh/shBrushCSharp.js"></script>
<script type="text/javascript" src="sh/shBrushCss.js"></script>
<script type="text/javascript" src="sh/shBrushDiff.js"></script>
<script type="text/javascript" src="sh/shBrushErlang.js"></script>
<script type="text/javascript" src="sh/shBrushGroovy.js"></script>
<script type="text/javascript" src="sh/shBrushJava.js"></script>
<script type="text/javascript" src="sh/shBrushJavaFX.js"></script>
<script type="text/javascript" src="sh/shBrushJScript.js"></script>
<script type="text/javascript" src="sh/shBrushPerl.js"></script>
<script type="text/javascript" src="sh/shBrushPhp.js"></script>
<script type="text/javascript" src="sh/shBrushPlain.js"></script>
<script type="text/javascript" src="sh/shBrushPython.js"></script>
<script type="text/javascript" src="sh/shBrushRuby.js"></script>
<script type="text/javascript" src="sh/shBrushScala.js"></script>
<script type="text/javascript" src="sh/shBrushSql.js"></script>
<script type="text/javascript" src="sh/shBrushVb.js"></script>
<script type="text/javascript" src="sh/shBrushXml.js"></script>
</head>
<body>
<div class="container" style="min-width: 760px;">
<div class="block header">
<p id="title">
<a class="site_href" href="http://www.jboss.org"><strong>JBoss.org</strong></a>
<a class="doc_href" href="http://docs.jboss.org"><strong>Community Documentation</strong></a>
</p>
<ul class="docnav">
<li class="previous"><a accesskey="p" href="Arquillian_Test_Framework.html"><strong>Prev</strong></a></li>
<li class="next"><a accesskey="n" href="References.html"><strong>Next</strong></a></li>
</ul>
<div>
<h1>Provided Examples</h1>
</div>
</div>
<div class="block content">
<div class="section-2" id="4784855_ProvidedExamples-Content" >
<h2>Content</h2>
<ul class=" "><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-BuildandRuntheExamples">Build and Run the Examples</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-ExamplesforStandalone%26RemoteWildFly">Examples for Standalone & Remote WildFly</a> </p>
<ul class=" "><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-BlueprintContainer">Blueprint Container</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-ConfigurationAdmin">Configuration Admin</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-DeclarativeServices">Declarative Services</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-EventAdmin">Event Admin</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-JNDIService">JNDI Service</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-JMXService">JMX Service</a> </p>
</li></ul></li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-ExamplesforWildFlyIntegration">Examples for WildFly Integration</a> </p>
<ul class=" "><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-CDIIntegration">CDI Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-EARDeployments">EAR Deployments</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-EJB3Integration">EJB3 Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-HttpService">HttpService</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-JAXBIntegration">JAXB Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-JPAIntegration">JPA Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-JTAService">JTA Service</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-LifecycleInterceptor">Lifecycle Interceptor</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-ResourceInjection">Resource Injection</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-RESTIntegration">REST Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-WebServicesIntegration">Web Services Integration</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-WebApplication">Web Application</a> </p>
</li><li class=" "> <p>
<a href="Provided_Examples.html#4784855_ProvidedExamples-XMLParserServices">XML Parser Services</a> </p>
</li></ul></li></ul> </div>
<div class="section-2" id="4784855_ProvidedExamples-BuildandRuntheExamples" >
<h2>Build and Run the Examples</h2>
<p>
JBoss OSGi comes with a number of examples that demonstrate supported functionality and show best practices. All examples are part of the binary distribution and tightly integrated in our <a href="http://www.jboss.org/community/docs/DOC-13275">Maven Build Process</a>. </p>
<p>
The examples can be either run against an embedded OSGi framework or against WildFly. Here is how you build and run the standalone framework tests. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">[tdiesler@localhost example]$ mvn clean test
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running org.jboss.test.osgi.example.blueprint.BlueprintTestCase
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.225 sec
...
Tests run: 22, Failures: 0, Errors: 0, Skipped: 1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.846s
[INFO] Finished at: Fri Jun 28 10:24:25 CEST 2013
[INFO] Final Memory: 25M/202M
[INFO] ------------------------------------------------------------------------</pre>
</div>
</div>
<p>
To run the examples against WildFly, you need to provide the target container that the runtime should connect to. This can be done with the <strong class=" ">target.container</strong> system property. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"> mvn -Dtarget.container=wildfly800 test</pre>
</div>
</div>
</div>
<div class="section-2" id="4784855_ProvidedExamples-ExamplesforStandalone%26RemoteWildFly" >
<h2>Examples for Standalone & Remote WildFly</h2>
<p>
This section covers example tests that run both in the standalone and remote WildFly runtimes. </p>
<div class="section-3" id="4784855_ProvidedExamples-BlueprintContainer" >
<h3>Blueprint Container</h3>
<p>
The <strong class=" ">BlueprintTestCase</strong> shows how a number of components can be wired together and registered as OSGi service through the Blueprint Container Service. </p>
<p>
The example uses this simple blueprint descriptor </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"><blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ...>
<bean id="beanA" class="org.jboss.test.osgi.example.blueprint.bundle.BeanA">
<property name="mbeanServer" ref="mbeanService"/>
</bean>
<service id="serviceA" ref="beanA" interface="org.jboss.test.osgi.example.blueprint.bundle.ServiceA">
</service>
<service id="serviceB" interface="org.jboss.test.osgi.example.blueprint.bundle.ServiceB">
<bean class="org.jboss.test.osgi.example.blueprint.bundle.BeanB">
<property name="beanA" ref="beanA"/>
</bean>
</service>
<reference id="mbeanService" interface="javax.management.MBeanServer"/>
</blueprint></pre>
</div>
</div>
<p>
The Blueprint Container registers two services <strong class=" ">ServiceA</strong> and <strong class=" ">ServiceB</strong>. ServiceA is backed up by <strong class=" ">BeanA</strong>, ServiceB is backed up by the anonymous <strong class=" ">BeanB</strong>. BeanA is injected into BeanB and the <strong class=" ">MBeanServer</strong> gets injected into BeanA. Both beans are plain POJOs. There is <strong class=" ">no BundleActivator</strong> neccessary to register the services. </p>
<p>
The example test verifies the correct wiring like this </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">@Test
public void testServiceA() throws Exception
{
ServiceReference<ServiceA> srefA = context.getServiceReference(ServiceA.class);
assertNotNull("ServiceA not null", srefA);
ServiceA serviceA = context.getService(srefA);
MBeanServer mbeanServer = serviceA.getMbeanServer();
assertNotNull("MBeanServer not null", mbeanServer);
ServiceReference<ServiceB> srefB = context.getServiceReference(ServiceB.class);
assertNotNull("ServiceB not null", srefB);
ServiceB serviceB = context.getService(sref);
BeanA beanA = serviceB.getBeanA();
assertNotNull("BeanA not null", beanA);
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-ConfigurationAdmin" >
<h3>Configuration Admin</h3>
<p>
The <strong class=" ">ConfigurationAdminTestCase</strong> shows how an OSGi <a href="http://www.osgi.org/javadoc/r4v42/org/osgi/service/cm/ManagedService.html">ManagedService</a> can be configured through the <a href="http://www.osgi.org/javadoc/r4v42/org/osgi/service/cm/ConfigurationAdmin.html">ConfigurationAdmin</a> service. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testManagedService() throws Exception {
// Get the {@link Configuration} for the given PID
Configuration config = configAdmin.getConfiguration(ConfiguredService.SERVICE_PID);
assertNotNull("Config not null", config);
Dictionary<String, String> configProps = new Hashtable<String, String>();
configProps.put("foo", "bar");
config.update(configProps);
// Register a {@link ManagedService}
Dictionary<String, String> serviceProps = new Hashtable<String, String>();
serviceProps.put(Constants.SERVICE_PID, ConfiguredService.SERVICE_PID);
bundlecontext.registerService(new String[] { ConfiguredService.class.getName(),
ManagedService.class.getName() }, new ConfiguredService(), serviceProps);
// Wait a little for the update event
if (latch.await(5, TimeUnit.SECONDS) == false)
throw new TimeoutException();
// Verify service property
ServiceReference sref = bundlecontext.getServiceReference(ConfiguredService.class.getName());
ConfiguredService service = (ConfiguredService) bundlecontext.getService(sref);
assertEquals("bar", service.getValue("foo"));
config.delete();
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-DeclarativeServices" >
<h3>Declarative Services</h3>
<p>
The <strong class=" ">DeclarativeServicesTestCase</strong> shows how a service can be made available through a Declarative Services descriptor. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"><component name="sample.component" immediate="true">
<implementation class="org.jboss.test.osgi.example.ds.SampleComparator" />
<property name="service.description" value="Sample Comparator Service" />
<property name="service.vendor" value="Apache Software Foundation" />
<service>
<provide interface="java.util.Comparator" />
</service>
</component></pre>
</div>
</div>
<p>
The test then verifies that the service becomes available </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testImmediateService() throws Exception {
// Track the service provided by the test bundle
final CountDownLatch latch = new CountDownLatch(1);
ServiceTracker tracker = new ServiceTracker(context, Comparator.class.getName(), null) {
public Object addingService(ServiceReference reference) {
Comparator<Object> service = (Comparator<Object>) super.addingService(reference);
latch.countDown();
return service;
}
};
tracker.open();
// Wait for the service to become available
if (latch.await(2, TimeUnit.SECONDS) == false)
throw new TimeoutException("Timeout tracking Comparator service");
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-EventAdmin" >
<h3>Event Admin</h3>
<p>
The <strong class=" ">EventAdminTestCase</strong> uses the <a href="http://www.osgi.org/javadoc/r4v42/org/osgi/service/event/EventAdmin.html">EventAdmin</a> service to send/receive events. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testEventHandler() throws Exception
{
TestEventHandler eventHandler = new TestEventHandler();
// Register the EventHandler
Dictionary param = new Hashtable();
param.put(EventConstants.EVENT_TOPIC, new String[Introduction] { TOPIC });
context.registerService(EventHandler.class.getName(), eventHandler, param);
// Send event through the the EventAdmin
EventAdmin eventAdmin = EventAdminSupport.provideEventAdmin(context, bundle);
eventAdmin.sendEvent(new Event(TOPIC, null));
// Verify received event
assertEquals("Event received", 1, eventHandler.received.size());
assertEquals(TOPIC, eventHandler.received.get(0).getTopic());
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-JNDIService" >
<h3>JNDI Service</h3>
<p>
The <strong class=" ">NamingStandaloneTestCase</strong> gets the <strong class=" ">JNDIContextManager</strong> service and verifies JNDI access. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">ServiceReference<JNDIContextManager> sref = context.getServiceReference(JNDIContextManager.class);
JNDIContextManager contextManager = context.getService(sref);</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">Context initialContext = contextManager.newInitialContext();
BundleContext context = (BundleContext) initialContext.lookup("osgi:framework/bundleContext");
Assert.assertEquals(bundle.getBundleContext(), context);</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-JMXService" >
<h3>JMX Service</h3>
<p>
The <strong class=" ">MBeanServerTestCase</strong> tracks the MBeanServer service and registers a pojo with JMX. It then verifies the JMX access. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public class MBeanActivator implements BundleActivator
{
public void start(BundleContext context)
{
ServiceTracker tracker = new ServiceTracker(context, MBeanServer.class.getName(), null)
{
public Object addingService(ServiceReference reference)
{
MBeanServer mbeanServer = (MBeanServer)super.addingService(reference);
registerMBean(mbeanServer);
return mbeanServer;
}
@Override
public void removedService(ServiceReference reference, Object service)
{
unregisterMBean((MBeanServer)service);
super.removedService(reference, service);
}
};
tracker.open();
}
public void stop(BundleContext context)
{
ServiceReference sref = context.getServiceReference(MBeanServer.class.getName());
if (sref != null)
{
MBeanServer mbeanServer = (MBeanServer)context.getService(sref);
unregisterMBean(mbeanServer);
}
}
...
}</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testMBeanAccess() throws Exception
{
// Provide MBeanServer support
MBeanServer server = ManagementSupport.provideMBeanServer(context, bundle);
// Start the test bundle
bundle.start();
ObjectName oname = ObjectName.getInstance(FooMBean.MBEAN_NAME);
FooMBean foo = ManagementSupport.getMBeanProxy(server, oname, FooMBean.class);
assertEquals("hello", foo.echo("hello"));
}</pre>
</div>
</div>
<p>
The <strong class=" ">BundleStateTestCase</strong> uses JMX to control the bundle state through the BundleStateMBean. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testBundleStateMBean() throws Exception
{
MBeanServer server = ManagementSupport.provideMBeanServer(context, bundle);
ObjectName oname = ObjectName.getInstance(BundleStateMBean.OBJECTNAME);
BundleStateMBean bundleState = ManagementSupport.getMBeanProxy(server, oname, BundleStateMBean.class);
assertNotNull("BundleStateMBean not null", bundleState);
TabularData bundleData = bundleState.listBundles();
assertNotNull("TabularData not null", bundleData);
assertFalse("TabularData not empty", bundleData.isEmpty());
}</pre>
</div>
</div>
</div>
</div>
<div class="section-2" id="4784855_ProvidedExamples-ExamplesforWildFlyIntegration" >
<h2>Examples for WildFly Integration</h2>
<p>
This section covers example tests that only run both in the remote WildFly integration. </p>
<div class="section-3" id="4784855_ProvidedExamples-CDIIntegration" >
<h3>CDI Integration</h3>
<p>
The <strong class=" ">ManagedBeansTestCase</strong> deploys and EAR file that contains a WAR and three bundles. The first bundle tracks payment service providers </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"> private BundleContext context;
@Resource
public void setContext(BundleContext context) {
this.context = context;
}
private List<PaymentProvider> providers = new ArrayList<PaymentProvider>();
@PostConstruct
@SuppressWarnings({ "unchecked", "rawtypes" })
public void start() {
ServiceTracker tracker = new ServiceTracker(context, PaymentProvider.class.getName(), null) {
@Override
public Object addingService(ServiceReference reference) {
PaymentProvider service = (PaymentProvider) super.addingService(reference);
providers.add(service);
return service;
}
@Override
public void removedService(ServiceReference reference, Object service) {
providers.remove(service);
super.removedService(reference, service);
}
};
tracker.open();
}</pre>
</div>
</div>
<p>
The other two bundles each provide an OSGi payment service, which gets injected into the webapp via CDI. The advantage of this approach is that we can construct modular web applications from independent components (i.e. bundles) which have lifecyle. We can therefore easily add/remove/start/stop/update payment service providers. </p>
</div>
<div class="section-3" id="4784855_ProvidedExamples-EARDeployments" >
<h3>EAR Deployments</h3>
<p>
The <strong class=" ">EnterpriseArchiveTestCase</strong> shows that OSGi bundles can be deployed as part on an EAR. It is guaranteed the contained bundles all get 'installed' before they get 'resolved' and 'started'. With a large set of individual bundle deployments that have complex interdependencies it would be hard to deploy the bundles in the correct order. EAR deployments fix that ordering issue. </p>
</div>
<div class="section-3" id="4784855_ProvidedExamples-EJB3Integration" >
<h3>EJB3 Integration</h3>
<p>
The <strong class=" ">StatelessBeanTestCase</strong> verifies that an EJB can be deployed as OSGi bundle. The stateless session bean then accesses on OSGi services </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">@Stateless
@LocalBean
public class SimpleStatelessSessionBean implements Echo {
@Resource
BundleContext context;
public String echo(String message) {
if (context == null)
throw new IllegalStateException("BundleContext not injected");
if (BUNDLE_SYMBOLICNAME.equals(message)) {
Bundle bundle = getTargetBundle();
return bundle.getSymbolicName();
}
...
}
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-HttpService" >
<h3>HttpService</h3>
<p>
The <strong class=" ">HttpServiceTestCase</strong> deploys a Service that registeres a servlet and a resource with the <a href="http://www.osgi.org/javadoc/r4v41/org/osgi/service/http/HttpService.html">HttpService</a>. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">ServiceTracker tracker = new ServiceTracker(context, HttpService.class.getName(), null);
tracker.open();
HttpService httpService = (HttpService)tracker.getService();
if (httpService == null)
throw new IllegalStateException("HttpService not registered");
Properties initParams = new Properties();
initParams.setProperty("initProp", "SomeValue");
httpService.registerServlet("/servlet", new EndpointServlet(context), initParams, null);
httpService.registerResources("/file", "/res", null);</pre>
</div>
</div>
<p>
The test then verifies that the registered servlet context and the registered resource can be accessed. </p>
</div>
<div class="section-3" id="4784855_ProvidedExamples-JAXBIntegration" >
<h3>JAXB Integration</h3>
<p>
The <strong class=" ">XMLBindingTestCase</strong> verifies that an OSGi bundle can use the JAXB integration that is available in WildFly </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"> builder.addImportPackages("javax.xml.bind", "javax.xml.bind.annotation");
builder.addImportPackages("javax.xml.datatype", "javax.xml.namespace");
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class...);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
URL resURL = bundle.getResource("booking.xml");
JAXBElement<CourseBooking> rootElement = unmarshaller.unmarshal(resURL.openStream());
assertNotNull("root element not null", rootElement);</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-JPAIntegration" >
<h3>JPA Integration</h3>
<p>
The <strong class=" ">PersistenceTestCase</strong> verifies that an OSGi bundle can use the Hibernate JPA integration in WildFly </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"> EntityManagerFactory emf = null;
try {
ServiceReference<EntityManagerFactory> sref = context.getServiceReference(EntityManagerFactory.class);
emf = context.getService(sref);
Employee emp = new Employee();
emp.setId(100);
emp.setAddress("Sesame Street");
emp.setName("Kermit");
EntityManager em = emf.createEntityManager();
em.persist(emp);
emp = em.find(Employee.class, 100);
Assert.assertNotNull("Employee not null", emp);
em.remove(emp);
} finally {
if (emf != null) {
emf.close();
}
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-JTAService" >
<h3>JTA Service</h3>
<p>
The <strong class=" ">TransactionTestCase</strong> gets the <a href="http://java.sun.com/javaee/5/docs/api/javax/transaction/UserTransaction.html">UserTransaction</a> service and registers a transactional user object (i.e. one that implements <a href="http://java.sun.com/javaee/5/docs/api/javax/transaction/Synchronization.html">Synchronization</a>) with the <a href="http://java.sun.com/javaee/5/docs/api/javax/transaction/TransactionManager.html">TransactionManager</a> service. It then verifies that modifications on the user object are transactional. </p>
<p>
This functionality is only available in the context of AS7. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">Transactional txObj = new Transactional();
ServiceReference userTxRef = context.getServiceReference(UserTransaction.class.getName());
assertNotNull("UserTransaction service not null", userTxRef);
UserTransaction userTx = (UserTransaction)context.getService(userTxRef);
assertNotNull("UserTransaction not null", userTx);
userTx.begin();
try
{
ServiceReference tmRef = context.getServiceReference(TransactionManager.class.getName());
assertNotNull("TransactionManager service not null", tmRef);
TransactionManager tm = (TransactionManager)context.getService(tmRef);
assertNotNull("TransactionManager not null", tm);
Transaction tx = tm.getTransaction();
assertNotNull("Transaction not null", tx);
tx.registerSynchronization(txObj);
txObj.setMessage("Donate $1.000.000");
assertNull("Uncommited message null", txObj.getMessage());
userTx.commit();
}
catch (Exception e)
{
userTx.setRollbackOnly();
}
assertEquals("Donate $1.000.000", txObj.getMessage());</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">class Transactional implements Synchronization
{
public void afterCompletion(int status)
{
if (status == Status.STATUS_COMMITTED)
message = volatileMessage;
}
...
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-LifecycleInterceptor" >
<h3>Lifecycle Interceptor</h3>
<p>
The <strong class=" ">LifecycleInterceptorTestCase</strong> deployes a bundle that contains some metadata and an interceptor bundle that processes the metadata and registeres an http endpoint from it. The idea is that the bundle does not process its own metadata. Instead this work is delegated to some specialized metadata processor (i.e. the interceptor). </p>
<p>
Each interceptor is itself registered as a service. This is the well known <a href="http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf">Whiteboard Pattern</a>. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public class InterceptorActivator implements BundleActivator
{
public void start(BundleContext context)
{
LifecycleInterceptor publisher = new PublisherInterceptor();
LifecycleInterceptor parser = new ParserInterceptor();
// Add the interceptors, the order of which is handles by the service
context.registerService(LifecycleInterceptor.class.getName(), publisher, null);
context.registerService(LifecycleInterceptor.class.getName(), parser, null);
}
}</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public class ParserInterceptor extends AbstractLifecycleInterceptor
{
ParserInterceptor()
{
// Add the provided output
addOutput(HttpMetadata.class);
}
public void invoke(int state, InvocationContext context)
{
// Do nothing if the metadata is already available
HttpMetadata metadata = context.getAttachment(HttpMetadata.class);
if (metadata != null)
return;
// Parse and create metadta on STARTING
if (state == Bundle.STARTING)
{
VirtualFile root = context.getRoot();
VirtualFile propsFile = root.getChild("/http-metadata.properties");
if (propsFile != null)
{
log.info("Create and attach HttpMetadata");
metadata = createHttpMetadata(propsFile);
context.addAttachment(HttpMetadata.class, metadata);
}
}
}
...
}</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public class PublisherInterceptor extends AbstractLifecycleInterceptor
{
PublisherInterceptor()
{
// Add the required input
addInput(HttpMetadata.class);
}
public void invoke(int state, InvocationContext context)
{
// HttpMetadata is guaratied to be available because we registered
// this type as required input
HttpMetadata metadata = context.getAttachment(HttpMetadata.class);
// Register HttpMetadata on STARTING
if (state == Bundle.STARTING)
{
String servletName = metadata.getServletName();
// Load the endpoint servlet from the bundle
Bundle bundle = context.getBundle();
Class servletClass = bundle.loadClass(servletName);
HttpServlet servlet = (HttpServlet)servletClass.newInstance();
// Register the servlet with the HttpService
HttpService httpService = getHttpService(context, true);
httpService.registerServlet("/servlet", servlet, null, null);
}
// Unregister the endpoint on STOPPING
else if (state == Bundle.STOPPING)
{
log.info("Unpublish HttpMetadata: " + metadata);
HttpService httpService = getHttpService(context, false);
if (httpService != null)
httpService.unregister("/servlet");
}
}
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-ResourceInjection" >
<h3>Resource Injection</h3>
<p>
The <strong class=" ">ResourceInjectionTestCase</strong> verifies that resources can be injected in OSGi bundle activators. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public class ResourceInjectionActivator implements BundleActivator {
@Resource(name = "java:jboss/datasources/ExampleDS")
public DataSource ds;
public void start(BundleContext context) throws Exception {
String productName = ds.getConnection().getMetaData().getDatabaseProductName();
...
}
}</pre>
</div>
</div>
<p>
</p>
</div>
<div class="section-3" id="4784855_ProvidedExamples-RESTIntegration" >
<h3>REST Integration</h3>
<p>
The <strong class=" ">RestEndpointTestCase</strong> verifies that OSGi bundles can provide REST endpoints. REST endpoints can therefore be part of larger modular applications and have lifecycle - they can be started/stopped/updated, etc. REST endpoints can access OSGi services. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">@Path("/rest")
@Consumes({ "application/json" })
@Produces({ "application/json" })
public class SimpleRestEndpoint {
private static final Logger log = Logger.getLogger(SimpleRestEndpoint.class);
@Resource
private BundleContext context;
@GET
@Path("/echo/{message}")
public String echo(@PathParam("message") String message) {
ServiceReference<Echo> sref = context.getServiceReference(Echo.class);
return context.getService(sref).echo(message);
}
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-WebServicesIntegration" >
<h3>Web Services Integration</h3>
<p>
The <strong class=" ">WebServiceEndpointTestCase</strong> verifies that OSGi bundles can provide WebService endpoints. WebService endpoints can therefore be part of larger modular applications and have lifecycle - they can be started/stopped/updated, etc. WebService endpoints can access OSGi services. </p>
</div>
<div class="section-3" id="4784855_ProvidedExamples-WebApplication" >
<h3>Web Application</h3>
<p>
The <strong class=" ">WebAppTestCase</strong> deploys an OSGi Web Application Bundle (WAB). Similar to HTTP Service Example it registers a servlet and resources with the WebApp container. This is done through a standard web.xml descriptor. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;"><web-app xmlns="http://java.sun.com/xml/ns/javaee" ... version="2.5">
<display-name>WebApp Sample</display-name>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>org.jboss.test.osgi.example.webapp.bundle.EndpointServlet</servlet-class>
<init-param>
<param-name>initProp</param-name>
<param-value>SomeValue</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app></pre>
</div>
</div>
<p>
The associated OSGi manifest looks like this. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: example-webapp
Bundle-ClassPath: .,WEB-INF/classes
Web-ContextPath: example-webapp
Import-Package: javax.servlet,javax.servlet.http,...</pre>
</div>
</div>
<p>
The test verifies that we can access the servlet and some resources. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">public void testServletAccess() throws Exception
{
// Provide WebApp support
WebAppSupport.provideWebappSupport(context, bundle);
// Start the test bundle
bundle.start();
String line = getHttpResponse("/example-webapp/servlet?test=plain", 5000);
assertEquals("Hello from Servlet", line);
}</pre>
</div>
</div>
</div>
<div class="section-3" id="4784855_ProvidedExamples-XMLParserServices" >
<h3>XML Parser Services</h3>
<p>
The XML parser test cases get a DocumentBuilderFactory/SAXParserFactory respectivly and unmarshalls an XML document using that parser. </p>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">DocumentBuilderFactory factory = XMLParserSupport.provideDocumentBuilderFactory(context, bundle);
factory.setValidating(false);
DocumentBuilder domBuilder = factory.newDocumentBuilder();
URL resURL = context.getBundle().getResource("example-xml-parser.xml");
Document dom = domBuilder.parse(resURL.openStream());
assertNotNull("Document not null", dom);</pre>
</div>
</div>
<div class="confbox programlisting">
<div class="content">
<pre class="brush: java; gutter: false;">SAXParserFactory factory = XMLParserSupport.provideSAXParserFactory(context, bundle);
factory.setValidating(false);
SAXParser saxParser = factory.newSAXParser();
URL resURL = context.getBundle().getResource("example-xml-parser.xml");
SAXHandler saxHandler = new SAXHandler();
saxParser.parse(resURL.openStream(), saxHandler);
assertEquals("content", saxHandler.getContent());</pre>
</div>
</div>
</div>
</div>
</div>
<ul class="docnav">
<li class="previous"><a accesskey="p" href="Arquillian_Test_Framework.html"><strong>Prev</strong>Arquillian Test Framework</a></li>
<li class="up"><a accesskey="u" href="#"><strong>Top of page</strong></a></li>
<li class="home"><a accesskey="h" href="User_Guide.html"><strong>Front page</strong></a></li>
<li class="next"><a accesskey="n" href="References.html"><strong>Next</strong>References</a></li>
</ul>
</div>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>