Service and Component in OSGI - java

I have some little silly doubts in an OSGI concepts but they need to be clarified to have better understanding of concepts. Can anybody tell me what is the difference between OSGI Service and Component. What i know is that Service is like an interface file in java that can be used either by a different service or by a component. While component is like a particular implementation of the service.
Please let me know if i am wrong or suggest some link from where i can get the things nicely.

The OSGi Core specification defines the service model which is a key part of the OSGi concept. A service is an object (instance) which implements a declared type (normally an interface). The OSGi framework provides the service layer which is a broker between service providers and service consumers.
DS introduced the concept of Service Components which are classes in a bundle which that are managed by the DS runtime (SCR). The components are described by XML in the bundle which is read by SCR. These components, once instantiated and if declared to be services, can be registered as services by SCR.
So components can be services (but they do not have to be) and they can use services.

OSGi evolved the concept of services, so that bundles could reduce their coupling with other bundles - ie. achieve loose coupling. The 'loosest' coupling comes from using dynamic services, where bundles that produce services are started dynamically as consumers register to consume those services. The dynamic services model went through several evolutions with OSGi, through service registration and event listening, Service Tracker, and finally Declarative Services.
With all but the last (Declarative Services), the service registration code is put in the bundle's Activator. With Declarative Services, the bundle that exposes a service is called a component and it's declared in a component.xml file that the framework understands - no need for activators. In the Eclipse IDE, you can use Declarative Services by right-clicking on a bundle and adding a 'Component Definition'. There's a really good book on the subject that takes you through the technology with tutorials:
OSGi and Equinox

Related

Osgi bundles and their relation with packages

For an application written using OSGi specifications
A service is a java object that represents a feature, recording a voice call for example
Every service has a number of packages associated with it, for example, service interface, service implementation, and slick.
I can't get the relation between the above and OSGi bundles, as bundles contain services does that mean they contain the service packages or something else
An OSGi service is a mechanism for bundles to communicate over a well defined Java interface known to all parties. OSGi acts as a broker where one party can register a service under the interface name, and other parties can get it under this interface name. I.e. the actual implementation class is decoupled from the users of the service. This allows the use of different implementation classes while the user of the service is unaware. I.e. for example, if you want to set up a voice call, there could be an PhoneExchange service that would provide you with the functions to setup the call and maybe record it. You can then write your code against the PhoneExchange interface. In runtime, you might be coupled to an Ericsson PBX or a Nokia one.
This decoupling is also present with Java factories. However, Java factories have many disadvantages, and tend to be very static. The OSGi broker is a dynamic broker. A service can be registered but also unregistered. The dynamism in OSGi is seen by many as hard to handle but the Declarative Services makes that more or less trivial. When you really get the dynamism of OSGi services you will find out that many complex dynamic scenarios, like for example communication channels, map extremely well.
The bundle is the module in OSGi. It contains all the Java code and resources. A bundle will export and import Java packages. In a well designed system, these are only the Java packages that hold the service interfaces. It is a bad pattern to export implementation packages. At startup, bundles are wired. This means that exporters get bound to importers. OSGi is unique in that it can handle the same package in multiple versions.
Bundles have their own life cycle. They get started and stopped. In both cases, they can run their own private code.
The aforementioned Declarative Services provide yet another layer. When a Java class declares it is a component with an annotation, it can also declare on what services it depends. When these services are registered, they are injected and the component is activated. Declarative Services allow you to eat your cake and have it to. You get the incredibly powerful dynamics without the associated complexity.

OSGI Bundle Structure and communication to other bundles in CQ5

As per my understanding when developing with CQ5, service layer will be located on the OSGI bundle. Does that mean for every service classes that I will create it will be equivalent to one OSGI Bundle? For example if I have 3 services for my CQ5 application namely: Login Service, UserManagement Service, Registration Service does it mean that there will be also 3 OSGI bundles to be deployed? and how does this bundles will communicate with each other?
Not really. Bundles are more like modules. So you can split your services into bundles basing on their functionality or if you would like to reuse them in other projects. For example you can have next structure:
projectname-core: there you can have services, which can be used by other project as well. Like some content feed generators for external services, Log-in service (if it will be useful in other project as well:
projectname-ui-beans: there you can have beans, which you will be injecting on your jsp pages;
projectname-services: general services, which are specific for this project, like search or registration;
projectname-taglib: there you have your own jsp tags implementation;
projectname-it-test: bundle with integration tests;
projectname-some-specific-stuff: there can be some services which are not dependent on any other bundle, like one-time content manipulation;
Refer this topic for basic structure and Maven archetype for creating it.
Upd1: Communication between bundles can be done in two ways:
you can have one of your bundles as a dependency for another bundle. Then, you could just use #Reference to get services from other bundle
also you can use events to do communication, see this for details.
Having small, focused bundles is good in my opinion, but it doesn't necessarily mean one bundle per service. In your case, login, user management and registration look sufficiently different to warrant their own bundles. But user management for example might be implemented by several services, all provided by the same bundle.
A good rule of thumb is to design your bundles so that removing one of them disables a consistent unit of functionality. Removing your "user management" bundle for example would disable all user management features, ideally without affecting login or registration.
As for communication, think in services. Using Declarative Services, OSGi components simply declare which services they require (usually using #Reference annotations) and the framework takes care of only starting a component once all the services that it requires are available.

Get Declarative Service at runtime

What is the correct way to get a service, hopefully using Declarative Service if possible, when you don't know the attributes of the service to request until after runtime?
The use case is analogous to having 3 bundles providing services version 1.0, 2.0 and 3.0 but not knowing which one will be consumed until the user chooses one in the UI. If the user chooses 2.0 the consumer will consume the stuff from bundle 2.0
We are using BND annotations, so something with them would be ideal, but i have a feeling that we need to use the OSGi API directly instead of using annotations or declarative services injection.
Finally, if it is relevant, this is more to get different versions of a resource (XML schema) rather than about different behaviour/implementations. The idea was that the service would be providing its internal resource, which would be different in each version, even though the code in the service itself would be the same
I've worked in a similar system before and we had our own "routing" system. Basically when you register the services add the version number in the meta-data. Then in this routing mechanism pick the correct service. Your services will need to implement a common interface and in the router inject a List of them.
The declarative model of the Declarative Services specification is a build-time model, not a run-time one. To do run-time dependency management, you either need to do it yourself with a ServiceTracker, or use a different dependency management solution.
As one of its authors, I have a preference for the Apache Felix Dependency manager [1] which allows you to "declare" dependencies in Java code (at run-time, for example based on a choice made by a user in the UI like you say).It does not use Bnd annotations, but the code still allows you to use a declarative style and provides features like injection and/or callbacks.
Another solution that allows this is Apache Felix iPOJO [2].
[1] http://felix.apache.org/documentation/subprojects/apache-felix-dependency-manager.html
[2] http://felix.apache.org/documentation/subprojects/apache-felix-ipojo.html

Where do EJB3s fit in with SOA/EIP?

My (perhaps all-too-simple) understanding of EJB3 is that its a way of turning a POJO into a Java EE-compliant unit of business logic. It is reusable and can be "plugged in" to different backend architectures spanning multiple projects. It's a step in the direction of true component-driven architectures. If any of these assertions are untrue, please begin by correcting me!!
If I am correct on these items, then I'm wondering how/where/when/if EJB3s snap into an ESB like Apache Camel. With Camel each endpoint typically implements some EIP like WireTap, Filter, or Transformer. I'm wondering which of these EIP/SOA patterns the EJB (specifically EJB3) fits into. Is it a simple Filter? Something else?
I guess at the root of my question is this:
If I'm building a Camel Route, when does it makes sense to make an EJB3 an endpoint, as opposed to some other EIP? What are the use cases for EJB3s in an ESB and when are they preferable over other EIPs?
There is no right or wrong in this case.
EJB plugs very well into JavaEE application servers and are built to provide an architecture to encapsulate the business logic as Java code inside EJBs and let the application server handle scaling, throttling, fail over, clustering, load balancing etc, as well as exposure of the EJBs to communication protocols (Web Services or JMS for Message Driven Beans).
I see no real point in introducing EJBs as business logic containers in Apache Camel, unless you already have a full stack Java EE application that you want Camel to work with.
Camel has a great set of features to connect to "real" pojos through bean-binding.
I would recommend using simple java beans/pojos for business logic, and you can easily plug them in at any other application through camel's rich set of connectors. There are multiple options for implementing the different camel EIPs. One common way is with java code, but XSLT for transformations and groovy for filters is just as common. I would never use EJBs for simple filters, but rather invoke some complex logic inside a Java EE app. server, or typically avoid all together (except MDBs) and look at JMS communication with the application server instead.
Basically an EJB is a service. The idea behind a service is that it can simply be used without needing to create it as a consumer. Additionally services often can be looked up in a registry.
So my advice is to use the simple bean integration for cases where it is easy to instantiate the bean impl and to use services where it is difficult. So you can encapsulate the initialization inside the component that provides the service.
I am not using EJBs regularly but often use OSGi services which are very similar in concept to EJBs.
In addition to previous answers I'd mention that SOA is rather approach with specified requirements than a concrete technology stack. Make your EJB3 beans or OSGI services be operable via network regardless to operations systems, platforms and languages at least and you will have service-oriented system. So EJBs and OSGI or Spring-powered applications do fit to SOA when they do fulfill its requirements.

Modular web apps

I've been looking into OSGi recently and think it looks like a really good idea for modular Java apps.
However, I was wondering how OSGi would work in a web application, where you don't just have code to worry about - also HTML, images, CSS, that sort of thing.
At work we're building an application which has multiple 'tabs', each tab being one part of the app. I think this could really benefit from taking an OSGi approach - however I'm really not sure what would be the best way to handle all the usual web app resources.
I'm not sure whether it makes any difference, but we're using JSF and IceFaces (which adds another layer of problems because you have navigation rules and you have to specify all faces config files in your web.xml... doh!)
Edit: according to this thread, faces-config.xml files can be loaded up from JAR files - so it is actually possible to have multiple faces-config.xml files included without modifying web.xml, provided you split up into JAR files.
Any suggestions would be greatly appreciated :-)
You are very right in thinking there are synergies here, we have a modular web app where the app itself is assembled automatically from independent components (OSGi bundles) where each bundle contributes its own pages, resources, css and optionally javascript.
We don't use JSF (Spring MVC here) so I can't comment on the added complexity of that framework in an OSGi context.
Most frameworks or approaches out there still adhere to the "old" way of thinking: one WAR file representing your webapp and then many OSGi bundles and services but almost none concern themselves with the modularisation of the GUI itself.
Prerequisites for a Design
With OSGi the first question to solve is: what is your deployment scenario and who is the primary container? What I mean is that you can deploy your application on an OSGi runtime and use its infrastructure for everything. Alternatively, you can embed an OSGi runtime in a traditional app server and then you will need to re-use some infrastructure, specifically you want to use the AppServer's servlet engine.
Our design is currently based on OSGi as the container and we use the HTTPService offered by OSGi as our servlet container. We are looking into providing some sort of transparent bridge between an external servlet container and the OSGi HTTPService but that work is ongoing.
Architectural Sketch of a Spring MVC + OSGi modular webapp
So the goal is not to just serve a web application over OSGi but to also apply OSGi's component model to the web UI itself, to make it composable, re-usable, dynamic.
These are the components in the system:
1 central bundle that takes care of bridging Spring MVC with OSGi, specifically it uses code by Bernd Kolb to allow you to register the Spring DispatcherServlet with OSGi as a servlet.
1 custom URL Mapper that is injected into the DispatcherServlet and that provides the mapping of incoming HTTP requests to the correct controller.
1 central Sitemesh based decorator JSP that defines the global layout of the site, as well as the central CSS and Javascript libraries that we want to offer as defaults.
Each bundle that wants to contribute pages to our web UI has to publish 1 or more Controllers as OSGi Services and make sure to register its own servlet and its own resources (CSS, JSP, images, etc) with the OSGi HTTPService. The registering is done with the HTTPService and the key methods are:
httpService.registerResources()
and
httpService.registerServlet()
When a web ui contributing bundle activates and publishes its controllers, they are automatically picked up by our central web ui bundle and the aforementioned custom URL Mapper gathers these Controller services and keeps an up to date map of URLs to Controller instances.
Then when an HTTP request comes in for a certain URL, it finds the associated controller and dispatches the request there.
The Controller does its business and then returns any data that should be rendered and the name of the view (a JSP in our case). This JSP is located in the Controller's bundle and can be accessed and rendered by the central web ui bundle exactly because we went and registered the resource location with the HTTPService. Our central view resolver then merges this JSP with our central Sitemesh decorator and spits out the resulting HTML to the client.
In know this is rather high level but without providing the complete implementation it's hard to fully explain.
Our key learning point for this was to look at what Bernd Kolb did with his example JPetstore conversion to OSGi and to use that information to design our own architecture.
IMHO there is currently way too much hype and focus on getting OSGi somehow embedded in traditional Java EE based apps and very little thought being put into actually making use of OSGi idioms and its excellent component model to really allow the design of componentized web applications.
Check out SpringSource dm Server - an application server built entirely in terms of OSGi and supporting modular web applications. It is available in free, open source, and commercial versions.
You can start by deploying a standard WAR file and then gradually break your application into OSGi modules, or 'bundles' in OSGi-speak. As you might expect of SpringSource, the server has excellent support for the Spring framework and related Spring portfolio products.
Disclaimer: I work on this product.
Be aware of the Spring DM server licensing.
We've been using Restlet with OSGi to good effect with an embedded Http service (under the covers it's actually Jetty, but tomcat is available too).
Restlet has zero to minimal XML configuration needs, and any configuration we do is in the BundleActivator (registering new services).
When building up the page, we just process the relevant service implementations to generate the output, decorator style. New bundles getting plugged in will add new page decorations/widgets the next time its rendered.
REST gives us nice clean and meaningful URLs, multiple representations of the same data, and seems an extensible metaphor (few verbs, many nouns).
A bonus feature for us was the extensive support for caching, specifically the ETag.
SpringSource seems to be working on an interesting modular web framework built on top of OSGi called SpringSource Slices. More information can be found in the following blog posts:
Modular Web Applications with SpringSource Slices
Pluggable styling with SpringSource Slices
Slices Menu Bar Screencast
Have a look at RAP! http://www.eclipse.org/rap/
Take a look at http://www.ztemplates.org which is simple and easy to learn. This one allows you to put all related templates, javascript and css into one jar and use it transparently. Means you even have not to care about declaring the needed javascript in your page when using a provided component, as the framework does it for you.
Interesting set of posts. I have a web application which is customized on a per customer basis. Each customer gets a core set of components and additional components depending on what they have signed up for. For each release we have to 'assemble' the correct set of services and apply the correct menu config (we use struts menu) based on the customer, which is tedious to say the least. Basically its the same code base but we simply customize navigation to expose or hide certain pages. This is obviously not ideal and we would like to leverage OSGi to componentize services. While I can see how this is done for service APIs and sort of understand how resources like CSS and java script and controllers (we use Spring MVC) could also be bundled, how would you go about dealing with 'cross cutting' concerns like page navigation and general work flow especially in the scenario where you want to dynamically deploy a new service and need to add navigation to that service. There may also be other 'cross cutting' concerns like services that span other of other services.
Thanks,
Declan.

Categories

Resources