QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgssensorthingsshareddata.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgssensorthingsshareddata.h
3 ----------------
4 begin : November 2023
5 copyright : (C) 2013 Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include <nlohmann/json.hpp>
19
21#include "qgsjsonutils.h"
22#include "qgslogger.h"
24#include "qgsreadwritelocker.h"
28
29#include <QCryptographicHash>
30#include <QFile>
31#include <QString>
32
33using namespace Qt::StringLiterals;
34
36
37QgsSensorThingsSharedData::QgsSensorThingsSharedData( const QString &uri )
38{
39 const QVariantMap uriParts = QgsSensorThingsProviderMetadata().decodeUri( uri );
40
41 mEntityType = qgsEnumKeyToValue( uriParts.value( u"entity"_s ).toString(), Qgis::SensorThingsEntity::Invalid );
42 const QVariantList expandTo = uriParts.value( u"expandTo"_s ).toList();
43 QList< Qgis::SensorThingsEntity > expandedEntities;
44 for ( const QVariant &expansionVariant : expandTo )
45 {
46 const QgsSensorThingsExpansionDefinition expansion = expansionVariant.value< QgsSensorThingsExpansionDefinition >();
47 if ( expansion.isValid() )
48 {
49 mExpansions.append( expansion );
50 expandedEntities.append( expansion.childEntity() );
51 }
52
53 mExpandQueryString = QgsSensorThingsUtils::asQueryString( mEntityType, mExpansions );
54 }
55
56 mFields = QgsSensorThingsUtils::fieldsForExpandedEntityType( mEntityType, expandedEntities );
57
58 mGeometryField = QgsSensorThingsUtils::geometryFieldForEntityType( mEntityType );
59 // use initial value of maximum page size as default
60 mMaximumPageSize = uriParts.value( u"pageSize"_s, mMaximumPageSize ).toInt();
61 // will default to 0 if not specified, i.e. no limit
62 mFeatureLimit = uriParts.value( u"featureLimit"_s ).toInt();
63 mFilterExtent = uriParts.value( u"bounds"_s ).value< QgsRectangle >();
64 mSubsetString = uriParts.value( u"sql"_s ).toString();
65
67 {
68 if ( uriParts.contains( u"geometryType"_s ) )
69 {
70 const QString geometryType = uriParts.value( u"geometryType"_s ).toString();
71 if ( geometryType.compare( "point"_L1, Qt::CaseInsensitive ) == 0 )
72 {
73 mGeometryType = Qgis::WkbType::PointZ;
74 }
75 else if ( geometryType.compare( "multipoint"_L1, Qt::CaseInsensitive ) == 0 )
76 {
77 mGeometryType = Qgis::WkbType::MultiPointZ;
78 }
79 else if ( geometryType.compare( "line"_L1, Qt::CaseInsensitive ) == 0 )
80 {
81 mGeometryType = Qgis::WkbType::MultiLineStringZ;
82 }
83 else if ( geometryType.compare( "polygon"_L1, Qt::CaseInsensitive ) == 0 )
84 {
85 mGeometryType = Qgis::WkbType::MultiPolygonZ;
86 }
87
88 if ( mGeometryType != Qgis::WkbType::NoGeometry )
89 {
90 // geometry is always GeoJSON spec (for now, at least), so CRS will always be WGS84
91 mSourceCRS = QgsCoordinateReferenceSystem( u"EPSG:4326"_s );
92 }
93 }
94 else
95 {
96 mGeometryType = Qgis::WkbType::NoGeometry;
97 }
98 }
99 else
100 {
101 mGeometryType = Qgis::WkbType::NoGeometry;
102 }
103
104 const QgsDataSourceUri dsUri( uri );
105 mAuthCfg = dsUri.authConfigId();
106 mHeaders = dsUri.httpHeaders();
107
108 mRootUri = uriParts.value( u"url"_s ).toString();
109}
110
111QUrl QgsSensorThingsSharedData::parseUrl( const QUrl &url, bool *isTestEndpoint )
112{
113 if ( isTestEndpoint )
114 *isTestEndpoint = false;
115
116 QUrl modifiedUrl( url );
117 if ( modifiedUrl.toString().contains( "fake_qgis_http_endpoint"_L1 ) )
118 {
119 if ( isTestEndpoint )
120 *isTestEndpoint = true;
121
122 // Just for testing with local files instead of http:// resources
123 QString modifiedUrlString = modifiedUrl.toString();
124 // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
125 modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
126 modifiedUrlString.replace( "fake_qgis_http_endpoint/"_L1, "fake_qgis_http_endpoint_"_L1 );
127 QgsDebugMsgLevel( u"Get %1"_s.arg( modifiedUrlString ), 2 );
128 modifiedUrlString = modifiedUrlString.mid( u"http://"_s.size() );
129 QString args = modifiedUrlString.indexOf( '?' ) >= 0 ? modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) ) : QString();
130 if ( modifiedUrlString.size() > 150 )
131 {
132 args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
133 }
134 else
135 {
136 args.replace( "?"_L1, "_"_L1 );
137 args.replace( "&"_L1, "_"_L1 );
138 args.replace( "$"_L1, "_"_L1 );
139 args.replace( "<"_L1, "_"_L1 );
140 args.replace( ">"_L1, "_"_L1 );
141 args.replace( "'"_L1, "_"_L1 );
142 args.replace( "\""_L1, "_"_L1 );
143 args.replace( " "_L1, "_"_L1 );
144 args.replace( ":"_L1, "_"_L1 );
145 args.replace( "/"_L1, "_"_L1 );
146 args.replace( "\n"_L1, "_"_L1 );
147 }
148#ifdef Q_OS_WIN
149 // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
150 // so we must restore it
151 if ( modifiedUrlString[1] == '/' )
152 {
153 modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
154 }
155#endif
156 modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
157 QgsDebugMsgLevel( u"Get %1 (after laundering)"_s.arg( modifiedUrlString ), 2 );
158 modifiedUrl = QUrl::fromLocalFile( modifiedUrlString );
159 if ( !QFile::exists( modifiedUrlString ) )
160 {
161 QgsDebugError( u"Local test file %1 for URL %2 does not exist!!!"_s.arg( modifiedUrlString, url.toString() ) );
162 }
163 }
164
165 return modifiedUrl;
166}
167
168QgsRectangle QgsSensorThingsSharedData::extent() const
169{
170 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
171
172 // Since we can't retrieve the actual layer extent via SensorThings API, we use a pessimistic
173 // global extent until we've retrieved all the features from the layer
174 return hasCachedAllFeatures() ? mFetchedFeatureExtent : ( !mFilterExtent.isNull() ? mFilterExtent : QgsRectangle( -180, -90, 180, 90 ) );
175}
176
177long long QgsSensorThingsSharedData::featureCount( QgsFeedback *feedback ) const
178{
179 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
180 if ( mFeatureCount >= 0 )
181 return mFeatureCount;
182
183 locker.changeMode( QgsReadWriteLocker::Write );
184 mError.clear();
185
186 // MISSING PART -- how to handle feature count when we are expanding features?
187 // This situation is not handled by the SensorThings standard at all, so we'll just have
188 // to return an unknown count whenever expansion is used
189 if ( !mExpansions.isEmpty() )
190 {
191 return static_cast< long long >( Qgis::FeatureCountState::UnknownCount );
192 }
193
194 // return no features, just the total count
195 QString countUri = u"%1?$top=0&$count=true"_s.arg( mEntityBaseUri );
196 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
197 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, mFilterExtent );
198 QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
199 if ( !filterString.isEmpty() )
200 filterString = u"&$filter="_s + filterString;
201 if ( !filterString.isEmpty() )
202 countUri += filterString;
203
204 const QUrl url = parseUrl( QUrl( countUri ) );
205
206 QNetworkRequest request( url );
207 QgsSetRequestInitiatorClass( request, u"QgsSensorThingsSharedData"_s );
208 mHeaders.updateNetworkRequest( request );
209
210 QgsBlockingNetworkRequest networkRequest;
211 networkRequest.setAuthCfg( mAuthCfg );
212 const QgsBlockingNetworkRequest::ErrorCode error = networkRequest.get( request, false, feedback );
213
214 if ( feedback && feedback->isCanceled() )
215 return mFeatureCount;
216
217 // Handle network errors
219 {
220 QgsDebugError( u"Network error: %1"_s.arg( networkRequest.errorMessage() ) );
221 mError = networkRequest.errorMessage();
222 }
223 else
224 {
225 const QgsNetworkReplyContent content = networkRequest.reply();
226 try
227 {
228 auto rootContent = json::parse( content.content().toStdString() );
229 if ( !rootContent.contains( "@iot.count" ) )
230 {
231 mError = QObject::tr( "No '@iot.count' value in response" );
232 return mFeatureCount;
233 }
234
235 mFeatureCount = rootContent["@iot.count"].get<long long>();
236 if ( mFeatureLimit > 0 && mFeatureCount > mFeatureLimit )
237 mFeatureCount = mFeatureLimit;
238 }
239 catch ( const json::parse_error &ex )
240 {
241 mError = QObject::tr( "Error parsing response: %1" ).arg( ex.what() );
242 }
243 }
244
245 return mFeatureCount;
246}
247
248QString QgsSensorThingsSharedData::subsetString() const
249{
250 return mSubsetString;
251}
252
253bool QgsSensorThingsSharedData::hasCachedAllFeatures() const
254{
255 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
256 return mHasCachedAllFeatures || ( mFeatureCount > 0 && mCachedFeatures.size() == mFeatureCount ) || ( mFeatureLimit > 0 && mRetrievedBaseFeatureCount >= mFeatureLimit );
257}
258
259bool QgsSensorThingsSharedData::getFeature( QgsFeatureId id, QgsFeature &f, QgsFeedback *feedback )
260{
261 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
262
263 // If cached, return cached feature
264 QMap<QgsFeatureId, QgsFeature>::const_iterator it = mCachedFeatures.constFind( id );
265 if ( it != mCachedFeatures.constEnd() )
266 {
267 f = it.value();
268 return true;
269 }
270
271 if ( hasCachedAllFeatures() )
272 return false; // all features are cached, and we didn't find a match
273
274 bool featureFetched = false;
275
276 if ( mNextPage.isEmpty() )
277 {
278 locker.changeMode( QgsReadWriteLocker::Write );
279
280 int thisPageSize = mMaximumPageSize;
281 if ( mFeatureLimit > 0 && ( mCachedFeatures.size() + thisPageSize ) > mFeatureLimit )
282 thisPageSize = mFeatureLimit - mCachedFeatures.size();
283
284 mNextPage = u"%1?$top=%2&$count=false%3"_s.arg( mEntityBaseUri ).arg( thisPageSize ).arg( !mExpandQueryString.isEmpty() ? ( u"&"_s + mExpandQueryString ) : QString() );
285 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
286 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, mFilterExtent );
287 const QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
288 if ( !filterString.isEmpty() )
289 mNextPage += u"&$filter="_s + filterString;
290 }
291
292 locker.unlock();
293
294 processFeatureRequest(
295 mNextPage,
296 feedback,
297 [id, &f, &featureFetched]( const QgsFeature &feature ) {
298 if ( feature.id() == id )
299 {
300 f = feature;
301 featureFetched = true;
302 // don't break here -- store all the features we retrieved in this page first!
303 }
304 },
305 [&featureFetched, this] { return !featureFetched && !hasCachedAllFeatures(); },
306 [this] {
307 mNextPage.clear();
308 mHasCachedAllFeatures = true;
309 }
310 );
311
312 return featureFetched;
313}
314
315QgsFeatureIds QgsSensorThingsSharedData::getFeatureIdsInExtent( const QgsRectangle &extent, QgsFeedback *feedback, const QString &thisPage, QString &nextPage, const QgsFeatureIds &alreadyFetchedIds )
316{
317 const QgsRectangle requestExtent = mFilterExtent.isNull() ? extent : extent.intersect( mFilterExtent );
318 const QgsGeometry extentGeom = QgsGeometry::fromRect( requestExtent );
319 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
320
321 if ( hasCachedAllFeatures() || mCachedExtent.contains( extentGeom ) )
322 {
323 // all features cached locally, rely on local spatial index
324 nextPage.clear();
325 return qgis::listToSet( mSpatialIndex.intersects( requestExtent ) );
326 }
327
328 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
329 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, requestExtent );
330 QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
331 if ( !filterString.isEmpty() )
332 filterString = u"&$filter="_s + filterString;
333 int thisPageSize = mMaximumPageSize;
334 QString queryUrl;
335 if ( !thisPage.isEmpty() )
336 {
337 queryUrl = thisPage;
338 const thread_local QRegularExpression topRe( u"\\$top=\\d+"_s );
339 const QRegularExpressionMatch match = topRe.match( queryUrl );
340 if ( match.hasMatch() )
341 {
342 if ( mFeatureLimit > 0 && ( mCachedFeatures.size() + thisPageSize ) > mFeatureLimit )
343 thisPageSize = mFeatureLimit - mCachedFeatures.size();
344 queryUrl = queryUrl.left( match.capturedStart( 0 ) ) + u"$top=%1"_s.arg( thisPageSize ) + queryUrl.mid( match.capturedEnd( 0 ) );
345 }
346 }
347 else
348 {
349 queryUrl = u"%1?$top=%2&$count=false%3%4"_s.arg( mEntityBaseUri ).arg( thisPageSize ).arg( filterString, !mExpandQueryString.isEmpty() ? ( u"&"_s + mExpandQueryString ) : QString() );
350 }
351
352 if ( thisPage.isEmpty() && mCachedExtent.intersects( extentGeom ) )
353 {
354 // we have SOME of the results from this extent cached. Let's return those first.
355 // This is slightly nicer from a rendering point of view, because panning the map won't see features
356 // previously visible disappear temporarily while we wait for them to be included in the service's result set...
357 nextPage = queryUrl;
358 return qgis::listToSet( mSpatialIndex.intersects( requestExtent ) );
359 }
360
361 locker.unlock();
362
363 QgsFeatureIds ids;
364
365 bool noMoreFeatures = false;
366 bool hasFirstPage = false;
367 const bool res = processFeatureRequest(
368 queryUrl,
369 feedback,
370 [&ids, &alreadyFetchedIds]( const QgsFeature &feature ) {
371 if ( !alreadyFetchedIds.contains( feature.id() ) )
372 ids.insert( feature.id() );
373 },
374 [&hasFirstPage] {
375 if ( !hasFirstPage )
376 {
377 hasFirstPage = true;
378 return true;
379 }
380
381 return false;
382 },
383 [&noMoreFeatures] { noMoreFeatures = true; }
384 );
385 if ( noMoreFeatures && res && ( !feedback || !feedback->isCanceled() ) )
386 {
387 locker.changeMode( QgsReadWriteLocker::Write );
388 mCachedExtent = QgsGeometry::unaryUnion( { mCachedExtent, extentGeom } );
389 }
390 nextPage = noMoreFeatures || !res ? QString() : queryUrl;
391
392 return ids;
393}
394
395void QgsSensorThingsSharedData::clearCache()
396{
397 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Write );
398
399 mFeatureCount = static_cast< long long >( Qgis::FeatureCountState::Uncounted );
400 mCachedFeatures.clear();
401 mIotIdToFeatureId.clear();
402 mSpatialIndex = QgsSpatialIndex();
403 mFetchedFeatureExtent = QgsRectangle();
404}
405
406bool QgsSensorThingsSharedData::processFeatureRequest(
407 QString &nextPage,
408 QgsFeedback *feedback,
409 const std::function< void( const QgsFeature & ) > &fetchedFeatureCallback,
410 const std::function<bool()> &continueFetchingCallback,
411 const std::function<void()> &onNoMoreFeaturesCallback
412)
413{
414 // copy some members before we unlock the read/write locker
415
416 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
417 const QString authcfg = mAuthCfg;
418 const QgsHttpHeaders headers = mHeaders;
419 const QgsFields fields = mFields;
420 const QList< QgsSensorThingsExpansionDefinition > expansions = mExpansions;
421
422 while ( continueFetchingCallback() )
423 {
424 // don't lock while doing the fetch
425 locker.unlock();
426
427 // from: https://docs.ogc.org/is/18-088/18-088.html#nextLink
428 // "SensorThings clients SHALL treat the URL of the nextLink as opaque, and SHALL NOT append system query options to the URL of a next link"
429 //
430 // ie don't mess with this URL!!
431 const QUrl url = parseUrl( nextPage );
432
433 QNetworkRequest request( url );
434 QgsSetRequestInitiatorClass( request, u"QgsSensorThingsSharedData"_s );
435 headers.updateNetworkRequest( request );
436
437 QgsBlockingNetworkRequest networkRequest;
438 networkRequest.setAuthCfg( authcfg );
439 const QgsBlockingNetworkRequest::ErrorCode error = networkRequest.get( request, false, feedback );
440 if ( feedback && feedback->isCanceled() )
441 {
442 return false;
443 }
444
446 {
447 QgsDebugError( u"Network error: %1"_s.arg( networkRequest.errorMessage() ) );
448 locker.changeMode( QgsReadWriteLocker::Write );
449 mError = networkRequest.errorMessage();
450 QgsDebugMsgLevel( u"Query returned empty result"_s, 2 );
451 return false;
452 }
453 else
454 {
455 const QgsNetworkReplyContent content = networkRequest.reply();
456 try
457 {
458 const auto rootContent = json::parse( content.content().toStdString() );
459 if ( !rootContent.contains( "value" ) )
460 {
461 locker.changeMode( QgsReadWriteLocker::Write );
462 mError = QObject::tr( "No 'value' in response" );
463 QgsDebugMsgLevel( u"No 'value' in response"_s, 2 );
464 return false;
465 }
466 else
467 {
468 // all good, got a batch of features
469 const auto &values = rootContent["value"];
470 if ( values.empty() )
471 {
472 locker.changeMode( QgsReadWriteLocker::Write );
473
474 onNoMoreFeaturesCallback();
475
476 return true;
477 }
478 else
479 {
480 locker.changeMode( QgsReadWriteLocker::Write );
481 for ( const auto &featureData : values )
482 {
483 auto getString = []( const basic_json<> &json, const char *tag ) -> QVariant {
484 if ( !json.contains( tag ) )
485 return QVariant();
486
487 std::function< QString( const basic_json<> &obj, bool &ok ) > objToString;
488 objToString = [&objToString]( const basic_json<> &obj, bool &ok ) -> QString {
489 ok = true;
490 if ( obj.is_number_integer() )
491 {
492 return QString::number( obj.get<int>() );
493 }
494 else if ( obj.is_number_unsigned() )
495 {
496 return QString::number( obj.get<unsigned>() );
497 }
498 else if ( obj.is_boolean() )
499 {
500 return QString::number( obj.get<bool>() );
501 }
502 else if ( obj.is_number_float() )
503 {
504 return QString::number( obj.get<double>() );
505 }
506 else if ( obj.is_array() )
507 {
508 QStringList results;
509 results.reserve( obj.size() );
510 for ( const auto &item : obj )
511 {
512 bool itemOk = false;
513 const QString itemString = objToString( item, itemOk );
514 if ( itemOk )
515 results.push_back( itemString );
516 }
517 return results.join( ',' );
518 }
519 else if ( obj.is_string() )
520 {
521 return QString::fromStdString( obj.get<std::string >() );
522 }
523
524 ok = false;
525 return QString();
526 };
527
528 const auto &jObj = json[tag];
529 bool ok = false;
530 const QString r = objToString( jObj, ok );
531 if ( ok )
532 return r;
533 return QVariant();
534 };
535
536 auto getDateTime = []( const basic_json<> &json, const char *tag ) -> QVariant {
537 if ( !json.contains( tag ) )
538 return QVariant();
539
540 const auto &jObj = json[tag];
541 if ( jObj.is_string() )
542 {
543 const QString dateTimeString = QString::fromStdString( json[tag].get<std::string >() );
544 return QDateTime::fromString( dateTimeString, Qt::ISODateWithMs );
545 }
546
547 return QVariant();
548 };
549
550 auto getVariantMap = []( const basic_json<> &json, const char *tag ) -> QVariant {
551 if ( !json.contains( tag ) )
552 return QVariant();
553
554 return QgsJsonUtils::jsonToVariant( json[tag] );
555 };
556
557 auto getVariantList = []( const basic_json<> &json, const char *tag ) -> QVariant {
558 if ( !json.contains( tag ) )
559 return QVariant();
560
561 return QgsJsonUtils::jsonToVariant( json[tag] );
562 };
563
564 auto getStringList = []( const basic_json<> &json, const char *tag ) -> QVariant {
565 if ( !json.contains( tag ) )
566 return QVariant();
567
568 const auto &jObj = json[tag];
569 if ( jObj.is_string() )
570 {
571 return QStringList { QString::fromStdString( json[tag].get<std::string >() ) };
572 }
573 else if ( jObj.is_array() )
574 {
575 QStringList res;
576 for ( const auto &element : jObj )
577 {
578 if ( element.is_string() )
579 res.append( QString::fromStdString( element.get<std::string >() ) );
580 }
581 return res;
582 }
583
584 return QVariant();
585 };
586
587 auto getDateTimeRange = []( const basic_json<> &json, const char *tag ) -> std::pair< QVariant, QVariant > {
588 if ( !json.contains( tag ) )
589 return { QVariant(), QVariant() };
590
591 const auto &jObj = json[tag];
592 if ( jObj.is_string() )
593 {
594 const QString rangeString = QString::fromStdString( json[tag].get<std::string >() );
595 const QStringList rangeParts = rangeString.split( '/' );
596 if ( rangeParts.size() == 2 )
597 {
598 return { QDateTime::fromString( rangeParts.at( 0 ), Qt::ISODateWithMs ), QDateTime::fromString( rangeParts.at( 1 ), Qt::ISODateWithMs ) };
599 }
600 else
601 {
602 const QDateTime instant = QDateTime::fromString( rangeString, Qt::ISODateWithMs );
603 if ( instant.isValid() )
604 return { instant, instant };
605 }
606 }
607
608 return { QVariant(), QVariant() };
609 };
610
611 const QString iotId = getString( featureData, "@iot.id" ).toString();
612 if ( expansions.isEmpty() )
613 {
614 auto existingFeatureIdIt = mIotIdToFeatureId.constFind( iotId );
615 if ( existingFeatureIdIt != mIotIdToFeatureId.constEnd() )
616 {
617 // we've previously fetched and cached this feature, skip it
618 fetchedFeatureCallback( *mCachedFeatures.find( *existingFeatureIdIt ) );
619 continue;
620 }
621 }
622
623 QgsFeature feature( fields );
624
625 // Set geometry
626 if ( mGeometryType != Qgis::WkbType::NoGeometry )
627 {
628 if ( featureData.contains( mGeometryField.toLocal8Bit().constData() ) )
629 {
630 const auto &geometryPart = featureData[mGeometryField.toLocal8Bit().constData()];
631 if ( geometryPart.contains( "geometry" ) )
632 feature.setGeometry( QgsJsonUtils::geometryFromGeoJson( geometryPart["geometry"] ) );
633 else
634 feature.setGeometry( QgsJsonUtils::geometryFromGeoJson( geometryPart ) );
635 }
636 }
637
638 auto extendAttributes =
639 [&getString, &getVariantMap, &getDateTimeRange, &getDateTime, &getStringList, &getVariantList]( Qgis::SensorThingsEntity entityType, const auto &entityData, QgsAttributes &attributes ) {
640 const QString iotId = getString( entityData, "@iot.id" ).toString();
641 const QString selfLink = getString( entityData, "@iot.selfLink" ).toString();
642
643 const QVariant properties = getVariantMap( entityData, "properties" );
644
645 // NOLINTBEGIN(bugprone-branch-clone)
646 switch ( entityType )
647 {
649 break;
650
652 attributes << iotId << selfLink << getString( entityData, "name" ) << getString( entityData, "description" ) << properties;
653 break;
654
656 attributes << iotId << selfLink << getString( entityData, "name" ) << getString( entityData, "description" ) << properties;
657 break;
658
660 attributes << iotId << selfLink << getDateTime( entityData, "time" );
661 break;
662
664 {
665 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
666 std::pair< QVariant, QVariant > resultTime = getDateTimeRange( entityData, "resultTime" );
667 attributes
668 << iotId
669 << selfLink
670 << getString( entityData, "name" )
671 << getString( entityData, "description" )
672 << getVariantMap( entityData, "unitOfMeasurement" )
673 << getString( entityData, "observationType" )
674 << properties
675 << phenomenonTime.first
676 << phenomenonTime.second
677 << resultTime.first
678 << resultTime.second;
679 break;
680 }
681
683 attributes << iotId << selfLink << getString( entityData, "name" ) << getString( entityData, "description" ) << getString( entityData, "metadata" ) << properties;
684 break;
685
687 attributes << iotId << selfLink << getString( entityData, "name" ) << getString( entityData, "definition" ) << getString( entityData, "description" ) << properties;
688 break;
689
691 {
692 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
693 std::pair< QVariant, QVariant > validTime = getDateTimeRange( entityData, "validTime" );
694 attributes
695 << iotId
696 << selfLink
697 << phenomenonTime.first
698 << phenomenonTime.second
699 << getString( entityData, "result" ) // TODO -- result type handling!
700 << getDateTime( entityData, "resultTime" )
701 << getStringList( entityData, "resultQuality" )
702 << validTime.first
703 << validTime.second
704 << getVariantMap( entityData, "parameters" );
705 break;
706 }
707
709 attributes << iotId << selfLink << getString( entityData, "name" ) << getString( entityData, "description" ) << properties;
710 break;
711
713 {
714 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
715 std::pair< QVariant, QVariant > resultTime = getDateTimeRange( entityData, "resultTime" );
716 attributes
717 << iotId
718 << selfLink
719 << getString( entityData, "name" )
720 << getString( entityData, "description" )
721 << getVariantList( entityData, "unitOfMeasurements" )
722 << getString( entityData, "observationType" )
723 << getStringList( entityData, "multiObservationDataTypes" )
724 << properties
725 << phenomenonTime.first
726 << phenomenonTime.second
727 << resultTime.first
728 << resultTime.second;
729 break;
730 }
731 }
732 // NOLINTEND(bugprone-branch-clone)
733 };
734
735 QgsAttributes attributes;
736 attributes.reserve( fields.size() );
737 extendAttributes( mEntityType, featureData, attributes );
738
739 auto processFeature = [this, &fetchedFeatureCallback]( QgsFeature &feature, const QString &rawFeatureId ) {
740 feature.setId( mNextFeatureId++ );
741
742 mCachedFeatures.insert( feature.id(), feature );
743 mIotIdToFeatureId.insert( rawFeatureId, feature.id() );
744 mSpatialIndex.addFeature( feature );
745 mFetchedFeatureExtent.combineExtentWith( feature.geometry().boundingBox() );
746
747 fetchedFeatureCallback( feature );
748 };
749
750 const QString baseFeatureId = getString( featureData, "@iot.id" ).toString();
751 if ( !expansions.empty() )
752 {
753 mRetrievedBaseFeatureCount++;
754
755 std::function< void( const nlohmann::json &, Qgis::SensorThingsEntity, const QList<QgsSensorThingsExpansionDefinition > &, const QString &, const QgsAttributes & ) > traverseExpansion;
756 traverseExpansion =
757 [this,
758 &feature,
759 &getString,
760 &traverseExpansion,
761 &fetchedFeatureCallback,
762 &extendAttributes,
763 &processFeature]( const nlohmann::json &currentLevelData, Qgis::SensorThingsEntity parentEntityType, const QList<QgsSensorThingsExpansionDefinition > &expansionTargets, const QString &lowerLevelId, const QgsAttributes &lowerLevelAttributes ) {
764 const QgsSensorThingsExpansionDefinition currentExpansionTarget = expansionTargets.at( 0 );
765 const QList< QgsSensorThingsExpansionDefinition > remainingExpansionTargets = expansionTargets.mid( 1 );
766
767 bool ok = false;
768 const Qgis::RelationshipCardinality cardinality = QgsSensorThingsUtils::relationshipCardinality( parentEntityType, currentExpansionTarget.childEntity(), ok );
769 QString currentExpansionPropertyString;
770 switch ( cardinality )
771 {
774 currentExpansionPropertyString = qgsEnumValueToKey( currentExpansionTarget.childEntity() );
775 break;
776
779 currentExpansionPropertyString = QgsSensorThingsUtils::entityToSetString( currentExpansionTarget.childEntity() );
780 break;
781 }
782
783 if ( currentLevelData.contains( currentExpansionPropertyString.toLocal8Bit().constData() ) )
784 {
785 auto parseExpandedEntity = [lowerLevelAttributes,
786 &feature,
787 &processFeature,
788 &lowerLevelId,
789 &getString,
790 &remainingExpansionTargets,
791 &fetchedFeatureCallback,
792 &extendAttributes,
793 &traverseExpansion,
794 &currentExpansionTarget,
795 this]( const json &expandedEntityElement ) {
796 QgsAttributes expandedAttributes = lowerLevelAttributes;
797 const QString expandedEntityIotId = getString( expandedEntityElement, "@iot.id" ).toString();
798 const QString expandedFeatureId = lowerLevelId + '_' + expandedEntityIotId;
799
800 if ( remainingExpansionTargets.empty() )
801 {
802 auto existingFeatureIdIt = mIotIdToFeatureId.constFind( expandedFeatureId );
803 if ( existingFeatureIdIt != mIotIdToFeatureId.constEnd() )
804 {
805 // we've previously fetched and cached this feature, skip it
806 fetchedFeatureCallback( *mCachedFeatures.find( *existingFeatureIdIt ) );
807 return;
808 }
809 }
810
811 extendAttributes( currentExpansionTarget.childEntity(), expandedEntityElement, expandedAttributes );
812 if ( !remainingExpansionTargets.empty() )
813 {
814 // traverse deeper
815 traverseExpansion( expandedEntityElement, currentExpansionTarget.childEntity(), remainingExpansionTargets, expandedFeatureId, expandedAttributes );
816 }
817 else
818 {
819 feature.setAttributes( expandedAttributes );
820 processFeature( feature, expandedFeatureId );
821 }
822 };
823 const auto &expandedEntity = currentLevelData[currentExpansionPropertyString.toLocal8Bit().constData()];
824 if ( expandedEntity.is_array() )
825 {
826 for ( const auto &expandedEntityElement : expandedEntity )
827 {
828 parseExpandedEntity( expandedEntityElement );
829 }
830 // NOTE: What do we do when the expanded entity has a next link? Does this situation ever arise?
831 // The specification doesn't explicitly state whether pagination is supported for expansion, so we assume
832 // it's not possible.
833 }
834 else if ( expandedEntity.is_object() )
835 {
836 parseExpandedEntity( expandedEntity );
837 }
838 }
839 else
840 {
841 // No expansion for this parent feature.
842 // Maybe we should NULL out the attributes and return the parent feature? Right now we just
843 // skip it if there's no child features...
844 }
845 };
846
847 traverseExpansion( featureData, mEntityType, expansions, baseFeatureId, attributes );
848
849 if ( mFeatureLimit > 0 && mFeatureLimit <= mRetrievedBaseFeatureCount )
850 break;
851 }
852 else
853 {
854 feature.setAttributes( attributes );
855 processFeature( feature, baseFeatureId );
856 mRetrievedBaseFeatureCount++;
857 if ( mFeatureLimit > 0 && mFeatureLimit <= mRetrievedBaseFeatureCount )
858 break;
859 }
860 }
861 }
862 locker.unlock();
863
864 if ( rootContent.contains( "@iot.nextLink" ) && ( mFeatureLimit == 0 || mFeatureLimit > mCachedFeatures.size() ) )
865 {
866 nextPage = QString::fromStdString( rootContent["@iot.nextLink"].get<std::string>() );
867 }
868 else
869 {
870 onNoMoreFeaturesCallback();
871 }
872
873 // if target feature was added to cache, return it
874 if ( !continueFetchingCallback() )
875 {
876 return true;
877 }
878 }
879 }
880 catch ( const json::parse_error &ex )
881 {
882 locker.changeMode( QgsReadWriteLocker::Write );
883 mError = QObject::tr( "Error parsing response: %1" ).arg( ex.what() );
884 QgsDebugMsgLevel( u"Error parsing response: %1"_s.arg( ex.what() ), 2 );
885 return false;
886 }
887 }
888 }
889 return false;
890}
891
SensorThingsEntity
OGC SensorThings API entity types.
Definition qgis.h:6324
@ Sensor
A Sensor is an instrument that observes a property or phenomenon with the goal of producing an estima...
Definition qgis.h:6330
@ MultiDatastream
A MultiDatastream groups a collection of Observations and the Observations in a MultiDatastream have ...
Definition qgis.h:6334
@ ObservedProperty
An ObservedProperty specifies the phenomenon of an Observation.
Definition qgis.h:6331
@ Invalid
An invalid/unknown entity.
Definition qgis.h:6325
@ FeatureOfInterest
In the context of the Internet of Things, many Observations’ FeatureOfInterest can be the Location of...
Definition qgis.h:6333
@ Datastream
A Datastream groups a collection of Observations measuring the same ObservedProperty and produced by ...
Definition qgis.h:6329
@ Observation
An Observation is the act of measuring or otherwise determining the value of a property.
Definition qgis.h:6332
@ Location
A Location entity locates the Thing or the Things it associated with. A Thing’s Location entity is de...
Definition qgis.h:6327
@ Thing
A Thing is an object of the physical world (physical things) or the information world (virtual things...
Definition qgis.h:6326
@ HistoricalLocation
A Thing’s HistoricalLocation entity set provides the times of the current (i.e., last known) and prev...
Definition qgis.h:6328
RelationshipCardinality
Relationship cardinality.
Definition qgis.h:4561
@ ManyToMany
Many to many relationship.
Definition qgis.h:4565
@ ManyToOne
Many to one relationship.
Definition qgis.h:4564
@ OneToOne
One to one relationship.
Definition qgis.h:4562
@ OneToMany
One to many relationship.
Definition qgis.h:4563
@ MultiPointZ
MultiPointZ.
Definition qgis.h:317
@ NoGeometry
No geometry.
Definition qgis.h:312
@ PointZ
PointZ.
Definition qgis.h:313
@ MultiLineStringZ
MultiLineStringZ.
Definition qgis.h:318
@ MultiPolygonZ
MultiPolygonZ.
Definition qgis.h:319
A vector of attributes.
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
QString errorMessage() const
Returns the error message string, after a get(), post(), head() or put() request has been made.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NoError
No error was encountered.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Represents a coordinate reference system (CRS).
Stores the component parts of a data source URI (e.g.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsFeatureId id
Definition qgsfeature.h:68
void setId(QgsFeatureId id)
Sets the feature id for this feature.
QgsGeometry geometry
Definition qgsfeature.h:71
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
int size() const
Returns number of items.
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Implements simple HTTP header management.
bool updateNetworkRequest(QNetworkRequest &request) const
Updates a request by adding all the HTTP headers.
static QgsGeometry geometryFromGeoJson(const json &geometry)
Parses a GeoJSON "geometry" value to a QgsGeometry object.
static QVariant jsonToVariant(const json &value)
Converts a JSON value to a QVariant, in case of parsing error an invalid QVariant is returned.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
QByteArray content() const
Returns the reply content.
A convenience class that simplifies locking and unlocking QReadWriteLocks.
@ Write
Lock for write.
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be rounded to the spec...
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Encapsulates information about how relationships in a SensorThings API service should be expanded.
Qgis::SensorThingsEntity childEntity() const
Returns the target child entity which should be expanded.
bool isValid() const
Returns true if the definition is valid.
static QString entityToSetString(Qgis::SensorThingsEntity type)
Converts a SensorThings entity set to a SensorThings entity set string.
static QString asQueryString(Qgis::SensorThingsEntity baseType, const QList< QgsSensorThingsExpansionDefinition > &expansions)
Returns a list of expansions as a valid SensorThings API query string, eg "$expand=Locations($orderby...
static QString combineFilters(const QStringList &filters)
Combines a set of SensorThings API filter operators.
static QString filterForWkbType(Qgis::SensorThingsEntity entityType, Qgis::WkbType wkbType)
Returns a filter string which restricts results to those matching the specified entityType and wkbTyp...
static Qgis::RelationshipCardinality relationshipCardinality(Qgis::SensorThingsEntity baseType, Qgis::SensorThingsEntity relatedType, bool &valid)
Returns the cardinality of the relationship between a base entity type and a related entity type.
static bool entityTypeHasGeometry(Qgis::SensorThingsEntity type)
Returns true if the specified entity type can have geometry attached.
static QgsFields fieldsForExpandedEntityType(Qgis::SensorThingsEntity baseType, const QList< Qgis::SensorThingsEntity > &expandedTypes)
Returns the fields which correspond to a specified entity baseType, expanded using the specified list...
static QString geometryFieldForEntityType(Qgis::SensorThingsEntity type)
Returns the geometry field for a specified entity type.
static QString filterForExtent(const QString &geometryField, const QgsRectangle &extent)
Returns a filter string which restricts results to those within the specified extent.
A spatial index for QgsFeature objects.
@ Uncounted
Feature count not yet computed.
Definition qgis.h:572
@ UnknownCount
Provider returned an unknown feature count.
Definition qgis.h:573
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:7176
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7157
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
#define QgsSetRequestInitiatorClass(request, _class)