void GenerateData_3DImage_CompareToReference() { int upperThr = 255; int lowerThr = 60; int outsideVal = 0; int insideVal = 100; us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); resources->GetContext(); //todo why do i need to call this before GetMaximumImageSize()? if(resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0) { //GPU device does not support 3D images. Skip this test. MITK_INFO << "Skipping test."; return; } try{ m_oclBinaryFilter->SetInput( m_Random3DImage ); m_oclBinaryFilter->SetUpperThreshold( upperThr ); m_oclBinaryFilter->SetLowerThreshold( lowerThr ); m_oclBinaryFilter->SetOutsideValue( outsideVal ); m_oclBinaryFilter->SetInsideValue( insideVal ); m_oclBinaryFilter->Update(); mitk::Image::Pointer outputImage = mitk::Image::New(); outputImage = m_oclBinaryFilter->GetOutput(); // reference computation //This is not optimal here, but since we use a random image //we cannot know the reference image at this point. typedef itk::Image< unsigned char, 3> ImageType; typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType; ImageType::Pointer itkInputImage = ImageType::New(); CastToItkImage( m_Random3DImage, itkInputImage ); ThresholdFilterType::Pointer refThrFilter = ThresholdFilterType::New(); refThrFilter->SetInput( itkInputImage ); refThrFilter->SetLowerThreshold( lowerThr ); refThrFilter->SetUpperThreshold( upperThr ); refThrFilter->SetOutsideValue( outsideVal ); refThrFilter->SetInsideValue( insideVal ); refThrFilter->Update(); mitk::Image::Pointer referenceImage = mitk::Image::New(); mitk::CastToMitkImage(refThrFilter->GetOutput(), referenceImage); MITK_ASSERT_EQUAL( referenceImage, outputImage, "OclBinaryThresholdFilter should be equal to regular itkBinaryThresholdImageFilter."); } catch(mitk::Exception &e) { std::string errorMessage = "Caught unexpected exception "; errorMessage.append(e.what()); CPPUNIT_FAIL(errorMessage.c_str()); } }
int main(int /*argc*/, char* /*argv*/[]) { { //! [tracker] MyTrackingCustomizer myCustomizer; ServiceTracker<IFooService, MyTrackedClassTraits> tracker(GetModuleContext(), &myCustomizer); //! [tracker] } { //! [tracker2] MyTrackingPointerCustomizer myCustomizer; ServiceTracker<IFooService, TrackedTypeTraits<IFooService,MyTrackedClass*> > tracker(GetModuleContext(), &myCustomizer); //! [tracker2] } // For compilation test purposes only MyTrackingCustomizerVoid myCustomizer2; try { ServiceTracker<void, MyTrackedClassTraits> tracker2(GetModuleContext(), &myCustomizer2); ServiceTracker<void, TrackedTypeTraits<void,MyTrackedClass*> > tracker3(GetModuleContext()); } catch (const us::ServiceException&) {} return 0; }
cl_mem mitk::OclDataSet::CreateGPUBuffer() { MITK_DEBUG << "InitializeGPUBuffer call with: BPE=" << m_BpE; us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); m_context = resources->GetContext(); int clErr; if (m_gpuBuffer) clReleaseMemObject(m_gpuBuffer); m_gpuBuffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE, m_bufferSize * (size_t)m_BpE, nullptr, &clErr); #ifdef SHOW_MEM_INFO MITK_INFO << "Created GPU Buffer Object of size: " << (size_t)m_BpE * m_bufferSize << " Bytes"; #endif CHECK_OCL_ERR(clErr); if (clErr != CL_SUCCESS) mitkThrow() << "openCL Error when creating Buffer"; return m_gpuBuffer; }
US_USE_NAMESPACE int main(int /*argc*/, char* /*argv*/[]) { ServiceReference<IDictionaryService> dictionaryServiceRef = GetModuleContext()->GetServiceReference<IDictionaryService>(); if (dictionaryServiceRef) { IDictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); if (dictionaryService) { std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->CheckWord("Tutorial") << std::endl; } } }
SingletonTwoService* SingletonTwoService::GetInstance() { static ServiceReference serviceRef; static ModuleContext* context = GetModuleContext(); if (!serviceRef) { // This is either the first time GetInstance() was called, // or a SingletonTwoService instance has not yet been registered. serviceRef = context->GetServiceReference<SingletonTwoService>(); } if (serviceRef) { // We have a valid service reference. It always points to the service // with the lowest id (usually the one which was registered first). // This still might return a null pointer, if all SingletonTwoService // instances have been unregistered (during unloading of the library, // for example). return context->GetService<SingletonTwoService>(serviceRef); } else { // No SingletonTwoService instance was registered yet. return 0; } }
void TestMultipleServiceRegistrations() { struct TestServiceA : public ITestServiceA { }; ModuleContext* context = GetModuleContext(); TestServiceA s1; TestServiceA s2; ServiceRegistration<ITestServiceA> reg1 = context->RegisterService<ITestServiceA>(&s1); ServiceRegistration<ITestServiceA> reg2 = context->RegisterService<ITestServiceA>(&s2); std::vector<ServiceReference<ITestServiceA> > refs = context->GetServiceReferences<ITestServiceA>(); US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services") reg2.Unregister(); refs = context->GetServiceReferences<ITestServiceA>(); US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services") reg1.Unregister(); refs = context->GetServiceReferences<ITestServiceA>(); US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services") ServiceReference<ITestServiceA> ref = context->GetServiceReference<ITestServiceA>(); US_TEST_CONDITION_REQUIRED(!ref, "Testing for invalid service reference") }
void ModuleHooks::FilterModules(const ModuleContext* mc, std::vector<Module*>& modules) const { std::vector<ServiceRegistrationBase> srl; coreCtx->services.Get(us_service_interface_iid<ModuleFindHook>(), srl); ShrinkableVector<Module*> filtered(modules); std::sort(srl.begin(), srl.end()); for (std::vector<ServiceRegistrationBase>::reverse_iterator srBaseIter = srl.rbegin(), srBaseEnd = srl.rend(); srBaseIter != srBaseEnd; ++srBaseIter) { ServiceReference<ModuleFindHook> sr = srBaseIter->GetReference(); ModuleFindHook* const fh = reinterpret_cast<ModuleFindHook*>(sr.d->GetService(GetModuleContext()->GetModule())); if (fh != nullptr) { try { fh->Find(mc, filtered); } catch (const std::exception& e) { US_WARN << "Failed to call Module FindHook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": " << e.what(); } catch (...) { US_WARN << "Failed to call Module FindHook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": unknown exception type"; } } } }
US_USE_NAMESPACE void resourceExample() { //! [1] // Get this module's Module object Module* module = GetModuleContext()->GetModule(); ModuleResource resource = module->GetResource("config.properties"); if (resource.IsValid()) { // Create a ModuleResourceStream object ModuleResourceStream resourceStream(resource); // Read the contents line by line std::string line; while (std::getline(resourceStream, line)) { // Process the content std::cout << line << std::endl; } } else { // Error handling } //! [1] }
void ModuleRegistry::UnRegister(const ModuleInfo* info) { // If we are unregistering the core module, we just call // the module activators Unload() method (if there is a // module activator). Since we cannot be sure that the // ModuleContext for the core library is still valid, we // just pass a null-pointer. Using the module context during // static deinitalization time of the core library makes // no sense anyway. if (info->id == 1) { // Remove listeners from static modules if they have forgotten to do so coreModuleContext()->listeners.RemoveAllListeners(GetModuleContext()); if (info->activatorHook) { info->activatorHook()->Unload(0); } return; } Module* curr = 0; { MutexLock lock(*modulesLock()); curr = modules()->operator[](info->id); assert(curr != 0); } curr->Stop(); }
void mitk::OclBinaryThresholdImageFilter::Update() { //Check if context & program available if (!this->Initialize()) { us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>(); OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref); // clean-up also the resources resources->InvalidateStorage(); mitkThrow() <<"Filter is not initialized. Cannot update."; } else{ // Execute this->Execute(); } }
US_USE_NAMESPACE void RetrieveModuleContext() { ModuleContext* context = GetModuleContext(); Module* module = context->GetModule(); std::cout << "Module name: " << module->GetName() << " [id: " << module->GetModuleId() << "]\n"; }
US_END_NAMESPACE void TestServiceFactoryModuleScope() { // Install and start test module H, a service factory and test that the methods // in that interface works. SharedLibrary target(LIB_PATH, "TestModuleH"); #ifdef US_BUILD_SHARED_LIBS try { target.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) } #endif Module* moduleH = ModuleRegistry::GetModule("TestModuleH"); US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") std::vector<ServiceReferenceU> registeredRefs = moduleH->GetRegisteredServices(); US_TEST_CONDITION_REQUIRED(registeredRefs.size() == 2, "# of registered services") US_TEST_CONDITION(registeredRefs[0].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") US_TEST_CONDITION(registeredRefs[1].GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") ModuleContext* mc = GetModuleContext(); // Check that a service reference exist const ServiceReferenceU sr1 = mc->GetServiceReference("us::TestModuleH"); US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_MODULE(), "service scope") InterfaceMap service = mc->GetService(sr1); US_TEST_CONDITION_REQUIRED(service.size() >= 1, "GetService()") InterfaceMap::const_iterator serviceIter = service.find("us::TestModuleH"); US_TEST_CONDITION_REQUIRED(serviceIter != service.end(), "GetService()") US_TEST_CONDITION_REQUIRED(serviceIter->second != nullptr, "GetService()") InterfaceMap service2 = mc->GetService(sr1); US_TEST_CONDITION(service == service2, "Same service pointer") std::vector<ServiceReferenceU> usedRefs = mc->GetModule()->GetServicesInUse(); US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") InterfaceMap service3 = moduleH->GetModuleContext()->GetService(sr1); US_TEST_CONDITION(service != service3, "Different service pointer") US_TEST_CONDITION(moduleH->GetModuleContext()->UngetService(sr1), "UngetService()") US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1) == false, "ungetService()") US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1) == true, "ungetService()") target.Unload(); }
void ServiceHooks::Open() { US_UNUSED(Lock(this)); listenerHookTracker = new ServiceTracker<ServiceListenerHook>(GetModuleContext(), this); listenerHookTracker->Open(); bOpen = true; }
void TestServicePropertiesUpdate() { struct TestServiceA : public ITestServiceA { }; ModuleContext* context = GetModuleContext(); TestServiceA s1; ServiceProperties props; props["string"] = std::string("A std::string"); props["bool"] = false; const char* str = "A const char*"; props["const char*"] = str; ServiceRegistration<ITestServiceA> reg1 = context->RegisterService<ITestServiceA>(&s1, props); ServiceReference<ITestServiceA> ref1 = context->GetServiceReference<ITestServiceA>(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().size() == 1, "Testing service count") US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == false, "Testing bool property") // register second service with higher rank TestServiceA s2; ServiceProperties props2; props2[ServiceConstants::SERVICE_RANKING()] = 50; ServiceRegistration<ITestServiceA> reg2 = context->RegisterService<ITestServiceA>(&s2, props2); // Get the service with the highest rank, this should be s2. ServiceReference<ITestServiceA> ref2 = context->GetServiceReference<ITestServiceA>(); TestServiceA* service = dynamic_cast<TestServiceA*>(context->GetService(ref2)); US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") props["bool"] = true; // change the service ranking props[ServiceConstants::SERVICE_RANKING()] = 100; reg1.SetProperties(props); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().size() == 2, "Testing service count") US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == true, "Testing bool property") US_TEST_CONDITION_REQUIRED(any_cast<int>(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking") // Service with the highest ranking should now be s1 service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref1)); US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank") reg1.Unregister(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>("").size() == 1, "Testing service count") service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref2)); US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") reg2.Unregister(); US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().empty(), "Testing service count") }
void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){ if ( sourceID.empty() ) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice()."; // Get Context mitk::ModuleContext* context = GetModuleContext(); // Define ServiceProps ServiceProperties props; props[ US_PROPKEY_SOURCE_ID ] = sourceID; m_ServiceRegistration = context->RegisterService<mitk::NavigationToolStorage>(this, props); }
int usModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleResourceTest"); ModuleContext* mc = GetModuleContext(); assert(mc); #ifdef US_BUILD_SHARED_LIBS SharedLibrary libR(LIB_PATH, "TestModuleR"); try { libR.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } #endif Module* moduleR = ModuleRegistry::GetModule("TestModuleR"); US_TEST_CONDITION_REQUIRED(moduleR != nullptr, "Test for existing module TestModuleR") US_TEST_CONDITION(moduleR->GetName() == "TestModuleR", "Test module name") testInvalidResource(moduleR); testResourceFromExecutable(mc->GetModule()); testResourceTree(moduleR); testResourceOperators(moduleR); testTextResource(moduleR); testTextResourceAsBinary(moduleR); testSpecialCharacters(moduleR); testBinaryResource(moduleR); testCompressedResource(moduleR); ModuleResource foo = moduleR->GetResource("foo.txt"); US_TEST_CONDITION(foo.IsValid() == true, "Valid resource") #ifdef US_BUILD_SHARED_LIBS libR.Unload(); US_TEST_CONDITION(foo.IsValid() == true, "Still valid resource") #endif testResourcesFrom("TestModuleRL"); testResourcesFrom("TestModuleRA"); US_TEST_END() }
int IOUtil::LoadFiles(const std::vector<std::string> &fileNames, DataStorage &ds) { // Get the set of registered mitk::IDataNodeReader services ModuleContext* context = GetModuleContext(); const std::list<ServiceReference> refs = context->GetServiceReferences<IDataNodeReader>(); std::vector<IDataNodeReader*> services; services.reserve(refs.size()); for (std::list<ServiceReference>::const_iterator i = refs.begin(); i != refs.end(); ++i) { IDataNodeReader* s = context->GetService<IDataNodeReader>(*i); if (s != 0) { services.push_back(s); } } mitk::ProgressBar::GetInstance()->AddStepsToDo(2*fileNames.size()); // Iterate over all file names and use the IDataNodeReader services // to load them. int nodesRead = 0; for (std::vector<std::string>::const_iterator i = fileNames.begin(); i != fileNames.end(); ++i) { for (std::vector<IDataNodeReader*>::const_iterator readerIt = services.begin(); readerIt != services.end(); ++readerIt) { try { int n = (*readerIt)->Read(*i, ds); nodesRead += n; if (n > 0) break; } catch (const std::exception& e) { MITK_WARN << e.what(); } } mitk::ProgressBar::GetInstance()->Progress(2); } for (std::list<ServiceReference>::const_iterator i = refs.begin(); i != refs.end(); ++i) { context->UngetService(*i); } return nodesRead; }
int main(int /*argc*/, char* /*argv*/[]) { //! [0] ModuleContext* moduleContext = GetModuleContext(); Module* module = moduleContext->GetModule(); // List all XML files in the config directory std::vector<ModuleResource> xmlFiles = module->FindResources("config", "*.xml", false); // Find the resource named vertex_shader.txt starting at the root directory std::vector<ModuleResource> shaders = module->FindResources("", "vertex_shader.txt", true); //! [0] return 0; }
int usStaticModuleTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("StaticModuleTest"); ModuleContext* mc = GetModuleContext(); TestModuleListener listener; ModuleListenerRegistrationHelper<TestModuleListener> ml(mc, &listener, &TestModuleListener::ModuleChanged); ServiceListenerRegistrationHelper<TestModuleListener> sl(mc, &listener, &TestModuleListener::ServiceChanged); SharedLibrary libB(LIB_PATH, "TestModuleB"); frame020a(mc, listener, libB); frame030b(mc, listener, libB); US_TEST_END() }
int usModuleTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ModuleTest"); frame02a(); ModuleContext* mc = GetModuleContext(); TestModuleListener listener; try { mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); throw; } try { mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); } catch (const std::logic_error& ise) { US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); throw; } frame005a(mc); frame010a(mc); frame018a(mc); SharedLibrary libA(LIB_PATH, "TestModuleA"); frame020a(mc, listener, libA); frame030b(mc, listener, libA); frame045a(mc); mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); US_TEST_END() }
ServiceHooks::TrackedType ServiceHooks::AddingService(const ServiceReferenceType& reference) { ServiceListenerHook* lh = GetModuleContext()->GetService(reference); try { lh->Added(coreCtx->listeners.GetListenerInfoCollection()); } catch (const std::exception& e) { US_WARN << "Failed to call listener hook #" << reference.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": " << e.what(); } catch (...) { US_WARN << "Failed to call listener hook #" << reference.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": unknown exception type"; } return lh; }
bool mitk::USDevice::Connect() { if (GetIsConnected()) { MITK_WARN << "Tried to connect an ultrasound device that was already connected. Ignoring call..."; return false; } // Prepare connection, fail if this fails. if (! this->OnConnection()) return false; // Get Context and Module mitk::ModuleContext* context = GetModuleContext(); ServiceProperties props = ConstructServiceProperties(); m_ServiceRegistration = context->RegisterService<mitk::USDevice>(this, props); // This makes sure that the SmartPointer to this device does not invalidate while the device is connected this->Register(); return true; }
mitk::Dispatcher::Dispatcher() : m_ProcessingMode(REGULAR) { m_EventObserverTracker = new mitk::ServiceTracker<InteractionEventObserver*>(GetModuleContext()); m_EventObserverTracker->Open(); }
US_USE_NAMESPACE int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceTrackerTest") ModuleContext* mc = GetModuleContext(); SharedLibraryHandle libS("TestModuleS"); // Start the test target to get a service published. try { libS.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); } // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null std::string s1("org.cppmicroservices.TestModuleSService"); ServiceReference servref = mc->GetServiceReference(s1 + "0"); US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); ServiceControlInterface* serviceController = mc->GetService<ServiceControlInterface>(servref); US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); std::auto_ptr<ServiceTracker<> > st1(new ServiceTracker<>(mc, servref)); // 2. Check the size method with an unopened service tracker US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); // 3. Open the service tracker and see what it finds, // expect to find one instance of the implementation, // "org.cppmicroservices.TestModuleSService0" st1->Open(); std::string expName = "TestModuleS"; std::list<ServiceReference> sa2; st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); std::string name(us_service_impl_name(mc->GetService(sa2.front()))); US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name"); // 5. Close this service tracker st1->Close(); // 6. Check the size method, now when the servicetracker is closed US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); // 7. Check if we still track anything , we should get null sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); // 8. A new Servicetracker, this time with a filter for the object std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; LDAPFilter f1(fs); st1.reset(new ServiceTracker<>(mc, f1)); // add a service serviceController->ServiceControl(1, "register", 7); // 9. Open the service tracker and see what it finds, // expect to find two instances of references to // "org.cppmicroservices.TestModuleSService*" // i.e. they refer to the same piece of code st1->Open(); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 10. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(2, "register", 1); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 11. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(3, "register", 2); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 12. Get libTestModuleS to unregister one service and see if it disappears serviceController->ServiceControl(3, "unregister", 0); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 13. Get the highest ranking service reference, it should have ranking 7 ServiceReference h1 = st1->GetServiceReference(); int rank = any_cast<int>(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); // 14. Get the service of the highest ranked service reference US_BASECLASS_NAME* o1 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service"); // 14a Get the highest ranked service, directly this time US_BASECLASS_NAME* o3 = st1->GetService(); US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service"); US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); // 15. Now release the tracking of that service and then try to get it // from the servicetracker, which should yield a null object serviceController->ServiceControl(1, "unregister", 7); US_BASECLASS_NAME* o2 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null"); // 16. Get all service objects this tracker tracks, it should be 2 std::list<US_BASECLASS_NAME*> ts1; st1->GetServices(ts1); US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); // 17. Test the remove method. // First register another service, then remove it being tracked serviceController->ServiceControl(1, "register", 7); h1 = st1->GetServiceReference(); std::list<ServiceReference> sa3; st1->GetServiceReferences(sa3); US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); for (std::list<ServiceReference>::const_iterator i = sa3.begin(); i != sa3.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name"); } st1->Remove(h1); // remove tracking on one servref sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); // 18. Test the addingService method,add a service reference // 19. Test the removedService method, remove a service reference // 20. Test the waitForService method US_BASECLASS_NAME* o9 = st1->WaitForService(50); US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method"); US_TEST_END() }
void ModuleHooks::FilterModuleEventReceivers(const ModuleEvent& evt, ServiceListeners::ModuleListenerMap& moduleListeners) { std::vector<ServiceRegistrationBase> eventHooks; coreCtx->services.Get(us_service_interface_iid<ModuleEventHook>(), eventHooks); { MutexLock lock(coreCtx->listeners.moduleListenerMapMutex); moduleListeners = coreCtx->listeners.moduleListenerMap; } if(!eventHooks.empty()) { std::vector<ModuleContext*> moduleContexts; for (ServiceListeners::ModuleListenerMap::iterator le = moduleListeners.begin(), leEnd = moduleListeners.end(); le != leEnd; ++le) { moduleContexts.push_back(le->first); } std::sort(moduleContexts.begin(), moduleContexts.end()); moduleContexts.erase(std::unique(moduleContexts.begin(), moduleContexts.end()), moduleContexts.end()); const std::size_t unfilteredSize = moduleContexts.size(); ShrinkableVector<ModuleContext*> filtered(moduleContexts); std::sort(eventHooks.begin(), eventHooks.end()); for (std::vector<ServiceRegistrationBase>::reverse_iterator iter = eventHooks.rbegin(), iterEnd = eventHooks.rend(); iter != iterEnd; ++iter) { ServiceReference<ModuleEventHook> sr; try { sr = iter->GetReference(); } catch (const std::logic_error& e) { US_WARN << "Failed to get event hook service reference: " << e.what(); continue; } ModuleEventHook* eh = reinterpret_cast<ModuleEventHook*>(sr.d->GetService(GetModuleContext()->GetModule())); if (eh != nullptr) { try { eh->Event(evt, filtered); } catch (const std::exception& e) { US_WARN << "Failed to call Module EventHook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": " << e.what(); } catch (...) { US_WARN << "Failed to call Module EventHook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": unknown exception type"; } } } if (unfilteredSize != moduleContexts.size()) { for (ServiceListeners::ModuleListenerMap::iterator le = moduleListeners.begin(); le != moduleListeners.end();) { if(std::find(moduleContexts.begin(), moduleContexts.end(), le->first) == moduleContexts.end()) { moduleListeners.erase(le++); } else { ++le; } } } } }
void ServiceHooks::FilterServiceReferences(ModuleContext* mc, const std::string& service, const std::string& filter, std::vector<ServiceReferenceBase>& refs) { std::vector<ServiceRegistrationBase> srl; coreCtx->services.Get_unlocked(us_service_interface_iid<ServiceFindHook>(), srl); if (!srl.empty()) { ShrinkableVector<ServiceReferenceBase> filtered(refs); std::sort(srl.begin(), srl.end()); for (std::vector<ServiceRegistrationBase>::reverse_iterator fhrIter = srl.rbegin(), fhrEnd = srl.rend(); fhrIter != fhrEnd; ++fhrIter) { ServiceReference<ServiceFindHook> sr = fhrIter->GetReference(); ServiceFindHook* const fh = reinterpret_cast<ServiceFindHook*>(sr.d->GetService(GetModuleContext()->GetModule())); if (fh != NULL) { try { fh->Find(mc, service, filter, filtered); } catch (const std::exception& e) { US_WARN << "Failed to call find hook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": " << e.what(); } catch (...) { US_WARN << "Failed to call find hook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": unknown exception type"; } } } } }
void TestServiceFactoryPrototypeScope() { // Install and start test module H, a service factory and test that the methods // in that interface works. SharedLibrary target(LIB_PATH, "TestModuleH"); #ifdef US_BUILD_SHARED_LIBS try { target.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what()) } Module* moduleH = ModuleRegistry::GetModule("TestModuleH"); US_TEST_CONDITION_REQUIRED(moduleH != 0, "Test for existing module TestModuleH") #endif ModuleContext* mc = GetModuleContext(); // Check that a service reference exist const ServiceReference<TestModuleH2> sr1 = mc->GetServiceReference<TestModuleH2>(); US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.") US_TEST_CONDITION(sr1.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") ServiceObjects<TestModuleH2> svcObjects = mc->GetServiceObjects(sr1); TestModuleH2* prototypeServiceH2 = svcObjects.GetService(); const ServiceReferenceU sr1void = mc->GetServiceReference(us_service_interface_iid<TestModuleH2>()); ServiceObjects<void> svcObjectsVoid = mc->GetServiceObjects(sr1void); InterfaceMap prototypeServiceH2Void = svcObjectsVoid.GetService(); US_TEST_CONDITION_REQUIRED(prototypeServiceH2Void.find(us_service_interface_iid<TestModuleH2>()) != prototypeServiceH2Void.end(), "ServiceObjects<void>::GetService()") #ifdef US_BUILD_SHARED_LIBS // There should be only one service in use US_TEST_CONDITION_REQUIRED(mc->GetModule()->GetServicesInUse().size() == 1, "services in use") #endif TestModuleH2* moduleScopeService = mc->GetService(sr1); US_TEST_CONDITION_REQUIRED(moduleScopeService && moduleScopeService != prototypeServiceH2, "GetService()") US_TEST_CONDITION_REQUIRED(prototypeServiceH2 != prototypeServiceH2Void.find(us_service_interface_iid<TestModuleH2>())->second, "GetService()") svcObjectsVoid.UngetService(prototypeServiceH2Void); TestModuleH2* moduleScopeService2 = mc->GetService(sr1); US_TEST_CONDITION(moduleScopeService == moduleScopeService2, "Same service pointer") #ifdef US_BUILD_SHARED_LIBS std::vector<ServiceReferenceU> usedRefs = mc->GetModule()->GetServicesInUse(); US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use") #endif std::string filter = "(" + ServiceConstants::SERVICE_ID() + "=" + sr1.GetProperty(ServiceConstants::SERVICE_ID()).ToString() + ")"; const ServiceReference<TestModuleH> sr2 = mc->GetServiceReferences<TestModuleH>(filter).front(); US_TEST_CONDITION_REQUIRED(sr2, "Service shall be present.") US_TEST_CONDITION(sr2.GetProperty(ServiceConstants::SERVICE_SCOPE()).ToString() == ServiceConstants::SCOPE_PROTOTYPE(), "service scope") US_TEST_CONDITION(any_cast<long>(sr2.GetProperty(ServiceConstants::SERVICE_ID())) == any_cast<long>(sr1.GetProperty(ServiceConstants::SERVICE_ID())), "same service id") try { svcObjects.UngetService(moduleScopeService2); US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") } catch (const std::invalid_argument&) { // this is expected } #ifdef US_BUILD_SHARED_LIBS // There should still be only one service in use usedRefs = mc->GetModule()->GetServicesInUse(); US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use") #endif ServiceObjects<TestModuleH2> svcObjects2 = svcObjects; ServiceObjects<TestModuleH2> svcObjects3 = mc->GetServiceObjects(sr1); try { svcObjects3.UngetService(prototypeServiceH2); US_TEST_FAILED_MSG(<< "std::invalid_argument exception expected") } catch (const std::invalid_argument&) { // this is expected } svcObjects2.UngetService(prototypeServiceH2); prototypeServiceH2 = svcObjects2.GetService(); TestModuleH2* prototypeServiceH2_2 = svcObjects3.GetService(); US_TEST_CONDITION_REQUIRED(prototypeServiceH2_2 && prototypeServiceH2_2 != prototypeServiceH2, "prototype service") svcObjects2.UngetService(prototypeServiceH2); svcObjects3.UngetService(prototypeServiceH2_2); US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1) == false, "ungetService()") US_TEST_CONDITION_REQUIRED(mc->UngetService(sr1) == true, "ungetService()") target.Unload(); }
void ServiceHooks::FilterServiceEventReceivers(const ServiceEvent& evt, ServiceListeners::ServiceListenerEntries& receivers) { std::vector<ServiceRegistrationBase> eventListenerHooks; coreCtx->services.Get_unlocked(us_service_interface_iid<ServiceEventListenerHook>(), eventListenerHooks); if (!eventListenerHooks.empty()) { std::sort(eventListenerHooks.begin(), eventListenerHooks.end()); std::map<ModuleContext*, std::vector<ServiceListenerHook::ListenerInfo> > listeners; for (ServiceListeners::ServiceListenerEntries::iterator sleIter = receivers.begin(), sleEnd = receivers.end(); sleIter != sleEnd; ++sleIter) { listeners[sleIter->GetModuleContext()].push_back(*sleIter); } std::map<ModuleContext*, ShrinkableVector<ServiceListenerHook::ListenerInfo> > shrinkableListeners; for (std::map<ModuleContext*, std::vector<ServiceListenerHook::ListenerInfo> >::iterator iter = listeners.begin(), iterEnd = listeners.end(); iter != iterEnd; ++iter) { shrinkableListeners.insert(std::make_pair(iter->first, ShrinkableVector<ServiceListenerHook::ListenerInfo>(iter->second))); } ShrinkableMap<ModuleContext*, ShrinkableVector<ServiceListenerHook::ListenerInfo> > filtered(shrinkableListeners); for(std::vector<ServiceRegistrationBase>::reverse_iterator sriIter = eventListenerHooks.rbegin(), sriEnd = eventListenerHooks.rend(); sriIter != sriEnd; ++sriIter) { ServiceReference<ServiceEventListenerHook> sr = sriIter->GetReference(); ServiceEventListenerHook* elh = reinterpret_cast<ServiceEventListenerHook*>(sr.d->GetService(GetModuleContext()->GetModule())); if(elh != NULL) { try { elh->Event(evt, filtered); } catch(const std::exception& e) { US_WARN << "Failed to call event hook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": " << e.what(); } catch(...) { US_WARN << "Failed to call event hook #" << sr.GetProperty(ServiceConstants::SERVICE_ID()).ToString() << ": unknown exception type"; } } } receivers.clear(); for(std::map<ModuleContext*, std::vector<ServiceListenerHook::ListenerInfo> >::iterator iter = listeners.begin(), iterEnd = listeners.end(); iter != iterEnd; ++iter) { receivers.insert(iter->second.begin(), iter->second.end()); } } }
void ServiceHooks::RemovedService(const ServiceReferenceType& reference, TrackedType /*service*/) { GetModuleContext()->UngetService(reference); }