QGIS API Documentation 4.3.0-Master (bf28115e945)
Loading...
Searching...
No Matches
qgsserverogcapihandler.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsserverogcapihandler.cpp - QgsServerOgcApiHandler
3
4 ---------------------
5 begin : 10.7.2019
6 copyright : (C) 2019 by Alessandro Pasotti
7 email : elpaso at itopen dot it
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
18
19#include <nlohmann/json.hpp>
20
21#include "inja/inja.hpp"
22#include "qgsjsonutils.h"
23#include "qgsmessagelog.h"
24#include "qgsproject.h"
25#include "qgsserverapiutils.h"
26#include "qgsserverinterface.h"
27#include "qgsserverresponse.h"
28#include "qgsvectorlayer.h"
29
30#include <QDateTime>
31#include <QDebug>
32#include <QDir>
33#include <QFileInfo>
34#include <QString>
35
36using namespace Qt::StringLiterals;
37
38using namespace nlohmann;
39using namespace inja;
40
41
42QVariantMap QgsServerOgcApiHandler::values( const QgsServerApiContext &context ) const
43{
44 QVariantMap result;
45 const auto constParameters { parameters( context ) };
46 for ( const auto &p : constParameters )
47 {
48 // value() calls the validators and throws an exception if validation fails
49 result[p.name()] = p.value( context );
50 }
51 const auto sanitizedPath { QgsServerOgcApi::sanitizeUrl( context.handlerPath() ).path() };
52 const auto match { path().match( sanitizedPath ) };
53 if ( match.hasMatch() )
54 {
55 const auto constNamed { path().namedCaptureGroups() };
56 // Get named path parameters
57 for ( const auto &name : constNamed )
58 {
59 if ( !name.isEmpty() )
60 result[name] = QUrlQuery( match.captured( name ) ).toString();
61 }
62 }
63 return result;
64}
65
67{
68 //qDebug() << "handler destroyed";
69}
70
72{
73 const auto constContentTypes( contentTypes() );
74 return constContentTypes.size() > 0 ? constContentTypes.first() : QgsServerOgcApi::ContentType::JSON;
75}
76
77QList<QgsServerOgcApi::ContentType> QgsServerOgcApiHandler::contentTypes() const
78{
79 return mContentTypes;
80}
81
83{
84 Q_UNUSED( context )
85 throw QgsServerApiNotImplementedException( u"Subclasses must implement handleRequest"_s );
86}
87
88QString QgsServerOgcApiHandler::contentTypeForAccept( const QString &accept ) const
89{
90 const auto constContentTypes( QgsServerOgcApi::contentTypeMimes() );
91 for ( auto it = constContentTypes.constBegin(); it != constContentTypes.constEnd(); ++it )
92 {
93 const auto constValues = it.value();
94 for ( const auto &value : constValues )
95 {
96 if ( accept.contains( value, Qt::CaseSensitivity::CaseInsensitive ) )
97 {
98 return value;
99 }
100 }
101 }
102 // Log level info because this is not completely unexpected
103 QgsMessageLog::logMessage( u"Content type for accept %1 not found!"_s.arg( accept ), u"Server"_s, Qgis::MessageLevel::Info );
104
105 return QString();
106}
107
108void QgsServerOgcApiHandler::write( json &data, const QgsServerApiContext &context, const json &htmlMetadata ) const
109{
110 const QgsServerOgcApi::ContentType contentType { contentTypeFromRequest( context.request() ) };
111 switch ( contentType )
112 {
114 data["handler"] = schema( context );
115 if ( !htmlMetadata.is_null() )
116 {
117 data["metadata"] = htmlMetadata;
118 }
119 htmlDump( data, context );
120 break;
125 jsonDump( data, context, QgsServerOgcApi::contentTypeMimes().value( contentType ).first() );
126 break;
128 // Not handled yet
129 break;
131 // Handled separately in the handler if supported, so do nothing here
132 break;
133 }
134}
135
136void QgsServerOgcApiHandler::write( QVariant &data, const QgsServerApiContext &context, const QVariantMap &htmlMetadata ) const
137{
138 json j = QgsJsonUtils::jsonFromVariant( data );
139 json jm = QgsJsonUtils::jsonFromVariant( htmlMetadata );
140 QgsServerOgcApiHandler::write( j, context, jm );
141}
142
143std::string QgsServerOgcApiHandler::href( const QgsServerApiContext &context, const QString &extraPath, const QString &extension ) const
144{
145 QUrl url { context.request()->url() };
146 QString urlBasePath { context.matchedPath() };
147 const auto match { path().match( QgsServerOgcApi::sanitizeUrl( context.handlerPath() ).path() ) };
148 if ( match.captured().count() > 0 )
149 {
150 url.setPath( urlBasePath + match.captured( 0 ) );
151 }
152 else
153 {
154 url.setPath( urlBasePath );
155 }
156
157 // Remove any existing extension
158 const auto suffixLength { QFileInfo( url.path() ).suffix().length() };
159 if ( suffixLength > 0 )
160 {
161 auto path { url.path() };
162 path.truncate( path.length() - ( suffixLength + 1 ) );
163 url.setPath( path );
164 }
165
166 // Add extra path
167 url.setPath( url.path() + extraPath );
168
169 // (re-)add extension
170 // JSON is the default anyway so we don't need to add it
171 if ( !extension.isEmpty() )
172 {
173 // Remove trailing slashes if any.
174 QString path { url.path() };
175 while ( path.endsWith( '/' ) )
176 {
177 path.chop( 1 );
178 }
179 url.setPath( path + '.' + extension );
180 }
181 return QgsServerOgcApi::sanitizeUrl( url ).toString( QUrl::FullyEncoded ).toStdString();
182}
183
184void QgsServerOgcApiHandler::jsonDump( json &data, const QgsServerApiContext &context, const QString &contentType ) const
185{
186 // Do not append timestamp to openapi
187 if ( !QgsServerOgcApi::contentTypeMimes().value( QgsServerOgcApi::ContentType::OPENAPI3 ).contains( contentType, Qt::CaseSensitivity::CaseInsensitive ) )
188 {
189 QDateTime time { QDateTime::currentDateTime() };
190 time.setTimeSpec( Qt::TimeSpec::UTC );
191 data["timeStamp"] = time.toString( Qt::DateFormat::ISODate ).toStdString();
192 }
193 context.response()->setStatusCode( 200 );
194 context.response()->setHeader( u"Content-Type"_s, contentType );
195#ifdef QGISDEBUG
196 context.response()->write( data.dump( 2 ) );
197#else
198 context.response()->write( data.dump() );
199#endif
200}
201
203{
204 Q_UNUSED( context )
205 return nullptr;
206}
207
208json QgsServerOgcApiHandler::link( const QgsServerApiContext &context, const QgsServerOgcApi::Rel &linkType, const QgsServerOgcApi::ContentType contentType, const std::string &title ) const
209{
210 json l {
211 { "href", href( context, "/", QgsServerOgcApi::contentTypeToExtension( contentType ) ) },
213 { "type", QgsServerOgcApi::mimeType( contentType ) },
214 { "title", title != "" ? title : linkTitle() },
215 };
216 return l;
217}
218
220 const QgsServerApiContext &context, const QgsServerOgcApi::Rel &linkType, const QgsServerOgcApi::ContentType contentType, const QgsServerOgcApi::Profile &profile, const QString &title
221) const
222{
223 const QString profileStr { profile != QgsServerOgcApi::Profile::Unset ? QgsServerOgcApi::profileToString( profile ) : QString() };
224 QString hrefStr = QString::fromStdString( href( context, "/", QgsServerOgcApi::contentTypeToExtension( contentType ) ) );
225
226 if ( !profileStr.isEmpty() )
227 {
228 hrefStr += "&profile="_L1 + profileStr;
229 }
230
231 QString titleStr = !title.isEmpty() ? title : QString::fromStdString( linkTitle() );
232 titleStr.replace( '\\', "\\\\"_L1 );
233 titleStr.replace( '"', "\\\""_L1 );
234
235 QString linkStr = u"<%1>; rel=\"%2\"; title=\"%3\"; type=\"%4\""_s.arg(
236 QString::fromStdString( href( context, "/", QgsServerOgcApi::contentTypeToExtension( contentType ) ) ),
237 QString::fromStdString( QgsServerOgcApi::relToString( linkType ) ),
238 titleStr,
239 QString::fromStdString( QgsServerOgcApi::mimeType( contentType ) )
240 );
241
242 if ( !profileStr.isEmpty() )
243 {
244 linkStr += u"; profile=\"%1\""_s.arg( profileStr );
245 }
246
247 return linkStr;
248}
249
251{
252 const QgsServerOgcApi::ContentType currentCt { contentTypeFromRequest( context.request() ) };
253 json links = json::array();
254 const QList<QgsServerOgcApi::ContentType> constCts { contentTypes() };
255 for ( const auto &ct : constCts )
256 {
257 links.push_back( link( context, ( ct == currentCt ? QgsServerOgcApi::Rel::self : QgsServerOgcApi::Rel::alternate ), ct, linkTitle() + " as " + QgsServerOgcApi::contentTypeToStdString( ct ) ) );
258 }
259 return links;
260}
261
263{
264 if ( !context.project() )
265 {
266 throw QgsServerApiImproperlyConfiguredException( u"Project is invalid or undefined"_s );
267 }
268 // Check collectionId
269 const QRegularExpressionMatch match { path().match( context.request()->url().path() ) };
270 if ( !match.hasMatch() )
271 {
272 throw QgsServerApiNotFoundError( u"Collection was not found"_s );
273 }
274 const QString collectionId { match.captured( u"collectionId"_s ) };
275 // May throw if not found
276 return layerFromCollectionId( context, collectionId );
277}
278
279const QString QgsServerOgcApiHandler::staticPath( const QgsServerApiContext &context ) const
280{
281 // resources/server/api + /static
282 return context.serverInterface()->serverSettings()->apiResourcesDirectory() + u"/ogc/static"_s;
283}
284
286{
287 // resources/server/api + /ogc/templates/ + apiRootPath() + / + operationId() + .html
288 QString path { context.serverInterface()->serverSettings()->apiResourcesDirectory() };
289 path += "/ogc/templates"_L1;
290 path += context.apiRootPath();
291 path += '/';
292 path += QString::fromStdString( operationId() );
293 path += ".html"_L1;
294 return path;
295}
296
297void QgsServerOgcApiHandler::htmlDump( const json &data, const QgsServerApiContext &context ) const
298{
299 context.response()->setHeader( u"Content-Type"_s, u"text/html"_s );
300 auto path { templatePath( context ) };
301 if ( !QFile::exists( path ) )
302 {
303 QgsMessageLog::logMessage( u"Template not found error: %1"_s.arg( path ), u"Server"_s, Qgis::MessageLevel::Critical );
304 throw QgsServerApiBadRequestException( u"Template not found: %1"_s.arg( QFileInfo( path ).fileName() ) );
305 }
306
307 QFile f( path );
308 if ( !f.open( QFile::ReadOnly | QFile::Text ) )
309 {
310 QgsMessageLog::logMessage( u"Could not open template file: %1"_s.arg( path ), u"Server"_s, Qgis::MessageLevel::Critical );
311 throw QgsServerApiInternalServerError( u"Could not open template file: %1"_s.arg( QFileInfo( path ).fileName() ) );
312 }
313
314 try
315 {
316 // Get the template directory and the file name
317 QFileInfo pathInfo { path };
318 Environment env { QString( pathInfo.dir().path() + QDir::separator() ).toStdString() };
319
320 // For template debugging:
321 env.add_callback( "json_dump", 0, [data]( Arguments & ) { return data.dump(); } );
322
323 // Path manipulation: appends a directory path to the current url
324 env.add_callback( "path_append", 1, [context]( Arguments &args ) {
325 auto url { context.request()->url() };
326 QFileInfo fi { url.path() };
327 auto suffix { fi.suffix() };
328 auto fName { fi.filePath() };
329 if ( !suffix.isEmpty() )
330 {
331 fName.chop( suffix.length() + 1 );
332 }
333 // Chop any ending slashes
334 while ( fName.endsWith( '/' ) )
335 {
336 fName.chop( 1 );
337 }
338 fName += '/' + QString::fromStdString( args.at( 0 )->get<std::string>() );
339 if ( !suffix.isEmpty() )
340 {
341 fName += '.' + suffix;
342 }
343 fi.setFile( fName );
344 url.setPath( fi.filePath() );
345 return url.toString().toStdString();
346 } );
347
348 // Path manipulation: removes the specified number of directory components from the current url path
349 env.add_callback( "path_chomp", 1, []( Arguments &args ) {
350 QUrl url { QString::fromStdString( args.at( 0 )->get<std::string>() ) };
351 QFileInfo fi { url.path() };
352 auto suffix { fi.suffix() };
353 auto fName { fi.filePath() };
354 fName.chop( suffix.length() + 1 );
355 // Chomp last segment
356 const thread_local QRegularExpression segmentRx( R"raw(\/[^/]+$)raw" );
357 fName = fName.replace( segmentRx, QString() );
358 if ( !suffix.isEmpty() )
359 {
360 fName += '.' + suffix;
361 }
362 fi.setFile( fName );
363 url.setPath( fi.filePath() );
364 return url.toString().toStdString();
365 } );
366
367 // Returns filtered links from a link list
368 // links_filter( <links>, <key>, <value> )
369 env.add_callback( "links_filter", 3, []( Arguments &args ) {
370 json links = args.at( 0 )->get<json>();
371 if ( !links.is_array() )
372 {
373 links = json::array();
374 }
375 std::string key { args.at( 1 )->get<std::string>() };
376 std::string value { args.at( 2 )->get<std::string>() };
377 json result = json::array();
378 for ( const auto &l : links )
379 {
380 if ( l[key] == value )
381 {
382 result.push_back( l );
383 }
384 }
385 return result;
386 } );
387
388 // Returns a short name from content types
389 env.add_callback( "content_type_name", 1, []( Arguments &args ) {
390 const QgsServerOgcApi::ContentType ct { QgsServerOgcApi::contentTypeFromExtension( args.at( 0 )->get<std::string>() ) };
392 } );
393
394 // Replace newlines with <br>
395 env.add_callback( "nl2br", 1, []( Arguments &args ) {
396 QString text { QString::fromStdString( args.at( 0 )->get<std::string>() ) };
397 return text.replace( '\n', "<br>"_L1 ).toStdString();
398 } );
399
400
401 // Returns a list of parameter component data from components -> parameters by ref name
402 // parameter( <ref object> )
403 env.add_callback( "component_parameter", 1, [data]( Arguments &args ) {
404 json ret = json::array();
405 json ref = args.at( 0 )->get<json>();
406 if ( !ref.is_object() )
407 {
408 return ret;
409 }
410 try
411 {
412 QString name = QString::fromStdString( ref["$ref"] );
413 name = name.split( '/' ).last();
414 ret.push_back( data["components"]["parameters"][name.toStdString()] );
415 }
416 catch ( std::exception & )
417 {
418 // Do nothing
419 }
420 return ret;
421 } );
422
423
424 // Static: returns the full URL to the specified static <path>
425 env.add_callback( "static", 1, [context]( Arguments &args ) {
426 auto asset( args.at( 0 )->get<std::string>() );
427 QString matchedPath { context.matchedPath() };
428 // If its the root path '/' strip it!
429 if ( matchedPath == '/' )
430 {
431 matchedPath.clear();
432 }
433 return matchedPath.toStdString() + "/static/" + asset;
434 } );
435
436
437 // Returns true if a string begins with the provided string prefix, false otherwise
438 env.add_callback( "starts_with", 2, []( Arguments &args ) { return string_view::starts_with( args.at( 0 )->get<std::string_view>(), args.at( 1 )->get<std::string_view>() ); } );
439
440 // Returns "null" string if object is null else string object representation
441 env.add_callback( "if_nullptr_null_str", 1, []( Arguments &args ) {
442 json jsonValue = args.at( 0 )->get<json>();
443 std::string out;
444 switch ( jsonValue.type() )
445 {
446 // avoid escaping string value
447 case json::value_t::string:
448 out = jsonValue.get<std::string>();
449 break;
450
451 case json::value_t::array:
452 case json::value_t::object:
453 if ( jsonValue.is_null() )
454 {
455 out = "null";
456 }
457 else
458 {
459 out = jsonValue.dump();
460 }
461
462 break;
463
464 // use dump() for all other value types
465 default:
466 out = jsonValue.dump();
467 }
468 return out;
469 } );
470
471 context.response()->write( env.render_file( pathInfo.fileName().toStdString(), data ) );
472 }
473 catch ( std::exception &e )
474 {
475 QgsMessageLog::logMessage( u"Error parsing template file: %1 - %2"_s.arg( path, e.what() ), u"Server"_s, Qgis::MessageLevel::Critical );
476 throw QgsServerApiInternalServerError( u"Error parsing template file: %1"_s.arg( e.what() ) );
477 }
478}
479
481{
482 // Fallback to default
484 bool found { false };
485 // First file extension ...
486 const QString extension { QFileInfo( request->url().path() ).suffix().toUpper() };
487 if ( !extension.isEmpty() )
488 {
489 static QMetaEnum metaEnum { QMetaEnum::fromType<QgsServerOgcApi::ContentType>() };
490 bool ok { false };
491 const int ct { metaEnum.keyToValue( extension.toLocal8Bit().constData(), &ok ) };
492 if ( ok )
493 {
494 result = static_cast<QgsServerOgcApi::ContentType>( ct );
495 found = true;
496 }
497 else
498 {
499 // Hardcoded aliases
500#if 0
501 // This not supported yet but I am leaving it here because
502 // I am very optimistic that it will be supported soon!
503
504 if ( ( extension.compare( u"JSONFG"_s, Qt::CaseSensitivity::CaseInsensitive ) == 0 ) || ( extension.compare( u"JSONFG-PLUS"_s, Qt::CaseSensitivity::CaseInsensitive ) == 0 ) )
505 {
507 found = true;
508 }
509 else
510#endif
511 if ( extension.compare( u"FGB"_s, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
512 {
514 found = true;
515 }
516 else
517 {
518 QgsMessageLog::logMessage( u"The client requested an unsupported extension: %1"_s.arg( extension ), u"Server"_s, Qgis::MessageLevel::Warning );
519 }
520 }
521 }
522 // ... then "Accept"
523 const QString accept { request->header( u"Accept"_s ) };
524 if ( !found && !accept.isEmpty() )
525 {
526 const QString ctFromAccept { contentTypeForAccept( accept ) };
527 if ( !ctFromAccept.isEmpty() )
528 {
529 const auto constContentTypes( QgsServerOgcApi::contentTypeMimes() );
530 auto it = constContentTypes.constBegin();
531 while ( !found && it != constContentTypes.constEnd() )
532 {
533 int idx = it.value().indexOf( ctFromAccept );
534 if ( idx >= 0 )
535 {
536 found = true;
537 result = it.key();
538 }
539 it++;
540 }
541 }
542 else
543 {
544 QgsMessageLog::logMessage( u"The client requested an unsupported content type in Accept header: %1"_s.arg( accept ), u"Server"_s, Qgis::MessageLevel::Warning );
545 }
546 }
547 // Validation: check if the requested content type (or an alias) is supported by the handler
548 if ( !contentTypes().contains( result ) )
549 {
550 // Check aliases
551 bool found { false };
552 if ( QgsServerOgcApi::contentTypeAliases().contains( result ) )
553 {
554 const QList<QgsServerOgcApi::ContentType> constCt { contentTypes() };
555 for ( const auto &ct : constCt )
556 {
557 if ( QgsServerOgcApi::contentTypeAliases()[result].contains( ct ) )
558 {
559 result = ct;
560 found = true;
561 break;
562 }
563 }
564 }
565
566 if ( !found )
567 {
568 QgsMessageLog::logMessage( u"Unsupported Content-Type: %1"_s.arg( QgsServerOgcApi::contentTypeToString( result ) ), u"Server"_s, Qgis::MessageLevel::Info );
569 throw QgsServerApiBadRequestException( u"Unsupported Content-Type: %1"_s.arg( QgsServerOgcApi::contentTypeToString( result ) ) );
570 }
571 }
572 return result;
573}
574
576{
577 if ( profile.compare( "RFC7946"_L1, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
578 {
579 ok = true;
581 }
582 else if ( profile.compare( "REL-AS-KEY"_L1, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
583 {
584 ok = true;
586 }
587 else if ( profile.compare( "REL-AS-URI"_L1, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
588 {
589 ok = true;
591 }
592 else if ( profile.compare( "REL-AS-LINK"_L1, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
593 {
594 ok = true;
596 }
597 else
598 {
599 ok = false;
601 }
603}
604
605QList<QgsServerOgcApi::Profile> QgsServerOgcApiHandler::profilesFromRequest( const QgsServerRequest *request ) const
606{
607 const QStringList profileStrings { request->queryParameter( u"profile"_s ).split( ',', Qt::SkipEmptyParts ) };
608 QList<QgsServerOgcApi::Profile> profiles;
609 if ( !profileStrings.isEmpty() )
610 {
611 for ( const auto &profileString : std::as_const( profileStrings ) )
612 {
613 bool ok { false };
614 const QgsServerOgcApi::Profile p { profileFromString( profileString, ok ) };
615 if ( ok )
616 {
617 profiles.push_back( p );
618 }
619 else
620 {
621 throw QgsServerApiBadRequestException( u"Unsupported profile requested: %1"_s.arg( profileString ) );
622 }
623 }
624 }
625 return profiles;
626}
627
628QString QgsServerOgcApiHandler::parentLink( const QUrl &url, int levels )
629{
630 QString path { url.path() };
631 const QFileInfo fi { path };
632 const QString suffix { fi.suffix() };
633 if ( !suffix.isEmpty() )
634 {
635 path.chop( suffix.length() + 1 );
636 }
637 while ( path.endsWith( '/' ) )
638 {
639 path.chop( 1 );
640 }
641 const thread_local QRegularExpression re( R"raw(\/[^/]+$)raw" );
642 for ( int i = 0; i < levels; i++ )
643 {
644 path = path.replace( re, QString() );
645 }
646 QUrl result( url );
647 QUrlQuery query( result );
648 QList<QPair<QString, QString>> qi;
649 const auto constItems { query.queryItems() };
650 for ( const auto &i : constItems )
651 {
652 if ( i.first.compare( u"MAP"_s, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
653 {
654 qi.push_back( i );
655 }
656 }
657 // Make sure the parent link ends with a slash
658 if ( !path.endsWith( '/' ) )
659 {
660 path.append( '/' );
661 }
662 QUrlQuery resultQuery;
663 resultQuery.setQueryItems( qi );
664 result.setQuery( resultQuery );
665 result.setPath( path );
666 return result.toString();
667}
668
670{
671 const auto mapLayers { context.project()->mapLayersByShortName<QgsVectorLayer *>( collectionId ) };
672 if ( mapLayers.count() != 1 )
673 {
674 throw QgsServerApiNotFoundError( u"Collection with given id (%1) was not found or multiple matches were found"_s.arg( collectionId ) );
675 }
676 return mapLayers.first();
677}
678
680{
681 static json defRes
682 = { { "description", "An error occurred." }, { "content", { { "application/json", { { "schema", { { "$ref", "#/components/schemas/exception" } } } } }, { "text/html", { { "schema", { { "type", "string" } } } } } } } };
683 return defRes;
684}
685
690
692{
693 mContentTypes.clear();
694 for ( const int &i : std::as_const( contentTypes ) )
695 {
696 mContentTypes.push_back( static_cast<QgsServerOgcApi::ContentType>( i ) );
697 }
698}
699
700void QgsServerOgcApiHandler::setContentTypes( const QList<QgsServerOgcApi::ContentType> &contentTypes )
701{
702 mContentTypes = contentTypes;
703}
@ Warning
Warning message.
Definition qgis.h:162
@ Critical
Critical/error message.
Definition qgis.h:163
@ Info
Information message.
Definition qgis.h:161
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
QList< QgsMapLayer * > mapLayersByShortName(const QString &shortName) const
Retrieves a list of matching registered layers by layer shortName.
Bad request error API exception.
Encapsulates the resources for a particular client request.
const QgsProject * project() const
Returns the (possibly NULL) project.
QgsServerResponse * response() const
Returns the server response object.
QString handlerPath() const
Returns the handler component of the URL path, i.e.
const QgsServerRequest * request() const
Returns the server request object.
QgsServerInterface * serverInterface() const
Returns the server interface.
QString apiRootPath() const
Returns the API root path.
const QString matchedPath() const
Returns the initial part of the incoming request URL path that matches the API root path.
Raised when a configuration error on the server prevents to serve the request, which would be valid o...
Internal server error API exception.
Not found error API exception.
Raised when the client requested a method that is not yet implemented.
virtual QgsServerSettings * serverSettings()=0
Returns the server settings.
void jsonDump(json &data, const QgsServerApiContext &context, const QString &contentType=u"application/json"_s) const
Writes data to the context response stream as JSON (indented if debug is active), an optional content...
std::string href(const QgsServerApiContext &context, const QString &extraPath=QString(), const QString &extension=QString()) const
Returns an URL to self, to be used for links to the current resources and as a base for constructing ...
virtual const QString templatePath(const QgsServerApiContext &context) const
Returns the HTML template path for the handler in the given context.
virtual const QString staticPath(const QgsServerApiContext &context) const
Returns the absolute path to the base directory where static resources for this handler are stored in...
virtual QVariantMap values(const QgsServerApiContext &context) const
Analyzes the incoming request context and returns the validated parameter map, throws QgsServerApiBad...
static QgsServerOgcApi::Profile profileFromString(const QString &profile, bool &ok)
Returns the Profile from the string representation in profile, or Profile::None if the string was not...
QString headerLink(const QgsServerApiContext &context, const QgsServerOgcApi::Rel &linkType=QgsServerOgcApi::Rel::self, const QgsServerOgcApi::ContentType contentType=QgsServerOgcApi::ContentType::JSON, const QgsServerOgcApi::Profile &profile=QgsServerOgcApi::Profile::Unset, const QString &title="") const
Builds and returns a header link to the resource.
json jsonTags() const
Returns tags as JSON.
void htmlDump(const json &data, const QgsServerApiContext &context) const
Writes data as HTML to the response stream in context using a template.
virtual QgsServerOgcApi::ContentType defaultContentType() const
Returns the default response content type in case the client did not specifically ask for any particu...
QgsServerOgcApi::ContentType contentTypeFromRequest(const QgsServerRequest *request) const
Returns the content type from the request.
virtual QgsServerOgcApi::Rel linkType() const =0
Main role for the resource link.
virtual json schema(const QgsServerApiContext &context) const
Returns handler information from the context for the OPENAPI description (id, description and other m...
virtual QStringList tags() const
Tags.
void setContentTypes(const QList< QgsServerOgcApi::ContentType > &contentTypes)
Set the content types to contentTypes.
void write(json &data, const QgsServerApiContext &context, const json &htmlMetadata=nullptr) const
Writes data to the context response stream, content-type is calculated from the context request,...
QList< QgsServerOgcApi::ContentType > contentTypes() const
Returns the list of content types this handler can serve, default to JSON and HTML.
virtual std::string linkTitle() const =0
Title for the handler link.
virtual QList< QgsServerQueryStringParameter > parameters(const QgsServerApiContext &context) const
Returns a list of query string parameters.
virtual std::string operationId() const =0
Returns the operation id for template file names and other internal references.
static json defaultResponse()
Returns the defaultResponse as JSON.
QgsVectorLayer * layerFromContext(const QgsServerApiContext &context) const
Returns a vector layer instance from the "collectionId" parameter of the path in the given context,...
QList< QgsServerOgcApi::Profile > profilesFromRequest(const QgsServerRequest *request) const
Return a list of the profiles in the request, extracted from the "profile" query parameter.
QString contentTypeForAccept(const QString &accept) const
Looks for the first ContentType match in the accept header and returns its mime type,...
virtual void handleRequest(const QgsServerApiContext &context) const
Handles the request within its context.
json link(const QgsServerApiContext &context, const QgsServerOgcApi::Rel &linkType=QgsServerOgcApi::Rel::self, const QgsServerOgcApi::ContentType contentType=QgsServerOgcApi::ContentType::JSON, const std::string &title="") const
Builds and returns a link to the resource.
json links(const QgsServerApiContext &context) const
Returns all the links for the given request context.
static QString parentLink(const QUrl &url, int levels=1)
Returns a link to the parent page up to levels in the HTML hierarchy from the given url,...
virtual QRegularExpression path() const =0
URL pattern for this handler, named capture group are automatically extracted and returned by values(...
void setContentTypesInt(const QList< int > &contentTypes)
Set the content types to contentTypes.
static QgsVectorLayer * layerFromCollectionId(const QgsServerApiContext &context, const QString &collectionId)
Returns a vector layer from the collectionId in the given context.
static QUrl sanitizeUrl(const QUrl &url)
Returns a sanitized url with extra slashes removed and the path URL component that always starts with...
static QString contentTypeToExtension(const QgsServerOgcApi::ContentType &ct)
Returns the file extension for a ct (Content-Type).
static const QMap< QgsServerOgcApi::ContentType, QStringList > contentTypeMimes()
Returns a map of contentType => list of mime types.
ContentType
Media types used for content negotiation, insert more specific first.
@ SCHEMA_JSON
"application/schema+json"
@ OPENAPI3
"application/openapi+json;version=3.0"
@ FLATGEOBUF
"application/flatgeobuf"
static QString contentTypeToString(const QgsServerOgcApi::ContentType &ct)
Returns the string representation of a ct (Content-Type) attribute.
static QString profileToString(const QgsServerOgcApi::Profile &profile)
Returns a string representation of the profile.
Rel
Rel link types.
@ alternate
Refers to a substitute for this context.
@ self
Conveys an identifier for the link’s context.
static std::string contentTypeToStdString(const QgsServerOgcApi::ContentType &ct)
Returns the string representation of a ct (Content-Type) attribute.
static std::string mimeType(const QgsServerOgcApi::ContentType &contentType)
Returns the mime-type for the contentType or an empty string if not found.
Profile
JSON profile.
@ Rfc7946
GeoJSON profile according to RFC7946.
@ RelAsUri
JSON responses that include URI for referenced resources http://www.opengis.net/def/profile/ogc/0/rel...
@ RelAsLink
JSON responses that include links for referenced resources http://www.opengis.net/def/profile/ogc/0/r...
@ RelAsKey
JSON responses that include key for referenced resources http://www.opengis.net/def/profile/ogc/0/rel...
static std::string relToString(const QgsServerOgcApi::Rel &rel)
Returns the string representation of rel attribute, to be used or "rel" link attribute in an OGC API ...
static const QHash< QgsServerOgcApi::ContentType, QList< QgsServerOgcApi::ContentType > > contentTypeAliases()
Returns contentType specializations (e.g.
static QgsServerOgcApi::ContentType contentTypeFromExtension(const std::string &extension)
Returns the Content-Type value corresponding to extension.
Defines requests passed to QgsService classes.
const QString queryParameter(const QString &name, const QString &defaultValue=QString()) const
Returns the query string parameter with the given name from the request URL, a defaultValue can be sp...
virtual QString header(const QString &name) const
Returns the header value.
QUrl url() const
Returns the request URL as seen by QGIS server.
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
virtual void setHeader(const QString &key, const QString &value)=0
Set a single header value replacing any existing value(s) for the same key.
virtual void setStatusCode(int code)=0
Set the http status code.
QString apiResourcesDirectory() const
Returns the server-wide base directory where HTML templates and static assets (e.g.
Represents a vector layer which manages a vector based dataset.
#define BUILTIN_UNREACHABLE
Definition qgis.h:8015