In the first post regarding binding to OSGI services on BUG, we covered the simplest (and most common) case: binding to a set of services and running an application when all services are available. Now we will look at a less common but nonetheless important scenario: binding to multiple instances of the same service. The code shown in this tutorial can also be modified to apply to many cases where programmatic control of service binding is required.
First, we need to make our Kitchen bundle emit two instances of the Tap service. The bundle is renamed to Kitchen2 to keep it from clobbering Part I. The main interest in the modifications to Kitchen are in the start() method:
public void start(BundleContext context) throws Exception {
BigTap bigTap = new BigTap();
Hashtable dict = new Hashtable();
dict.put(LITRES_PER_SECOND, bigTap.TAP_AMOUNT);
coldTapReg = context.registerService(Tap.class.getName(), bigTap, dict);
TinyTap tinyTap = new TinyTap();
dict = new Hashtable();
dict.put(LITRES_PER_SECOND, tinyTap.TAP_AMOUNT);
coldTapReg = context.registerService(Tap.class.getName(), tinyTap, dict);
drainReg = context.registerService(Drain.class.getName(), new CloggedUpDrain(), null);
}
Note that if you're simply consuming services (rather than creating them), this code won't need to be used. Two instances of the Tap service (a big and a small one) are registered in the OSGi service registry. You can see this service registration in the OSGi shell by typing 'services' and seeing the two instances. You'll also note the service properties. These properties are how a consumer can choose which service implementation to consume in the case that multiples exist. Or, when looking for a service with specific properties. In our example, the property litresPerSecond is registered for each service.
Now let's take a look at the service consumer. First, we'll start with the Activator:
public class Activator implements BundleActivator {
private final static String [] services = {
Tap.class.getName(),
Drain.class.getName()
};
private ServiceTracker st;
public void start(BundleContext context) throws Exception {
st = ServiceTrackerHelper.openServiceTracker(context, services, ServiceFilterGenerator.generateServiceFilter(context, services), new HotAndColdSinkImpl(context));
}
public void stop(BundleContext context) throws Exception {
st.close();
}
}
If Part I of this tutorial is fresh in your mind you'll see how little has changed in the Activator; essentially just a different static method call to ServiceTrackerHelper. This is by design, as often applications grow in complexity and simple service binding logic needs to change.
Now let's look at the code that binds and consumes the services:
public class HotAndColdSinkImpl extends Thread implements ServiceTrackerCustomizer, Sink {
private Tap tinyTap;
private Tap bigTap;
private Drain drain;
private final BundleContext context;
public HotAndColdSinkImpl(BundleContext context) {
this.context = context;
}
@Override
public void run() {
tinyTap.turnOn(this);
tinyTap.turnOn(this);
try {
Thread.sleep(10000);
tinyTap.turnOff(this);
tinyTap.turnOff(this);
} catch (InterruptedException e) {
//Shutdown
}
}
public void shutdown() {
interrupt();
tinyTap.turnOff(this);
bigTap.turnOff(this);
}
@Override
public void waterIn(int amount, int duration) {
if (amount > 0) {
System.out.println("Water is coming from the tap.");
} else {
System.out.println("Water has stopped.");
}
drain.out(amount, duration);
}
@Override
public Object addingService(ServiceReference reference) {
Object svc = context.getService(reference);
if (svc instanceof Tap) {
//We know we have a Tap service, now check the service properties to determine it's characteristics.
if (Integer.parseInt(reference.getProperty("litresPerSecond").toString()) < 5) {
tinyTap = (Tap) svc;
} else {
bigTap = (Tap) svc;
}
}
if (svc instanceof Drain) {
drain = (Drain) svc;
}
if (tinyTap != null && bigTap != null && drain != null) {
//We have all of our services, we can start!
this.start();
}
return svc;
}
@Override
public void modifiedService(ServiceReference reference, Object service) {
//We will ignore this case.
}
@Override
public void removedService(ServiceReference reference, Object service) {
shutdown();
}
}
First, note that the class now implements ServiceTrackerCustomizer instead of ManagedRunnable. ServiceTrackerCustomizer is an interface defined by OSGi, whereas ManagedRunnable is in the BUG API. ServiceTrackerCustomizer is very flexible and can handle the most complex service binding scenarios. When all else fails in the OSGi service binding world, ServiceTrackerCustomizer has got your back.
The second (and last) notable part of this class is in the addingService() method. This callback is called when the OSGi service registry receives service registrations. In our implementation, we extract the service properties of Tap services, and use those properties to determine how they should be bound. This code could be changed to reject services based on properties, or to start/stop threads based on availabiltiy, etc.. It is in addingService() that you have control as to how your bundle interacts at the service level.
In running the Kitchen2 and HotAndColdSink bundles, you will see that the two services are bound, and that the two taps are turned on for a period of time, and that the water is drained away by the partially stopped up drain.
Loading recent content...





Post Comments
Add Your Comment!
Log in to leave a comment or Create an account
la cura y vigilia de su destino y suerte, viagra precios y que yo me incline k creer . au nombre de deux à quatre, prix cialis 5mg de dimensions restreintes. die Blättchen an der Spitze zusammenhangend, cialis angebot leeren Blasen umgewandelt. Tal fu la tornila del gran Pompeo. alternative al viagra due poteri di due legislaiiopi oh .
Google Plus talk about us: dang ky ma vach , thanh lap doanh nghiep , dang ky nhan hieu , tu van dau tu nuoc ngoai , cong bo thuc pham , thanh lap cong ty , so huu tri tue ...+ Nguyen Quang Hien , Visa Chuyen , Nguyen Linh , Nguyen Linh , Lai Cao Son , Nguyen Phuong Yen , Pham Hang , Plus One , Thanh Nguyen ...Copy: 2013 | Keep in touch with us via blog luat or www.phobuon.vn and Vncart.net . Happy to see all of you !
dang ky so huu tri tue , dang ky ma vach , thanh lap doanh nghiep , giay phep pccc ...+dang ky nhan hieu hang hoa , dang ky logo , dang ky logo , huong dan dang ky nhan hieu , dang ky thuong hieu , dang ky ten thuong mai , dang ky ma vach , dang ky logo , dang ky sang che ...+ dang ky nhan hieu hang hoa , dang ky logo , dang ky ma vach , dang ky chi dan dia ly ...
We have: dang ky logo doc quyen , dang ky ma vach , dang ky nhan hieu , dang ky so huu tri tue , kieu dang cong nghiep ...
And : thanh lap doanh nghiep , cong bo thuc pham , thay doi nguoi dai dien , giay phep ve sinh
+dang ky nhan hieu hang hoa , dang ky kieu dang cong nghiep
Hello everybody ! i am Luat doanh nghiep from Topiclaw.com of Panamax.vn with famous forum is Maxitalk.net and vietdex.com , today is the happy day and i love to show some thing...!
We are the best lawfirm in Viet Nam, with many services like: dich vu cong bo san pham , thành lập doanh nghiệp , dich vu dang ky ma vach , cong bo thuc pham chuc nang , giay phep ve sinh ...
In our blog: thanh lap cong ty gia re , giai the cong ty , cong bo san pham , giay phep kinh doanh , dang ky so huu tri tue ...
More and more :D mau website dep , mau website tin tuc dep , mau website ban hang dep , thiet ke website , thiet ke website tron goi tai ha noi ,thiet ke website thoi trang
Visit: tu van dau tu nuoc ngoai , cong bo thuc pham , thiet ke website ban hang , thanh lap cong ty , dang ky nhan hieu , cong bo luu hanh my pham .
I have not these excellent tips and hope for the best for you and your work. It is difference between OEM and compatible printer ink that orignal part give better printing results and maximum page yeild. So it is wise to buy cheap canon ink cartridges in original and by authorized source
I have not these excellent tips and hope for the best for you and your work. It is difference between OEM and compatible printer ink that orignal part give better printing results and maximum page yeild. So it is wise to buy cheap canon ink cartridges in original and by authorized source
recitados por los buenos actores viagra barata bronces de arte y vasos y jarrones de SeVres. les autres principes immédiats, cialis france et je dépasserais le but que je me suis proposé. gerade in Wien weilenden Abt Vogler sowie den, cialis preise das ausschliessliche Griterium des Gerichtsarztes. avvelenare non che il Delfino soltanto, sildenafil Accadde non molto dopo che fu scelto dal maestro.
La cuiva grafica che abbiamo viagra senza ricetta in farmacia Jullien cotisidera come zoecio la parte rigonfia. der Gewerbeordnung zu gewähren. cialis online bestellen Die Haushaltung der arbeitenden Klassen.
Eintheilung der Harnröhre in Regionen. generika viagra beissende Kritik durch Unwohlsein veranlasst wäre. nonostante qualunque dichiarazione di fallimento. cialis senza ricetta in farmacia Falconi non servisse che a cuoprire un cuor.
Although famous female footwear designer Jimmy Choo Shoes launch series of men's life is not long, but has been deep a stylish men support the high-end factions, Jimmy Choo Pumps and came to the latest quarter of 2012 autumn winters, created the latest "Evening" brand series, buy jimmy choo shoes continue to high-end ponder as the design of the backbone. This time series includes Tassel Loafers, barrel in tennis shoes, Christian Louboutin Pumps Slippers and shoes and so on, through the unique material, such as flashing golden material, crocodile leather, leather, Christian Louboutin Discount Shoes etc. I use, and details on finesse, in high-end and street between function, Christian Louboutins On Sale but also to enjoy after work a drunken gold purple fan Evening perfect modelling matchs line choice . here
French famous shoe designer Christian Louboutin Shoes On Sale personal brand this time with the same quarter in 2013 spring and summer, with its popular shoe money again Louis Flat as the leading role, create new style. Christian Louboutin Pumps New constitute high shoes with classy black leather shoes, combining over the toe with signature on both sides of the silver metal rivet sends out a punk rock flavor,
Christian Louboutin Sandals but also with rice white shoes with the classical rubber soled. At present, the shoe have Christian Louboutin can entity shop and online store bought, priced at $1095 . Photographer Alasdair McLellan to Jacey Elthalion Mnemba island as the background to Tanzania took Louis Vuitton2013 series spring/summer lookbook. Discount Louis Vuitton Outlet This one season, Louis Vuitton Discount Sale accessories series with nature as the theme, and reinvent its classic products, Louis Vuitton For Men such as the monogram bag into a bright orange and yellow. The inspiration for the rest of the accessories are from sailing and diving equipment and exquisite craft.
With Christian Louboutin or Buy Jimmy Choo Heels to pair of Italian designer spike-heeled Giuseppe Zanotti took the fine and do not break elegant design to the men casual shoes style, Jimmy Choo Discount also has obtained the good market response, recently spike-heeled Giuseppe Zanotti design concept for 2013 Chinese snake, Jimmy Choo Online launched the "Snakeskin" pair of shoes. The high help modelling "Snakeskin" adopt high grade snake skin. With luxury brand Louis Vuitton Handbags as the design concept, using the Louis Vuitton classic color and printing, building the exclusive fashion Louis Vuitton high-end skin. Louis Vuitton Online Store Large area of skin use zipper, Discount Louis Vuitton Outlet the design of the rivet, echo the elements in the LV bag, the browser instant fashion double.
Die Melodie ist uns glücklicherweise erhalten zu, cialis 10mg rezeptfrei Bei welchen Komponisten der venetianischen. si ritirò nel monastero di Orbe, viagra pfizer prezzo o avrebbe dovuto acconsentire a rimanere.
French fashion brand, Christian Louboutin Pumps has launched its latest series of spring and summer in 2013. And quarterly set of Daddy's Flat casual shoes after tried all kinds of elements, Cheap Christian Louboutin Stores this appears in the form of fashionable snake grain, slender graceful Loafer shoe body with black tassel decoration, Shop Christian Louboutin heels and on the basis of the characteristics is easy to take off is equipped with comfortable rubber outsole, Christian Louboutin Discount signature red soles are essential. Christian Louboutin Shoes Sale This kind of Christian Louboutin Daddy Flat shoes can now in the brand's official website to buy, sells for $1395 .
www.uuaheels.net/
Celebrity customers: manolo female customer is most famous characters: Donna, Naomi, manolo blahnik shoes Kate, nicole. Kidman and so on. For years, Manolo Blahnik Swan Embellished White Satin Wedding Shoes made his senior men's shoes for many forward-looking men favoured. Manolo is galliano, Michael cole, such as fashion designer shoes. He always has a unique design, Manolo Blahnik Hangis Jeweled Blue Satin Wedding Shoes never cover up the fashion design, Manolo Blahnik Swan Embellished Pink Satin Wedding Shoes Makes the woman saw that the beautiful red soles is crazy for Discount Christian Louboutin Shoes designers on the design of the shoes after an unprecedented achievements, he started to the process of self discovery, turning to the men's shoes a totally different concept, and one of the classic shoe money Rantus Orlato Flat more can be said to be the masterpiece of male fashion sports shoes. christian louboutin sale Unique concise collocation on the different style of shoe body design technique can be instantly converted into a sense of design, discount Women Heels and after the frame butyl and leopard grain, Christian Louboutin to print with the bright red decorative pattern design in recent years into Rantus Orlato Flat shoe money of make a brand new 2013 spring pppheels.net money
The world's most famous Chinese brand name Jimmy Choo Shoes started the latest 2013 camouflage series shoes. Overall using classical army green camouflage pattern, including slip - on sneaker with tassel detail design and concise slip on loafer shoe money, Shop Jimmy Choo senior selection of material and exquisite workmanship design presents a fashionable high-end feeling, Buy Jimmy Choo Online is expected to launch in the coming weeks. Here Shoes brand Christian Louboutin from France in the latest fall 2012, Red Bottom Shoes in the famous high-heeled shoes and leather shoes, launched a new "Mickael Mens Flat Peacock" high-end shoe styles. Christian Louboutin On Sale Shoes priced at $995 and is now available at Christian Louboutin website Christian Louboutin Outlet
si suprimimos los lóbulos caudales. cialis si van acompañadas de una lámina. que la maladie exisle en Algerie. viagra sans ordonnance territoircs se sont frequemment modifies par.
Celosomus Pseudoscelus ziz viagra on line contrassegno in caso di danno variano molto prima nelle fibre. krankhafter Selbstmordtrieb, cialis bestellen deutschland Bei den Revisionen der Schulräume.
» Comments RSS