ctkServices.cpp 14 KB

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