Calling services from Java
With the services created, they can now be used. Eventually, we'll be using the services remotely and during web page delivery, but
for now, we'll use them directly within Java.
Here's the highlights:
LocalServices is the service accessor used to take services within the same JVM.
When taking a service, pass the service interface you want to use. An instance will be created
and returned. This instance can then be used:
// get services, as we'll be using them
PerformerService performerService = (PerformerService) LocalServices.takeAService(
PerformerService.class);
AlbumService albumService=(AlbumService) LocalServices.takeAService(AlbumService.class);
try {
// use the services
} finally {
LocalServices.returnAService(performerService);
LocalServices.returnAService(albumService);
}
Once the service has been used, the instances should be returned to LocalServices. This
should be done at the end of a try/finally block, so that the services are returned even in the case
of an error. By returning the services they can be reused, which improves performance. It won't do any harm to not
return them, but it's not encouraged.
- The services are then used to perform operations, such as creating artists:
// create a new artist
ArtistImpl aphex = (ArtistImpl) performerService.createArtist("Aphex Twin");
- Tracks are added to created albums. This modifies the album, so it needs to be updated.
// update the album as it's been updated
saw8592.update();
The albums are added and then fetched and dumped, producing the results:
Aphex Twin - Selected Ambient Works 85-92
1 Xtal (3064s)
2 Tha (69s)
3 Pulsewidth (2823s)
4 Ageispolis (1265s)
5 i (781s)
6 Green Calx (126s)
7 Heliosphan (3064s)
8 We Are The Music Makers (2527s)
9 Schottkey 7th Path (425s)
10 Ptolemy (727s)
11 Hedpheylm (126s)
12 Delphium (2165s)
13 Actium (2107s)
DATacide - Flowerhead
1 Flashback Signal (3255s)
2 Flowerhead (1989s)
3 Deep Chair (314s)
4 So Much Light (132s)
5 Sixties Out Of Tune (313s)
By using LocalServices, the services may be accessed and used in the
local JVM. The services are nice for grouping functionality, but they become more
useful when used in the construction of dynamic web pages. Let's prepare for that by
creating a simple page.