-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathGeoserver.py
3186 lines (2741 loc) · 103 KB
/
Geoserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# inbuilt libraries
import os
from typing import List, Optional, Set, Union, Dict, Iterable, Any
from pathlib import Path
# third-party libraries
import requests
from xmltodict import parse, unparse
# custom functions
from .Calculation_gdal import raster_value
from .Style import catagorize_xml, classified_xml, coverage_style_xml, outline_only_xml
from .supports import prepare_zip_file, is_valid_xml, is_surrounded_by_quotes
def _parse_request_options(request_options: Dict[str, Any]):
"""
Parse request options.
Parameters
----------
request_options : dict
The request options to parse.
Returns
-------
dict
The parsed request options.
"""
return request_options if request_options is not None else {}
# Custom exceptions.
class GeoserverException(Exception):
"""
Custom exception for Geoserver errors.
Parameters
----------
status : int
The status code of the error.
message : str
The error message.
"""
def __init__(self, status, message):
self.status = status
self.message = message
super().__init__(f"Status : {self.status} - {self.message}")
# call back class for reading the data
class DataProvider:
"""
Data provider for reading data.
Parameters
----------
data : str
The data to be read.
"""
def __init__(self, data):
self.data = data
self.finished = False
def read_cb(self, size):
"""
Read callback.
Parameters
----------
size : int
The size of the data to read.
Returns
-------
str
The read data.
"""
assert len(self.data) <= size
if not self.finished:
self.finished = True
return self.data
else:
# Nothing more to read
return ""
# callback class for reading the files
class FileReader:
"""
File reader for reading files.
Parameters
----------
fp : file object
The file object to read from.
"""
def __init__(self, fp):
self.fp = fp
def read_callback(self, size):
"""
Read callback.
Parameters
----------
size : int
The size of the data to read.
Returns
-------
str
The read data.
"""
return self.fp.read(size)
class Geoserver:
"""
Geoserver class to interact with GeoServer REST API.
Attributes
----------
service_url : str
The URL for the GeoServer instance.
username : str
Login name for session.
password: str
Password for session.
request_options : dict
Additional parameters to be sent with each request.
"""
def __init__(
self,
service_url: str = "http://localhost:8080/geoserver", # default deployment url during installation
username: str = "admin", # default username during geoserver installation
password: str = "geoserver", # default password during geoserver installation
request_options: Dict[str, Any] = None # additional parameters to be sent with each request
):
self.service_url = service_url
self.username = username
self.password = password
self.request_options = request_options if request_options is not None else {}
def _requests(self,
method: str,
url: str,
**kwargs) -> requests.Response:
"""
Convenience wrapper to the requests library which automatically handles the authentication, as well as additional options to be passed to each request.
Parameters
----------
method : str
Which method to use (`get`, `post`, `put`, `delete`)
url : str
URL to which to make the request
kwargs : dict
Additional arguments to pass to the request.
Returns
-------
requests.Response
The response object.
"""
if method.lower() == "post":
return requests.post(url, auth=(self.username, self.password), **kwargs, **self.request_options)
elif method.lower() == "get":
return requests.get(url, auth=(self.username, self.password), **kwargs, **self.request_options)
elif method.lower() == "put":
return requests.put(url, auth=(self.username, self.password), **kwargs, **self.request_options)
elif method.lower() == "delete":
return requests.delete(url, auth=(self.username, self.password), **kwargs, **self.request_options)
# _______________________________________________________________________________________________
#
# GEOSERVER AND SERVER SPECIFIC METHODS
# _______________________________________________________________________________________________
#
def get_manifest(self):
"""
Returns the manifest of the GeoServer. The manifest is a JSON of all the loaded JARs on the GeoServer server.
Returns
-------
dict
The manifest of the GeoServer.
"""
url = "{}/rest/about/manifest.json".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_version(self):
"""
Returns the version of the GeoServer as JSON. It contains only the details of the high level components: GeoServer, GeoTools, and GeoWebCache.
Returns
-------
dict
The version information of the GeoServer.
"""
url = "{}/rest/about/version.json".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_status(self):
"""
Returns the status of the GeoServer. It shows the status details of all installed and configured modules.
Returns
-------
dict
The status of the GeoServer.
"""
url = "{}/rest/about/status.json".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_system_status(self):
"""
Returns the system status of the GeoServer. It returns a list of system-level information. Major operating systems (Linux, Windows, and MacOS) are supported out of the box.
Returns
-------
dict
The system status of the GeoServer.
"""
url = "{}/rest/about/system-status.json".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def reload(self):
"""
Reloads the GeoServer catalog and configuration from disk.
This operation is used in cases where an external tool has modified the on-disk configuration. This operation will also force GeoServer to drop any internal caches and reconnect to all data stores.
Returns
-------
str
The status code of the reload operation.
"""
url = "{}/rest/reload".format(self.service_url)
r = self._requests("post", url)
if r.status_code == 200:
return "Status code: {}".format(r.status_code)
else:
raise GeoserverException(r.status_code, r.content)
def reset(self):
"""
Resets all store, raster, and schema caches. This operation is used to force GeoServer to drop all caches and store connections and reconnect to each of them the next time they are needed by a request. This is useful in case the stores themselves cache some information about the data structures they manage that may have changed in the meantime.
Returns
-------
str
The status code of the reset operation.
"""
url = "{}/rest/reset".format(self.service_url)
r = self._requests("post", url)
if r.status_code == 200:
return "Status code: {}".format(r.status_code)
else:
raise GeoserverException(r.status_code, r.content)
# _______________________________________________________________________________________________
#
# WORKSPACES
# _______________________________________________________________________________________________
#
def get_default_workspace(self):
"""
Returns the default workspace.
Returns
-------
dict
The default workspace.
"""
url = "{}/rest/workspaces/default".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_workspace(self, workspace):
"""
Get the name of a workspace if it exists.
Parameters
----------
workspace : str
The name of the workspace.
Returns
-------
dict
The workspace information.
"""
url = "{}/rest/workspaces/{}.json".format(self.service_url, workspace)
r = self._requests("get", url, params={"recurse": "true"})
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_workspaces(self):
"""
Returns all the workspaces.
Returns
-------
dict
All the workspaces.
"""
url = "{}/rest/workspaces".format(self.service_url)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def set_default_workspace(self, workspace: str):
"""
Set the default workspace.
Parameters
----------
workspace : str
The name of the workspace to set as default.
Returns
-------
str
The status code of the operation.
"""
url = "{}/rest/workspaces/default".format(self.service_url)
data = "<workspace><name>{}</name></workspace>".format(workspace)
r = self._requests(
"put",
url,
data=data,
headers={"content-type": "text/xml"}
)
if r.status_code == 200:
return "Status code: {}, default workspace {} set!".format(
r.status_code, workspace
)
else:
raise GeoserverException(r.status_code, r.content)
def create_workspace(self, workspace: str):
"""
Create a new workspace in GeoServer. The GeoServer workspace URL will be the same as the name of the workspace.
Parameters
----------
workspace : str
The name of the workspace to create.
Returns
-------
str
The status code and message of the operation.
"""
url = "{}/rest/workspaces".format(self.service_url)
data = "<workspace><name>{}</name></workspace>".format(workspace)
headers = {"content-type": "text/xml"}
r = self._requests("post", url, data=data, headers=headers)
if r.status_code == 201:
return "{} Workspace {} created!".format(r.status_code, workspace)
else:
raise GeoserverException(r.status_code, r.content)
def delete_workspace(self, workspace: str):
"""
Delete a workspace.
Parameters
----------
workspace : str
The name of the workspace to delete.
Returns
-------
str
The status code and message of the operation.
"""
payload = {"recurse": "true"}
url = "{}/rest/workspaces/{}".format(self.service_url, workspace)
r = self._requests("delete", url, params=payload)
if r.status_code == 200:
return "Status code: {}, delete workspace".format(r.status_code)
else:
raise GeoserverException(r.status_code, r.content)
# _______________________________________________________________________________________________
#
# DATASTORES
# _______________________________________________________________________________________________
#
def get_datastore(self, store_name: str, workspace: Optional[str] = None):
"""
Return the data store in a given workspace. If workspace is not provided, it will take the default workspace.
Parameters
----------
store_name : str
The name of the data store.
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The data store information.
"""
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores/{}".format(
self.service_url, workspace, store_name
)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_datastores(self, workspace: Optional[str] = None):
"""
List all data stores in a workspace. If workspace is not provided, it will list all the datastores inside the default workspace.
Parameters
----------
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The list of data stores.
"""
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores.json".format(
self.service_url, workspace
)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
# _______________________________________________________________________________________________
#
# COVERAGE STORES
# _______________________________________________________________________________________________
#
def get_coveragestore(
self, coveragestore_name: str, workspace: Optional[str] = None
):
"""
Returns the store name if it exists.
Parameters
----------
coveragestore_name : str
The name of the coverage store.
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The coverage store information.
"""
payload = {"recurse": "true"}
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/coveragestores/{}.json".format(
self.service_url, workspace, coveragestore_name
)
r = self._requests(method="get", url=url, params=payload)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_coveragestores(self, workspace: str = None):
"""
Returns all the coverage stores inside a specific workspace.
Parameters
----------
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The list of coverage stores.
"""
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/coveragestores".format(self.service_url, workspace)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def create_coveragestore(
self,
path,
workspace: Optional[str] = None,
layer_name: Optional[str] = None,
file_type: str = "GeoTIFF",
content_type: str = "image/tiff",
):
"""
Creates the coverage store; Data will be uploaded to the server.
Parameters
----------
path : str
The path to the file.
workspace : str, optional
The name of the workspace.
layer_name : str, optional
The name of the coverage store. If not provided, parsed from the file name.
file_type : str
The type of the file.
content_type : str
The content type of the file.
Returns
-------
dict
The response from the server.
Notes
-----
the path to the file and file_type indicating it is a geotiff, arcgrid or other raster type
"""
if path is None:
raise Exception("You must provide the full path to the raster")
if workspace is None:
workspace = "default"
if layer_name is None:
layer_name = os.path.basename(path)
f = layer_name.split(".")
if len(f) > 0:
layer_name = f[0]
file_type = file_type.lower()
url = "{0}/rest/workspaces/{1}/coveragestores/{2}/file.{3}?coverageName={2}".format(
self.service_url, workspace, layer_name, file_type
)
headers = {"content-type": content_type, "Accept": "application/json"}
r = None
with open(path, "rb") as f:
r = self._requests(method="put", url=url, data=f, headers=headers)
if r.status_code == 201:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def publish_time_dimension_to_coveragestore(
self,
store_name: Optional[str] = None,
workspace: Optional[str] = None,
presentation: Optional[str] = "LIST",
units: Optional[str] = "ISO8601",
default_value: Optional[str] = "MINIMUM",
content_type: str = "application/xml; charset=UTF-8",
):
"""
Create time dimension in coverage store to publish time series in GeoServer.
Parameters
----------
store_name : str, optional
The name of the coverage store.
workspace : str, optional
The name of the workspace.
presentation : str, optional
The presentation style.
units : str, optional
The units of the time dimension.
default_value : str, optional
The default value of the time dimension.
content_type : str
The content type of the request.
Returns
-------
dict
The response from the server.
Notes
-----
More about time support in geoserver WMS you can read here:
https://docs.geoserver.org/master/en/user/services/wms/time.html
"""
url = "{0}/rest/workspaces/{1}/coveragestores/{2}/coverages/{2}".format(
self.service_url, workspace, store_name
)
headers = {"content-type": content_type}
time_dimension_data = (
"<coverage>"
"<enabled>true</enabled>"
"<metadata>"
"<entry key='time'>"
"<dimensionInfo>"
"<enabled>true</enabled>"
"<presentation>{}</presentation>"
"<units>{}</units>"
"<defaultValue>"
"<strategy>{}</strategy>"
"</defaultValue>"
"</dimensionInfo>"
"</entry>"
"</metadata>"
"</coverage>".format(presentation, units, default_value)
)
r = self._requests(
method="put", url=url, data=time_dimension_data, headers=headers
)
if r.status_code in [200, 201]:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
# _______________________________________________________________________________________________
#
# LAYERS
# _______________________________________________________________________________________________
#
def get_layer(self, layer_name: str, workspace: Optional[str] = None):
"""
Returns the layer by layer name.
Parameters
----------
layer_name : str
The name of the layer.
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The layer information.
"""
url = "{}/rest/layers/{}".format(self.service_url, layer_name)
if workspace is not None:
url = "{}/rest/workspaces/{}/layers/{}".format(
self.service_url, workspace, layer_name
)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_layers(self, workspace: Optional[str] = None):
"""
Get all the layers from GeoServer. If workspace is None, it will list all the layers from GeoServer.
Parameters
----------
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The list of layers.
"""
url = "{}/rest/layers".format(self.service_url)
if workspace is not None:
url = "{}/rest/workspaces/{}/layers".format(self.service_url, workspace)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def delete_layer(self, layer_name: str, workspace: Optional[str] = None):
"""
Delete a layer.
Parameters
----------
layer_name : str
The name of the layer to delete.
workspace : str, optional
The name of the workspace.
Returns
-------
str
The status code and message of the operation.
"""
payload = {"recurse": "true"}
url = "{}/rest/workspaces/{}/layers/{}".format(
self.service_url, workspace, layer_name
)
if workspace is None:
url = "{}/rest/layers/{}".format(self.service_url, layer_name)
r = self._requests(method="delete", url=url, params=payload)
if r.status_code == 200:
return "Status code: {}, delete layer".format(r.status_code)
else:
raise GeoserverException(r.status_code, r.content)
# _______________________________________________________________________________________________
#
# LAYER GROUPS
# _______________________________________________________________________________________________
#
def get_layergroups(self, workspace: Optional[str] = None):
"""
Returns all the layer groups from GeoServer. If workspace is None, it will list all the layer groups from GeoServer.
Parameters
----------
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The list of layer groups.
Notes
-----
If workspace is None, it will list all the layer groups from geoserver.
"""
url = "{}/rest/layergroups".format(self.service_url)
if workspace is not None:
url = "{}/rest/workspaces/{}/layergroups".format(
self.service_url, workspace
)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def get_layergroup(self, layer_name: str, workspace: Optional[str] = None):
"""
Returns the layer group by layer group name.
Parameters
----------
layer_name : str
The name of the layer group.
workspace : str, optional
The name of the workspace.
Returns
-------
dict
The layer group information.
"""
url = "{}/rest/layergroups/{}".format(self.service_url, layer_name)
if workspace is not None:
url = "{}/rest/workspaces/{}/layergroups/{}".format(
self.service_url, workspace, layer_name
)
r = self._requests("get", url)
if r.status_code == 200:
return r.json()
else:
raise GeoserverException(r.status_code, r.content)
def create_layergroup(
self,
name: str = "geoserver-rest-layergroup",
mode: str = "single",
title: str = "geoserver-rest layer group",
abstract_text: str = "A new layergroup created with geoserver-rest python package",
layers: List[str] = [],
workspace: Optional[str] = None,
formats: str = "html",
metadata: List[dict] = [],
keywords: List[str] = [],
) -> str:
"""
Creates the Layergroup.
Parameters
----------
name : str
The name of the layer group.
mode : str
The mode of the layer group.
title : str
The title of the layer group.
abstract_text : str
The abstract text of the layer group.
layers : list
The list of layers in the layer group.
workspace : str, optional
The name of the workspace.
formats : str, optional
The format of the layer group.
metadata : list, optional
The metadata of the layer group.
keywords : list, optional
The keywords of the layer group.
Returns
-------
str
The URL of the created layer group.
Notes
-----
title is a human readable text for the layergroup
abstract_text is a long text, like a brief info about the layergroup
workspace is Optional(Global Layergroups don't need workspace).A layergroup can exist without a workspace.
"""
assert isinstance(name, str), "Name must be of type String:''"
assert isinstance(mode, str), "Mode must be of type String:''"
assert isinstance(title, str), "Title must be of type String:''"
assert isinstance(abstract_text, str), "Abstract text must be of type String:''"
assert isinstance(formats, str), "Format must be of type String:''"
assert isinstance(
metadata, list
), "Metadata must be of type List of dict:[{'about':'geoserver rest data metadata','content_url':'link to content url'}]"
assert isinstance(
keywords, list
), "Keywords must be of type List:['keyword1','keyword2'...]"
assert isinstance(
layers, list
), "Layers must be of type List:['layer1','layer2'...]"
if workspace:
assert isinstance(workspace, str), "Workspace must be of type String:''"
# check if the workspace is valid in GeoServer
if self.get_workspace(workspace) is None:
raise Exception("Workspace is not valid in GeoServer Instance")
supported_modes: Set = {
"single",
"opaque",
"named",
"container",
"eo",
}
supported_formats: Set = {"html", "json", "xml"}
if mode.lower() != "single" and mode.lower() not in supported_modes:
raise Exception(
f"Mode not supported. Acceptable modes are : {supported_modes}"
)
if formats.lower() != "html" and formats.lower() not in supported_formats:
raise Exception(
f"Format not supported. Acceptable formats are : {supported_formats}"
)
# check if it already exist in GeoServer
try:
existing_layergroup = self.get_layergroup(name, workspace=workspace)
except GeoserverException:
existing_layergroup = None
if existing_layergroup is not None:
raise Exception(f"Layergroup: {name} already exist in GeoServer instance")
if len(layers) == 0:
raise Exception("No layer provided!")
else:
for layer in layers:
# check if it is valid in geoserver
try:
# Layer check
self.get_layer(
layer_name=layer,
workspace=workspace if workspace is not None else None,
)
except GeoserverException:
try:
# Layer group check
self.get_layergroup(
layer_name=layer,
workspace=workspace if workspace is not None else None,
)
except GeoserverException:
raise Exception(
f"Layer: {layer} is not a valid layer in the GeoServer instance"
)
skeleton = ""
if workspace:
skeleton += f"<workspace><name>{workspace}</name></workspace>"
# metadata structure = [{about:"",content_url:""},{...}]
metadata_xml_list = []
if len(metadata) >= 1:
for meta in metadata:
metadata_about = meta.get("about")
metadata_content_url = meta.get("content_url")
metadata_xml_list.append(
f"""
<metadataLink>
<type>text/plain</type>
<about>{metadata_about}</about>
<metadataType>ISO19115:2003</metadataType>
<content>{metadata_content_url}</content>
</metadataLink>
"""
)
metadata_xml = f"<metadataLinks>{''.join(['{}'] * len(metadata_xml_list)).format(*metadata_xml_list)}</metadataLinks>"
skeleton += metadata_xml
layers_xml_list: List[str] = []
for layer in layers:
published_type = "layer"
try:
# Layer check
self.get_layer(
layer_name=layer,
workspace=workspace if workspace is not None else None,
)
except GeoserverException: # It's a layer group
published_type = "layerGroup"
layers_xml_list.append(
f"""<published type="{published_type}">
<name>{layer}</name>
<link>{self.service_url}/layers/{layer}.xml</link>
</published>
"""
)
layers_xml: str = f"<publishables>{''.join(['{}'] * len(layers)).format(*layers_xml_list)}</publishables>"
skeleton += layers_xml
if len(keywords) >= 1:
keyword_xml_list: List[str] = [
f"<keyword>{keyword}</keyword>" for keyword in keywords
]
keywords_xml: str = f"<keywords>{''.join(['{}'] * len(keywords)).format(*keyword_xml_list)}</keywords>"
skeleton += keywords_xml
data = f"""