-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathManageLayersService.groovy
1564 lines (1316 loc) · 59.2 KB
/
ManageLayersService.groovy
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
/*
* Copyright (C) 2016 Atlas of Living Australia
* All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
package au.org.ala.spatial
import au.org.ala.spatial.grid.Bil2diva
import au.org.ala.spatial.grid.Diva2bil
import au.org.ala.spatial.intersect.Grid
import au.org.ala.spatial.util.UploadSpatialResource
import grails.converters.JSON
import groovy.sql.Sql
import groovy.util.logging.Slf4j
import org.apache.commons.httpclient.methods.FileRequestEntity
import org.apache.commons.httpclient.methods.StringRequestEntity
import org.apache.commons.io.FileUtils
import org.apache.commons.lang.StringUtils
import org.geotools.data.shapefile.ShapefileDataStore
import org.json.simple.JSONObject
import org.json.simple.JSONValue
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.feature.type.AttributeDescriptor
import org.springframework.scheduling.annotation.Scheduled
import java.nio.file.Files
import java.nio.file.attribute.BasicFileAttributes
@Slf4j
class ManageLayersService {
def dataSource
FieldService fieldService
LayerService layerService
SpatialObjectsService spatialObjectsService
TasksService tasksService
SpatialConfig spatialConfig
PublishService publishService
def listUploadedFiles() {
def list = []
//get all uploaded files
def layersDir = spatialConfig.data.dir
def path = new File(layersDir + "/uploads/")
if (path.exists()) {
for (File f : path.listFiles()) {
if (f.isDirectory()) {
log.debug 'getting ' + f.getName()
def upload = getUpload(f.getName())
if (upload.size() > 0) {
list.add(upload)
}
}
}
}
list
}
Map getUpload(String uploadId, boolean canRetry = true) {
def upload = [:]
String layersDir = spatialConfig.data.dir
File f = new File(layersDir + "/uploads/" + uploadId)
List fields = []
if (f.exists()) {
f.listFiles().each { file ->
if (file.getPath().toLowerCase().endsWith("original.name")) {
upload.put("raw_id", uploadId)
upload.put("created", Files.readAttributes(file.toPath(), BasicFileAttributes.class).creationTime())
try {
def layerIdFile = new File(layersDir + "/uploads/" + uploadId + "/layer.id")
if (layerIdFile.exists()) {
upload.put("layer_id", layerIdFile.text)
}
def originalNameFile = new File(layersDir + "/uploads/" + uploadId + "/original.name")
if (originalNameFile.exists()) {
String originalName = originalNameFile.text
upload.put("filename", originalName)
//default name (unique) and displayname
def idx = 1
def cleanName = originalName.toLowerCase().replaceAll('[^0-9a-z_]', '_').replace('__', '_').replace('__', '_')
def checkName = cleanName
while (layerService.getLayerByName(checkName) != null) {
idx = idx + 1
checkName = cleanName + '_' + idx
}
upload.put("name", checkName)
upload.put("displayname", originalName)
}
File distributionFile = new File(layersDir + "/uploads/" + uploadId + "/distribution.id")
if (distributionFile.exists()) {
upload.put("data_resource_uid", distributionFile.text)
}
File checklistFile = new File(layersDir + "/uploads/" + uploadId + "/checklist.id")
if (checklistFile.exists()) {
upload.put("checklist", checklistFile.text)
}
List<Task> creationTask = Task.findAllByNameAndTag('LayerCreation', uploadId)
if (creationTask.size() > 0) {
if (creationTask.get(0).status < 2) {
upload.put("layer_creation", "running")
} else if (creationTask.get(0).status == 2) {
upload.put("layer_creation", "cancelled")
} else if (creationTask.get(0).status == 3) {
upload.put("layer_creation", "error")
} //else finished
}
} catch (IOException e) {
log.error "error reading layer.id file in: " + f.getPath(), e
}
} else if (file.getName().startsWith("field.id.")) {
fields.add(fieldService.getFieldById(file.getName().substring("field.id.".length()), false))
upload.put("fields", fields)
}
}
if (!upload.containsKey('filename')) {
// process manually uploaded file
processUpload(f, f.getName())
// try again
if (canRetry) {
upload = getUpload(uploadId, false)
}
}
}
//no upload dir, look in existing layers, at layer.id
if (!upload.containsKey("raw_id")) {
try {
Layers layer = layerService.getLayerById(Integer.parseInt(uploadId))
if (layer != null) {
upload.put("raw_id", uploadId)
upload.put("layer_id", uploadId)
upload.put("filename", "")
List<Fields> fieldList = fieldService.getFields()
for (Fields fs : fieldList) {
if (fs.getSpid() == uploadId) {
fields.add(fs)
}
}
upload.put("fields", fields)
}
} catch (Exception ignored) {
}
}
return upload
}
//files manually added to layersDir/upload/ need processing
def processUpload(File pth, String newName) {
if (pth.exists()) {
def columns = []
String name = ''
File shp = null
File hdr = null
File bil = null
File grd = null
def count = 0
//flatten directories
def moved = true
while (moved) {
moved = false
pth.listFiles().each { f ->
if (f.isDirectory()) {
f.listFiles().each { sf ->
try {
FileUtils.moveToDirectory(sf, f.getParentFile(), false)
} catch (IOException ignored) {
// try a copy + delete
if (sf.isFile()) {
FileUtils.copyFileToDirectory(sf, f.getParentFile())
} else if (sf.isDirectory()) {
FileUtils.copyDirectoryToDirectory(sf, f.getParentFile())
}
sf.delete()
}
}
f.delete()
moved = true
}
}
}
pth.listFiles().each { f ->
if (count == 0 && f.getPath().toLowerCase().endsWith(".shp")) {
shp = f
name = f.getName().substring(0, f.getName().length() - 4)
columns.addAll(getShapeFileColumns(f))
count = count + 1
} else if (f.getPath().toLowerCase().endsWith(".hdr")) {
bil = f
name = f.getName().substring(0, f.getName().length() - 4)
count = count + 1
} else if (f.getPath().toLowerCase().endsWith(".grd")) {
grd = f
}
log.debug("Files found..." + f.getName())
}
//diva to bil
if (grd != null && bil == null) {
log.debug("Converting DIVA to BIL")
def n = grd.getPath().substring(0, grd.getPath().length() - 4)
Diva2bil.diva2bil(n, n)
bil = n + '.hdr'
name = grd.getName().substring(0, grd.getName().length() - 4)
count = count + 1
}
//rename the file
if (count == 1) {
pth.listFiles().each { f ->
if (name != newName && f.getName().length() > 4 &&
f.getName().substring(0, f.getName().length() - 4) == name) {
def newF = new File(f.getParent() + "/" + f.getName().replace(name, newName))
if (newF.getPath() != f.getPath() && !newF.exists()) {
FileUtils.moveFile(f, newF)
log.debug("Moving file ${f.getName()} to ${newF.getName()}")
}
}
}
//store name
new File(pth.getPath() + "/original.name").write(name)
log.debug("Original file name stored..." + name)
}
shp = new File(pth.getPath() + "/" + newName + ".shp")
bil = new File(pth.getPath() + "/" + newName + ".bil")
def tif = new File(pth.getPath() + "/" + newName + ".tif")
if (!shp.exists() && bil.exists() && !tif.exists()) {
log.debug("BIL detected...")
bilToGTif(bil, tif)
} else {
log.debug("SHP: ${shp.getPath()}, TIF: ${tif.getPath()}, BIL: ${bil.getPath()}")
log.debug("SHP available: ${shp.exists()}, TIF available: ${tif.exists()}, BIL available: ${bil.exists()}")
}
def map = [:]
if (!shp.exists() && !tif.exists()) {
log.error("No SHP or TIF available....")
map.put("error", "no layer files")
} else {
def errors = publishService.layerToGeoserver(new OutputParameter([
file: ([shp.exists() ? shp.getPath() : tif.getPath()] as JSON).toString()
]), null)
if (errors) {
log.error("Errors uploading to geoserver...." + errors.inspect())
map.put("error", errors.inspect())
} else {
map.put("raw_id", name)
map.put("columns", columns)
map.put("test_id", newName)
map.put("test_url",
spatialConfig.geoserver.url.toString() +
"/ALA/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:" + newName +
"&styles=&bbox=-180,-90,180,90&width=512&height=507&srs=EPSG:4326&format=application/openlayers")
new File(pth.getPath() + "/upload.json").write(JSONValue.toJSONString(map))
}
}
return map
} else {
log.error("Path does not exist..." + pth)
}
return [error: pth + " does not exist!" ]
}
/**
* sends a PUT or POST call to a URL using authentication and including a
* file upload
*
* @param type one of UploadSpatialResource.PUT for a PUT call or
* UploadSpatialResource.POST for a POST call
* @param url URL for PUT/POST call
* @param username account username for authentication
* @param password account password for authentication
* @param resourcepath local path to file to upload, null for no file to
* upload
* @param contenttype file MIME content type
* @return server response status code as String or empty String if
* unsuccessful
*/
def httpCall(String type, String url, String username, String password, String resourcepath, String resourcestr, String contenttype) {
def output = ["", ""]
def entity = null
if (resourcepath != null) {
def input = new File(resourcepath)
entity = new FileRequestEntity(input, contenttype)
} else if (resourcestr != null) {
try {
entity = new StringRequestEntity(resourcestr, contenttype, "UTF-8")
} catch (UnsupportedEncodingException e) {
log.error 'failed to encode contenttype: ' + contenttype, e
}
}
def response = Util.urlResponse(type, url, null, [:], entity, type == "PUT" ? true : null, username, password)
// Execute the request
if (response) {
if (response.statusCode) {
output[0] = String.valueOf(response.statusCode)
}
if (response.text) {
output[1] = response.text
}
//Add extra info
switch (response.statusCode) {
case "401":
output[1] = 'UNAUTHORIZED: ' + url
break
}
}
return output
}
def bilToGTif(File bil, File geotiff) {
log.debug("BIL conversion to GeoTIFF with gdal_translate...")
//bil 2 geotiff (?)
String[] cmd = [spatialConfig.gdal.dir.toString() + "/gdal_translate", "-of", "GTiff",
"-co", "COMPRESS=DEFLATE", "-co", "TILED=YES", "-co", "BIGTIFF=IF_SAFER",
bil.getPath(), geotiff.getPath()]
def builder = new ProcessBuilder(cmd)
builder.environment().putAll(System.getenv())
builder.redirectErrorStream(true)
try {
def proc = builder.start()
proc.waitFor()
} catch (Exception e) {
log.error "error running gdal_translate", e
}
cmd = [spatialConfig.gdal.dir + '/gdaladdo',
"-r", "cubic"
, geotiff.getPath()
, "2", "4", "8", "16", "32"]
builder = new ProcessBuilder(cmd)
builder.environment().putAll(System.getenv())
builder.redirectErrorStream(true)
try {
def proc = builder.start()
proc.waitFor()
} catch (Exception e) {
log.error "error running gdal_translate", e
}
}
List<Layers> getAllLayers(url) {
List<Layers> layers
List<Fields> fields
if (!url) {
layers = layerService.getLayersForAdmin()
fields = fieldService.getFields(true)
} else {
try {
layers = []
JSON.parse(Util.getUrl("${url}/layers?all=true")).each {
Layers layer = it as Layers
layer.id = it['id']
layers.push(layer)
}
} catch (err) {
log.error 'failed to get all layers', err
}
try {
fields = []
JSON.parse(Util.getUrl("${url}/fields?all=true")).each {
Fields field = it as Fields
field.id = it['id']
fields.push(field)
}
} catch (err) {
log.error 'failed to get all fields', err
}
}
List<Layers> list = []
layers.each { Layers l ->
//get fields
def fs = []
fields.each { f ->
if (f.getSpid() == String.valueOf(l.id)) {
fs.add(f)
}
}
l.fields = fs
list.add(l)
}
list
}
Map layerMap(String layerId) {
String layersDir = spatialConfig.data.dir
def map = [:]
Map upload = getUpload(layerId)
map.putAll(upload)
try {
JSONObject jo = (JSONObject) JSON.parse(new File(layersDir + "/uploads/" + layerId + "/upload.json").text)
map.putAll(jo)
} catch (Exception ignored) {
try {
Layers l = layerService.getLayerById(Integer.parseInt(layerId.replaceAll('[ec]l', "")), false)
if (l) {
if (!upload.name) {
map.putAll(l.properties)
map.put('id', l.id)
}
//try to get from layer info
map.put("raw_id", l.getId())
if (!map.containsKey("layer_id")) {
map.put("layer_id", l.getId() + "")
}
//TODO: stop this failing when the table is not yet created
//map.put("columns", layerDao.getLayerColumns(l.getId()));
map.put("test_url",
spatialConfig.geoserver.url +
"/ALA/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:" + l.getName() +
"&styles=&bbox" +
"=-180,-90,180,90&width=512&height=507&srs=EPSG:4326&format=application/openlayers")
}
} catch (Exception e2) {
log.error("failed to find layer for rawId: " + layerId)
}
}
map.put("has_layer", map.containsKey("layer_id"))
if (map.containsKey("layer_id")) {
Layers layer = layerService.getLayerById(Integer.parseInt(map.layer_id as String), false)
if(layer) {
map.putAll(layer.properties)
}
map.put("fields", Fields.findAllBySpid(map.get('layer_id')))
} else {
//fetch defaults
//extents
double[] extents = getExtents(layerId)
if (extents == null) {
extents = [-180, -90, 180, 90]
}
map.put("minlongitude", extents[0])
map.put("minlatitude", extents[1])
map.put("maxlongitude", extents[2])
map.put("maxlatitude", extents[3])
File shp = new File(layersDir + "/uploads/" + layerId + "/" + layerId + ".shp")
File bil = new File(layersDir + "/uploads/" + layerId + "/" + layerId + ".bil")
if (shp.exists()) {
List columns = getShapeFileColumns(shp)
map.put("columns", columns)
map.put("type", "Contextual")
} else if (bil.exists()) {
double[] minmax = Bil2diva.getMinMax(bil, spatialConfig.gdal.dir, spatialConfig.admin.timeout)
map.put("environmentalvaluemin", minmax[0])
map.put("environmentalvaluemax", minmax[1])
map.put("type", "Environmental")
}
map.put("enabled", true)
}
//get list of available classifications
Set<String> classifications = new HashSet<String>()
List<Layers> layers = layerService.getLayersForAdmin()
for (Layers l : layers) {
classifications.add(l.getClassification1() + " > " + l.getClassification2())
}
List<String> classes = new ArrayList<String>(classifications)
Collections.sort(classes)
map.put("classifications", classes)
map.remove('class')
map
}
def deleteLayer(String id) {
String layersDir = spatialConfig.data.dir
String geoserverUrl = spatialConfig.geoserver.url
String geoserverUsername = spatialConfig.geoserver.username
String geoserverPassword = spatialConfig.geoserver.password
Map map = null
try {
map = layerMap(id)
} catch (err) {
log.error 'failed to get layer map for layer to delete: ' + id, err
}
//fields
if (map != null && map.containsKey("fields")) {
List fields = (List) map.get("fields"); for (Object o : fields) {
if (o != null) {
Fields field = (Fields) o
fieldService.delete(field.getId())
// analysis files
String[] dirs = ["/standard_layer/"]
for (String d : dirs) {
File df = new File(layersDir + d)
if (df.exists()) {
File[] files = df.listFiles()
for (File f : files) {
if (f.isDirectory()) {
File[] files2 = f.listFiles()
for (File f2 : files2) {
if (f2.getName().startsWith(field.getId() + ".")) {
FileUtils.deleteQuietly(f2)
}
}
} else if (f.getName().startsWith(field.getId() + ".")) {
FileUtils.deleteQuietly(f)
}
}
}
}
// tabulation
//TODO:
// association distances
//TODO:
}
}
}
//layer
if (map != null && map.containsKey("layer_id")) {
String layerId = (String) map.get("layer_id")
String name = (String) map.get("name")
httpCall("DELETE",
geoserverUrl + "/rest/workspaces/ALA/datastores/" + name + "?recurse=true", ///external.shp",
geoserverUsername, geoserverPassword,
null, null,
"text/plain")
httpCall("DELETE",
geoserverUrl + "/rest/workspaces/ALA/coveragestores/" + name + "?recurse=true", //"/external.geotiff",
geoserverUsername, geoserverPassword,
null, null,
"text/plain")
// layers table
layerService.delete(layerId)
// layer files
String[] dirs = ["/layer/"]
for (String d : dirs) {
File dir = new File(layersDir + d)
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (f.getName().startsWith(name + ".")) {
FileUtils.deleteQuietly(f)
}
}
}
}
}
//layer id in raw upload
def allUploads = listUploadedFiles()
allUploads.each {
if (it.containsKey('layer_id') && it.layer_id == id) {
new File(spatialConfig.data.dir.toString() + "/uploads/" + it.raw_id + "/layer.id").delete()
}
}
//raw upload
//TODO: tidy messages for id == name (layer already deleted)
// String[] result;
// result = httpCall("DELETE",
// geoserverUrl + "/rest/workspaces/ALA/datastores/" + id + "?recurse=true", ///external.shp",
// geoserverUsername, geoserverPassword,
// null,null,
// "text/plain");
// result = httpCall("DELETE",
// geoserverUrl + "/rest/workspaces/ALA/coveragestores/" + id + "?recurse=true", //"/external.geotiff",
// geoserverUsername, geoserverPassword,
// null,null,
// "text/plain");
}
def deleteField(String fieldId) {
String layersDir = spatialConfig.data.dir
//fields
Fields field = fieldService.getFieldById(fieldId, false)
if (field != null) {
fieldService.delete(fieldId)
// analysis files
String[] dirs = ["/analysis/"]
for (String d : dirs) {
File[] files = new File(layersDir + d).listFiles()
for (int i = 0; files != null && i < files.length; i++) {
File f = files[i]
if (f.isDirectory()) {
File[] files2 = f.listFiles()
for (int j = 0; files2 != null && j < files.length; j++) {
File f2 = files2[j]
if (f2.getName().startsWith(field.getId() + ".")) {
//FileUtils.deleteQuietly(f2);
}
}
} else if (f.getName().startsWith(field.getId() + ".")) {
//FileUtils.deleteQuietly(f);
}
}
}
// tabulation
// association distances
}
}
def fieldMapDefault(String layerId) {
def layerMap = layerMap(layerId)
String layersDir = spatialConfig.data.dir
Map fieldMap = new HashMap()
fieldMap.putAll(layerMap)
//fix default layer name
if (layerMap.containsKey("displayname")) {
fieldMap.put("displayname", layerMap.get("displayname"))
fieldMap.put("name", layerMap.get("displayname"))
}
//fix default layer description
if (layerMap.containsKey("description")) {
fieldMap.put("desc", layerMap.get("displayname"))
}
fieldMap.remove("id")
fieldMap.put("raw_id", layerId)
int countInDB = fieldService.countBySpid(layerId)
boolean isContextual = "Contextual".equalsIgnoreCase(String.valueOf(layerMap.get("type")))
fieldMap.put("indb", countInDB == 0)
fieldMap.put("intersect", false) //countInDB == 0 && isContextual);
fieldMap.put("analysis", countInDB == 0)
fieldMap.put("addtomap", countInDB == 0)
fieldMap.put("enabled", true)
// convention of field name
def sid = fieldService.calculateNextSequenceId(layerId)
fieldMap.put("requestedId", (isContextual ? "cl" : "el") + sid + layerId)
//type
//Contextual and shapefile = c, Environmental = e, Contextual and grid file = a & b
if (isContextual) {
fieldMap.put("type", "c")
} else if (isContextual) {
fieldMap.put("type", "a")
} else {
fieldMap.put("type", "e")
}
File shp = new File(layersDir + "/uploads/" + layerId + "/" + layerId + ".shp")
File bil = new File(layersDir + "/uploads/" + layerId + "/" + layerId + ".bil")
File loadedShp = new File(layersDir + "/layer/" + layerMap.get('name') + ".shp")
//TODO: do not set defaults
fieldMap.put("filetype", "bil")
fieldMap.put("columns", [])
if (loadedShp.exists()) {
fieldMap.put("filetype", "shp")
List columns = getShapeFileColumns(loadedShp)
fieldMap.put("columns", columns)
} else if (shp.exists()) {
fieldMap.put("filetype", "shp")
List columns = getShapeFileColumns(shp)
fieldMap.put("columns", columns)
} else if (bil.exists()) {
// fieldMap.put("filetype", "bil");
// fieldMap.put("columns", [:]);
}
if (isContextual && fieldMap.containsKey("columns") && fieldMap.get("columns") != null &&
((List) fieldMap.get("columns")).size() > 0) {
fieldMap.put("sname", ((List) fieldMap.get("columns")).get(0))
//"sdesc" is optional
}
return fieldMap
}
double[] getExtents(String rawId) {
String geoserverUrl = spatialConfig.geoserver.url
String geoserverUsername = spatialConfig.geoserver.username
String geoserverPassword = spatialConfig.geoserver.password
double[] extents = null
try {
String[] out = httpCall("GET",
geoserverUrl + "/rest/workspaces/ALA/datastores/" + rawId + "/featuretypes/" + rawId + ".json",
geoserverUsername, geoserverPassword,
null,
null,
"text/plain")
JSONObject jo = (JSONObject) JSON.parse(out[1])
JSONObject bbox = (JSONObject) ((JSONObject) jo.get("featureType")).get("nativeBoundingBox")
extents = new double[4]
extents[0] = Double.parseDouble(bbox.get("minx").toString())
extents[1] = Double.parseDouble(bbox.get("miny").toString())
extents[2] = Double.parseDouble(bbox.get("maxx").toString())
extents[3] = Double.parseDouble(bbox.get("maxy").toString())
} catch (err) {
log.debug 'failed feature layer, try coverage layer ' + rawId
//try tif
String[] out = httpCall("GET",
geoserverUrl + "/rest/workspaces/ALA/coverages/" + rawId + ".json",
geoserverUsername, geoserverPassword,
null,
null,
"text/plain")
try {
JSONObject jo = (JSONObject) JSON.parse(out[1])
JSONObject bbox = (JSONObject) ((JSONObject) jo.get("coverage")).get("nativeBoundingBox")
extents = new double[4]
extents[0] = Double.parseDouble(bbox.get("minx").toString())
extents[1] = Double.parseDouble(bbox.get("miny").toString())
extents[2] = Double.parseDouble(bbox.get("maxx").toString())
extents[3] = Double.parseDouble(bbox.get("maxy").toString())
} catch (err2) {
log.error 'failed to parse bbox for upload id ' + rawId
}
}
return extents
}
/**
* Have to determine if it is creating a new field or editing an existing field
*
* Assumption:
* If it is field id, it is an 'edit an existing field' function
* If it is a layer id, then it should be 'create new field' function
*
* Since function fieldMapDefault creates a new 'requestId' ( assigned to id after ) with incremental sequence number
* So, if it is an edit function, the requestId should be unchanged.
*
*
* @param fieldId It is field id if starts with el/cl, otherwise layer id
* @return
*/
def fieldMap(String fieldId) {
def layer = layerService.getLayerById(Integer.parseInt(fieldService.getFieldById(fieldId, false).spid), false)
def map = fieldMapDefault(String.valueOf(layer.id))
map.put("layerName", layer.name) // layer name for wms requests
def field = fieldService.getFieldById(fieldId, false)
if (fieldId.startsWith('cl') || fieldId.startsWith('el')) {
//It stands for 'editing' not creating a new field
//Restore requestedId
map.put("requestedId", field.getId())
}
map.put("id", field.getId())
map.put("desc", field.getDesc())
map.put("name", field.getName())
map.put("sdesc", field.getSdesc())
map.put("sname", field.getSname())
map.put("spid", field.getSpid())
map.put("type", field.getType())
map.put("addtomap", field.addtomap)
map.put("analysis", field.analysis)
map.put("defaultlayer", field.defaultlayer)
map.put("enabled", field.enabled)
map.put("indb", field.indb)
map.put("intersect", field.intersect)
map.put("layerbranch", field.layerbranch)
map.put("namesearch", field.namesearch)
map.put("is_field", true)
map
}
/**
*
* @param map params without kv pair of checkbox
* @param id
* @param createTask
* @return
*/
def createOrUpdateLayer(Map map, String id, boolean createTask = true) {
// Unchecked checkbox won't be post via params
Map checkboxFields = [:]
checkboxFields["enabled"] = false
checkboxFields.each { key, value ->
if (!map.containsKey(key)) {
map.put(key,value)
}
}
Layers layer = Layers.get(id) ?: new Layers()
layer.properties.each {
if (map.containsKey(it.key)) {
layer.properties.put(it.key, map.get(it.key))
}
}
if (map.containsKey('id')) {
try {
layer.id = map.get('id') as Long
} catch (Exception ignored) {}
}
createOrUpdateLayer(layer, id, createTask)
}
def createOrUpdateLayer(Layers layer, String id, boolean createTask = true) {
Map retMap = [:]
retMap.put('layer_id', id)
if (!layer.name) {
retMap.put("error", "name parameter missing")
retMap.putAll(layerMap(String.valueOf(id)))
retMap.putAll(layer.properties)
} else {
//UPDATE
Integer intId = null
try {
//look for upload layer.id to use instead of upload id
File idFile = new File(spatialConfig.data.dir.toString() + "/uploads/" + id + "/layer.id")
if (idFile.exists()) {
//update id
layer.id = idFile.text
}
intId = layer.id
} catch (ignored) {
log.debug 'unable to read uploads layer.id for ' + id
}
if (id != null && id.isInteger() && Layers.countById(id)) {
//update select values
try {
//flag background processes that need running
// boolean updateIntersect = field.intersect != null && field.intersect != originalField.intersect && field.intersect
// boolean updateNameSearch = field.namesearch != null && field.namesearch != originalField.namesearch
//
// // remove duplicate association
// originalField = null
Fields.withTransaction {
if (!layer.save(flush: true, validate:true)) {
layer.errors.each {
log.error(it)
}
}
}
//record layer.id
FileUtils.write(new File(spatialConfig.data.dir.toString() + "/uploads/" + id + "/layer.id"), String.valueOf(layer.getId()))
retMap.put('message', 'Layer updated')
} catch (err) {
log.error 'error updating layer: ' + id, err
retMap.put('error', 'error updating layer: ' + err.getMessage())
}
} else {
try {
//defaults, in case of missing values
def defaultLayer = layerMap(id)
if (!layer.name) layer.name= defaultLayer.name
if (!layer.environmentalvaluemin) layer.environmentalvaluemin= defaultLayer.environmentalvaluemin
if (!layer.environmentalvaluemax) layer.environmentalvaluemax= defaultLayer.environmentalvaluemax
if (!layer.extents) layer.extents = defaultLayer.extents
if (!layer.domain) layer.domain = defaultLayer.domain
if (!layer.maxlatitude) layer.maxlatitude= Double.valueOf(defaultLayer.maxlatitude)
if (!layer.minlatitude) layer.minlatitude= Double.valueOf(defaultLayer.minlatitude)
if (!layer.maxlongitude) layer.maxlongitude= Double.valueOf(defaultLayer.maxlongitude)
if (!layer.minlongitude) layer.minlongitude= Double.valueOf(defaultLayer.minlongitude)
if (!layer.displayname) layer.displayname= defaultLayer.displayname
if (layer.enabled == null) layer.enabled = true
if (!layer.environmentalvalueunits) layer.environmentalvalueunits= defaultLayer.environmentalvalueunits
if (!layer.type) layer.type= defaultLayer.type
if (layerService.getLayerByName(layer.name.toString(), false) != null) {
retMap.put("error", "name: " + layer.name + " is not unique")
retMap.putAll(layerMap(String.valueOf(id)))
retMap.putAll(layer.properties)
retMap.put('id', layer.id)
}
//default values from the name
layer.displaypath = spatialConfig.geoserver.url +
"/gwc/service/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:" +
layer.name + "&format=image/png&styles="
if (!layer?.path_orig) {
layer.path_orig = 'layer/' + layer.name
}
layer.dt_added = new Date()
//attempt to set layer id
if (layer.requestedId) {
layer.setId(Long.parseLong(String.valueOf(layer.requestedId)))
} else {
Long nextId = null
Sql.newInstance(dataSource).query("SELECT nextval('layers_id_seq'::regclass)", { result ->
if (result.next()) {
nextId = result.getLong(1)
}
})
layer.setId(nextId)
}
//create default layers table entry, this updates layer.id
Task.withNewTransaction {
if (!layer.save(flush: true)) {
layer.errors.each {
log.error(it)
}
}
}
//record layer.id
FileUtils.write(new File(spatialConfig.data.dir.toString() + "/uploads/" + id + "/layer.id"), String.valueOf(layer.getId()))
if (createTask) {
tasksService.create('LayerCreation', id, [layerId: String.valueOf(layer.getId()), uploadId: String.valueOf(id)], null, null, null)
}