ctkServices.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkServices_p.h"
  16. #include <QStringListIterator>
  17. #include <QMutexLocker>
  18. #include <QBuffer>
  19. #include <algorithm>
  20. #include "ctkServiceFactory.h"
  21. #include "ctkPluginConstants.h"
  22. #include "ctkPluginFrameworkContext_p.h"
  23. #include "ctkServiceException.h"
  24. #include "ctkServiceRegistrationPrivate.h"
  25. #include "ctkQtServiceRegistration_p.h"
  26. #include "ctkLDAPExpr_p.h"
  27. using namespace QtMobility;
  28. struct ServiceRegistrationComparator
  29. {
  30. bool operator()(const ctkServiceRegistration* a, const ctkServiceRegistration* b) const
  31. {
  32. return *a < *b;
  33. }
  34. };
  35. ServiceProperties ctkServices::createServiceProperties(const ServiceProperties& in,
  36. const QStringList& classes,
  37. long sid)
  38. {
  39. static qlonglong nextServiceID = 1;
  40. ServiceProperties props;
  41. if (!in.isEmpty())
  42. {
  43. for (ServiceProperties::const_iterator it = in.begin(); it != in.end(); ++it)
  44. {
  45. const QString key = it.key();
  46. const QString lcKey = it.key().toLower();
  47. for (QListIterator<QString> i(props.keys()); i.hasNext(); )
  48. {
  49. if (lcKey == i.next())
  50. {
  51. throw std::invalid_argument(std::string("Several entries for property: ") + key.toStdString());
  52. }
  53. }
  54. props.insert(lcKey, in.value(key));
  55. }
  56. }
  57. if (!classes.isEmpty())
  58. {
  59. props.insert(ctkPluginConstants::OBJECTCLASS, classes);
  60. }
  61. props.insert(ctkPluginConstants::SERVICE_ID, sid != -1 ? sid : nextServiceID++);
  62. return props;
  63. }
  64. ctkServices::ctkServices(ctkPluginFrameworkContext* fwCtx)
  65. : mutex(QMutex::Recursive), framework(fwCtx)
  66. {
  67. }
  68. ctkServices::~ctkServices()
  69. {
  70. clear();
  71. }
  72. void ctkServices::clear()
  73. {
  74. QList<ctkServiceRegistration*> serviceRegs = services.keys();
  75. qDeleteAll(serviceRegs);
  76. services.clear();
  77. classServices.clear();
  78. framework = 0;
  79. }
  80. ctkServiceRegistration* ctkServices::registerService(ctkPluginPrivate* plugin,
  81. const QStringList& classes,
  82. QObject* service,
  83. const ServiceProperties& properties)
  84. {
  85. if (service == 0)
  86. {
  87. throw std::invalid_argument("Can't register 0 as a service");
  88. }
  89. // Check if service implements claimed classes and that they exist.
  90. for (QStringListIterator i(classes); i.hasNext();)
  91. {
  92. QString cls = i.next();
  93. if (cls.isEmpty())
  94. {
  95. throw std::invalid_argument("Can't register as null class");
  96. }
  97. if (!(qobject_cast<ctkServiceFactory*>(service)))
  98. {
  99. if (!checkServiceClass(service, cls))
  100. {
  101. throw std::invalid_argument
  102. (std::string("Service object is not an instance of ") + cls.toStdString());
  103. }
  104. }
  105. }
  106. ctkServiceRegistration* res = new ctkServiceRegistration(plugin, service,
  107. createServiceProperties(properties, classes));
  108. {
  109. QMutexLocker lock(&mutex);
  110. services.insert(res, classes);
  111. for (QStringListIterator i(classes); i.hasNext(); )
  112. {
  113. QString currClass = i.next();
  114. QList<ctkServiceRegistration*>& s = classServices[currClass];
  115. QList<ctkServiceRegistration*>::iterator ip =
  116. std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator());
  117. s.insert(ip, res);
  118. }
  119. }
  120. ctkServiceReference r = res->getReference();
  121. plugin->fwCtx->listeners.serviceChanged(
  122. plugin->fwCtx->listeners.getMatchingServiceSlots(r),
  123. ctkServiceEvent(ctkServiceEvent::REGISTERED, r));
  124. return res;
  125. }
  126. void ctkServices::registerService(ctkPluginPrivate* plugin, QByteArray serviceDescription)
  127. {
  128. QMutexLocker lock(&mutex);
  129. QBuffer serviceBuffer(&serviceDescription);
  130. qServiceManager.addService(&serviceBuffer);
  131. QServiceManager::Error error = qServiceManager.error();
  132. if (!(error == QServiceManager::NoError || error == QServiceManager::ServiceAlreadyExists))
  133. {
  134. throw std::invalid_argument(std::string("Registering the service descriptor for plugin ")
  135. + plugin->symbolicName.toStdString() + " failed: " +
  136. getQServiceManagerErrorString(error).toStdString());
  137. }
  138. QString serviceName = plugin->symbolicName + "_" + plugin->version.toString();
  139. QList<QServiceInterfaceDescriptor> descriptors = qServiceManager.findInterfaces(serviceName);
  140. if (descriptors.isEmpty())
  141. {
  142. qDebug().nospace() << "Warning: No interfaces found for service name " << serviceName
  143. << " in plugin " << plugin->symbolicName << " (ctkVersion " << plugin->version.toString() << ")";
  144. }
  145. QListIterator<QServiceInterfaceDescriptor> it(descriptors);
  146. while (it.hasNext())
  147. {
  148. QServiceInterfaceDescriptor descr = it.next();
  149. qDebug() << "Registering:" << descr.interfaceName();
  150. QStringList classes;
  151. ServiceProperties props;
  152. QStringList customKeys = descr.customAttributes();
  153. QStringListIterator keyIt(customKeys);
  154. bool classAttrFound = false;
  155. while (keyIt.hasNext())
  156. {
  157. QString key = keyIt.next();
  158. if (key == ctkPluginConstants::OBJECTCLASS)
  159. {
  160. classAttrFound = true;
  161. classes << descr.customAttribute(key);
  162. }
  163. else
  164. {
  165. props.insert(key, descr.customAttribute(key));
  166. }
  167. }
  168. if (!classAttrFound)
  169. {
  170. throw std::invalid_argument(std::string("The custom attribute \"") +
  171. ctkPluginConstants::OBJECTCLASS.toStdString() +
  172. "\" is missing in the interface description of \"" +
  173. descr.interfaceName().toStdString());
  174. }
  175. ctkServiceRegistration* res = new ctkQtServiceRegistration(plugin,
  176. descr,
  177. createServiceProperties(props, classes));
  178. services.insert(res, classes);
  179. for (QStringListIterator i(classes); i.hasNext(); )
  180. {
  181. QString currClass = i.next();
  182. QList<ctkServiceRegistration*>& s = classServices[currClass];
  183. QList<ctkServiceRegistration*>::iterator ip =
  184. std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator());
  185. s.insert(ip, res);
  186. }
  187. ctkServiceReference r = res->getReference();
  188. plugin->fwCtx->listeners.serviceChanged(
  189. plugin->fwCtx->listeners.getMatchingServiceSlots(r),
  190. ctkServiceEvent(ctkServiceEvent::REGISTERED, r));
  191. }
  192. }
  193. QString ctkServices::getQServiceManagerErrorString(QServiceManager::Error error)
  194. {
  195. switch (error)
  196. {
  197. case QServiceManager::NoError:
  198. return QString("No error occurred.");
  199. case QServiceManager::StorageAccessError:
  200. return QString("The service data storage is not accessible. This could be because the caller does not have the required permissions.");
  201. case QServiceManager::InvalidServiceLocation:
  202. return QString("The service was not found at its specified location.");
  203. case QServiceManager::InvalidServiceXml:
  204. return QString("The XML defining the service metadata is invalid.");
  205. case QServiceManager::InvalidServiceInterfaceDescriptor:
  206. return QString("The service interface descriptor is invalid, or refers to an interface implementation that cannot be accessed in the current scope.");
  207. case QServiceManager::ServiceAlreadyExists:
  208. return QString("Another service has previously been registered with the same location.");
  209. case QServiceManager::ImplementationAlreadyExists:
  210. return QString("Another service that implements the same interface version has previously been registered.");
  211. case QServiceManager::PluginLoadingFailed:
  212. return QString("The service plugin cannot be loaded.");
  213. case QServiceManager::ComponentNotFound:
  214. return QString("The service or interface implementation has not been registered.");
  215. case QServiceManager::ServiceCapabilityDenied:
  216. return QString("The security session does not allow the service based on its capabilities.");
  217. case QServiceManager::UnknownError:
  218. return QString("An unknown error occurred.");
  219. default:
  220. return QString("Unknown error enum.");
  221. }
  222. }
  223. void ctkServices::updateServiceRegistrationOrder(ctkServiceRegistration* sr,
  224. const QStringList& classes)
  225. {
  226. QMutexLocker lock(&mutex);
  227. for (QStringListIterator i(classes); i.hasNext(); )
  228. {
  229. QList<ctkServiceRegistration*>& s = classServices[i.next()];
  230. s.removeAll(sr);
  231. s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr);
  232. }
  233. }
  234. bool ctkServices::checkServiceClass(QObject* service, const QString& cls) const
  235. {
  236. return service->inherits(cls.toAscii());
  237. }
  238. QList<ctkServiceRegistration*> ctkServices::get(const QString& clazz) const
  239. {
  240. QMutexLocker lock(&mutex);
  241. return classServices.value(clazz);
  242. }
  243. ctkServiceReference ctkServices::get(ctkPluginPrivate* plugin, const QString& clazz) const
  244. {
  245. QMutexLocker lock(&mutex);
  246. try {
  247. QList<ctkServiceReference> srs = get(clazz, QString());
  248. qDebug() << "get service ref" << clazz << "for plugin"
  249. << plugin->location << " = " << srs.size() << "refs";
  250. if (!srs.isEmpty()) {
  251. return srs.front();
  252. }
  253. }
  254. catch (const std::invalid_argument& )
  255. { }
  256. throw ctkServiceException(QString("No service registered for: ") + clazz);
  257. }
  258. QList<ctkServiceReference> ctkServices::get(const QString& clazz, const QString& filter) const
  259. {
  260. QMutexLocker lock(&mutex);
  261. QListIterator<ctkServiceRegistration*>* s = 0;
  262. QList<ctkServiceRegistration*> v;
  263. ctkLDAPExpr ldap;
  264. if (clazz.isEmpty())
  265. {
  266. if (!filter.isEmpty())
  267. {
  268. ldap = ctkLDAPExpr(filter);
  269. QSet<QString> matched = ldap.getMatchedObjectClasses();
  270. if (!matched.isEmpty())
  271. {
  272. v.clear();
  273. foreach (QString className, matched)
  274. {
  275. const QList<ctkServiceRegistration*>& cl = classServices[className];
  276. v += cl;
  277. }
  278. if (!v.isEmpty())
  279. {
  280. s = new QListIterator<ctkServiceRegistration*>(v);
  281. }
  282. else
  283. {
  284. return QList<ctkServiceReference>();
  285. }
  286. }
  287. else
  288. {
  289. s = new QListIterator<ctkServiceRegistration*>(services.keys());
  290. }
  291. }
  292. else
  293. {
  294. s = new QListIterator<ctkServiceRegistration*>(services.keys());
  295. }
  296. }
  297. else
  298. {
  299. QList<ctkServiceRegistration*> v = classServices.value(clazz);
  300. if (!v.isEmpty())
  301. {
  302. s = new QListIterator<ctkServiceRegistration*>(v);
  303. }
  304. else
  305. {
  306. return QList<ctkServiceReference>();
  307. }
  308. if (!filter.isEmpty())
  309. {
  310. ldap = ctkLDAPExpr(filter);
  311. }
  312. }
  313. QList<ctkServiceReference> res;
  314. while (s->hasNext())
  315. {
  316. ctkServiceRegistration* sr = s->next();
  317. ctkServiceReference sri = sr->getReference();
  318. if (filter.isEmpty() || ldap.evaluate(sr->d_func()->properties, false))
  319. {
  320. res.push_back(sri);
  321. }
  322. }
  323. delete s;
  324. return res;
  325. }
  326. void ctkServices::removeServiceRegistration(ctkServiceRegistration* sr)
  327. {
  328. QMutexLocker lock(&mutex);
  329. QStringList classes = sr->d_func()->properties.value(ctkPluginConstants::OBJECTCLASS).toStringList();
  330. services.remove(sr);
  331. for (QStringListIterator i(classes); i.hasNext(); )
  332. {
  333. QString currClass = i.next();
  334. QList<ctkServiceRegistration*>& s = classServices[currClass];
  335. if (s.size() > 1)
  336. {
  337. s.removeAll(sr);
  338. }
  339. else
  340. {
  341. classServices.remove(currClass);
  342. }
  343. }
  344. }
  345. QList<ctkServiceRegistration*> ctkServices::getRegisteredByPlugin(ctkPluginPrivate* p) const
  346. {
  347. QMutexLocker lock(&mutex);
  348. QList<ctkServiceRegistration*> res;
  349. for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); )
  350. {
  351. ctkServiceRegistration* sr = i.next().key();
  352. if ((sr->d_func()->plugin = p))
  353. {
  354. res.push_back(sr);
  355. }
  356. }
  357. return res;
  358. }
  359. QList<ctkServiceRegistration*> ctkServices::getUsedByPlugin(ctkPlugin* p) const
  360. {
  361. QMutexLocker lock(&mutex);
  362. QList<ctkServiceRegistration*> res;
  363. for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); )
  364. {
  365. ctkServiceRegistration* sr = i.next().key();
  366. if (sr->d_func()->isUsedByPlugin(p))
  367. {
  368. res.push_back(sr);
  369. }
  370. }
  371. return res;
  372. }