OSGi + Felix Example3 improvements in authoring and using services

Source: Internet
Author: User

OSGi + Felix Example3 improvements in authoring and using services

In the previous blog post we mentioned how to register a service, but in example2 and example2b no corresponding use of the service, in this article will use the appropriate use of this service, in Felix's official website, The use of the service is to scan the currently registered bundle, and then use the service, but personally feel activator this boot bundle is best only one, and this article set up a complete environment, the deployment of multiple activator bundle is not realistic, Therefore, other methods are used in this paper.

Ideas

In this paper, the implementation of the consideration is to implement the Dictionaryservice interface in the bundle again, and then in the activator in the Start method to register the service, and in the subsequent program for the corresponding service use, Do not scan other bundles for service.

Program

The previous dictionaryservice is no longer displayed, after the modified program is:

 PackageCn.com.example4;ImportCn.com.example2.DictionaryService;Importorg.osgi.framework.*;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;Importjava.util.Hashtable;/** * Created by Administrator on 2016/6/19. * * Public  class Activator implements bundleactivator, servicelistener {    //bundle ' s context    PrivateBundlecontext M_context =NULL;//the service Reference being used.    PrivateServiceReference M_ref =NULL;//the service object being used.    PrivateDictionaryservice m_dictionary =NULL; Public void Start(Bundlecontext context)throwsException {m_context = context; hashtable<string, string> props =NewHashtable<string, string> (); Props.put ("Language","French"); Context.registerservice (DictionaryService.class.getName (),NewDictionaryimpl (), props);synchronized( This) {M_context.addservicelistener ( This,"(& (objectclass=" )+ DictionaryService.class.getName () +")"+"(language=*))");//query for any service references matching any language.servicereference[] refs = m_context.getservicereferences (DictionaryService.class.getName (),"(language=*)");//if we found any dictionary services, then just get            //A reference to the first one so we can use it.            if(Refs! =NULL) {M_ref = refs[0];            M_dictionary = (dictionaryservice) m_context.getservice (M_REF); }        }Try{System.out.println ("Enter a blank line to exit."); String Word =""; BufferedReader in =NewBufferedReader (NewInputStreamReader (system.in));//loop endlessly             while(true) {//ask The user to enter a wordSystem.out.print ("Enter Word:"); Word = In.readline ();//if the user entered a blank line,then                //exit the loop.                if(word.length () = =0) { Break; }Else if(M_dictionary = =NULL) {System.out.println ("No dictionary available"); }Else if(M_dictionary.checkword (Word)) {System.out.println ("Correct."); }Else{System.out.println ("incorrect."); }            }        }Catch(Exception e) {        }    } Public void Stop(Bundlecontext context)throwsException {} Public void servicechanged(Serviceevent event) {string[] ObjectClass = (string[]) event.getservicereference (). GetProperty ("ObjectClass");//If a dictionary service is registered, see if we        //Need one. If So, get a reference to it.        if(Event.gettype () = = serviceevent.registered) {if(M_ref = =NULL)            {//Get a reference to the service object.M_ref = Event.getservicereference ();            M_dictionary = (dictionaryservice) m_context.getservice (M_REF); }        }//If a dictionary service is unregistered, see if it        //was the one we were using. If So, unget the service        //And try to query to get another one.        Else if(Event.gettype () = = serviceevent.unregistering) {if(event.getservicereference () = = M_ref) {//Unget service object and null references.M_context.ungetservice (M_REF); M_ref =NULL; M_dictionary =NULL;//Query to see if we can get another service.Servicereference[] Refs =NULL;Try{refs = M_context.getservicereferences (DictionaryService.class.getName (),"(language=*)"); }Catch(Invalidsyntaxexception ex) {//This'll never happen.}if(Refs! =NULL) {//Get a reference to the first service object.M_ref = refs[0];                M_dictionary = (dictionaryservice) m_context.getservice (M_REF); }            }        }    }Private Static  class Dictionaryimpl implements dictionaryservice {String[] M_dictionary = {"Bienvenue","Au","Tutoriel","OSGi"}; Public Boolean Checkword(String Word) {word = Word.tolowercase (); for(inti =0; i < m_dictionary.length; i++) {if(M_dictionary[i].equals (Word)) {return true; }            }return false; }    }}

In this program,

context.registerService(DictionaryService.class.getName(), new DictionaryImpl(), props);

This code carries out the registration of our service, in the following section of code, we get the service:

ServiceReference[] refs = m_context.getServiceReferences(DictionaryService.class.getName"(Language=*)");m_dictionary = (DictionaryService)m_context.getService(m_ref);

In this way, we can use the relevant services.

Program run

Before the program starts, the first need to pom.xml in the Felix plug-in Bundle-activator startup class, changed to the current class can start normally, and now run the program to observe the results:

You can observe that the service starts normally, enter OSGi, and display the result as:

You can get a response stating that the service is working properly and that both the registration and use of the service are successful.

Summarize
    • In the above services for the corresponding registration and use, the use of OSGi traditional registered services is relatively simple and convenient, but the individual think in the bundle or do not use this method of continuous registration services and use of services, where the interface implementation of the class is best not to put in the bundle inside, separate extraction.

    • In the next section, we will not be explaining these simple examples of Felix's official website, and will begin to explain the blueprint, while the use of these services will be managed using blueprint and no longer using OSGi's registered and declarative services.

    • In subsequent posts, some of the in-depth concepts of OSGi and the use of some middleware will begin.

OSGi + Felix Example3 improvements in authoring and using services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.