-
Notifications
You must be signed in to change notification settings - Fork 85
/
OrganismController.groovy
1540 lines (1383 loc) · 81.8 KB
/
OrganismController.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
package org.bbop.apollo
import grails.converters.JSON
import grails.transaction.NotTransactional
import grails.transaction.Transactional
import htsjdk.samtools.reference.FastaSequenceIndexCreator
import org.apache.shiro.web.servlet.ShiroHttpServletRequest
import org.bbop.apollo.gwt.shared.FeatureStringEnum
import org.bbop.apollo.gwt.shared.GlobalPermissionEnum
import org.bbop.apollo.gwt.shared.PermissionEnum
import org.bbop.apollo.gwt.shared.track.SequenceTypeEnum
import org.bbop.apollo.gwt.shared.track.TrackTypeEnum
import org.bbop.apollo.report.OrganismSummary
import org.bbop.apollo.track.TrackDefaults
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException
import org.codehaus.groovy.grails.web.json.JSONArray
import org.codehaus.groovy.grails.web.json.JSONObject
import org.restapidoc.annotation.RestApi
import org.restapidoc.annotation.RestApiMethod
import org.restapidoc.annotation.RestApiParam
import org.restapidoc.annotation.RestApiParams
import org.restapidoc.pojo.RestApiParamType
import org.restapidoc.pojo.RestApiVerb
import org.springframework.web.multipart.commons.CommonsMultipartFile
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.nio.file.FileSystems
import java.nio.file.Path
import static org.springframework.http.HttpStatus.NOT_FOUND
@RestApi(name = "Organism Services", description = "Methods for managing organisms")
@Transactional(readOnly = true)
class OrganismController {
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
def sequenceService
def permissionService
def requestHandlingService
def preferenceService
def organismService
def reportService
def configWrapperService
def trackService
def fileService
@RestApiMethod(description = "Remove an organism", path = "/organism/deleteOrganism", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "id", type = "string or number", paramType = RestApiParamType.QUERY, description = "Pass an Organism ID or commonName that corresponds to the organism to be removed")
, @RestApiParam(name = "organism", type = "string or number", paramType = RestApiParamType.QUERY, description = "Pass an Organism ID or commonName that corresponds to the organism to be removed")
])
@Transactional
def deleteOrganism() {
try {
JSONObject organismJson = permissionService.handleInput(request, params)
log.debug "deleteOrganism ${organismJson}"
log.debug "organism ID: ${organismJson.id}"
// backporting a bug here:
Organism organism = null
if(organismJson.containsKey("id")){
organism = Organism.findByCommonName(organismJson.id as String)
if(!organism){
organism = Organism.findById(organismJson.id as Long)
}
}
// backport a bug so that it doesn't break existing code
if(!organism && organismJson.containsKey("organism")){
organism = Organism.findByCommonName(organismJson.organism as String)
}
if (!organism) {
def error = [error: "Organism ${organismJson.id} not found"]
log.error(error.error)
render error as JSON
return
}
// to support webservice, get current user from session or input object
def currentUser = permissionService.getCurrentUser(organismJson)
String creatorMetaData = organism.getMetaData(FeatureStringEnum.CREATOR.value)
// only allow global admin or organism creator or organism administrative to delete the organism
if (!permissionService.hasGlobalPermissions(organismJson, GlobalPermissionEnum.ADMIN) && !(creatorMetaData && currentUser.id.toString() == creatorMetaData) && !permissionService.checkPermissions(organismJson, organism, PermissionEnum.ADMINISTRATE)) {
def error = [error: 'not authorized to delete organism']
log.error(error.error)
render error as JSON
return
}
UserOrganismPreference.deleteAll(UserOrganismPreference.findAllByOrganism(organism))
OrganismFilter.deleteAll(OrganismFilter.findAllByOrganism(organism))
organism.delete()
log.info "Success deleting organism: ${organismJson.organism}"
if (organism.directory.startsWith(trackService.commonDataDirectory)) {
log.info "Directoy is part of the common data directory ${trackService.commonDataDirectory}, so deleting ${organism.directory}"
File directoryToRemove = new File(organism.directory)
assert directoryToRemove.deleteDir()
}
findAllOrganisms()
}
catch (Exception e) {
def error = [error: 'problem deleting organism: ' + e]
log.error(error.error)
render error as JSON
}
}
@RestApiMethod(description = "Delete an organism along with its data directory and returns a JSON object containing properties of the deleted organism", path = "/organism/deleteOrganismWithSequence", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
, @RestApiParam(name = "id", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
])
@Transactional
def deleteOrganismWithSequence() {
JSONObject requestObject = permissionService.handleInput(request, params)
JSONObject responseObject = new JSONObject()
log.debug "deleteOrganismWithSequence ${requestObject}"
try {
//if (permissionService.isUserGlobalAdmin(permissionService.getCurrentUser(requestObject))) {
if (permissionService.hasGlobalPermissions(requestObject, GlobalPermissionEnum.ADMIN)) {
Organism organism = preferenceService.getOrganismForTokenInDB(requestObject.organism as String)
if(!organism){
organism = preferenceService.getOrganismForTokenInDB(requestObject.id as String)
}
if (organism) {
boolean dataAddedViaWebServices = organism.dataAddedViaWebServices == null ? false : organism.dataAddedViaWebServices
String organismDirectory = organism.directory
def organismAsJSON = organism as JSON
UserOrganismPreference.deleteAll(UserOrganismPreference.findAllByOrganism(organism))
OrganismFilter.deleteAll(OrganismFilter.findAllByOrganism(organism))
organism.delete()
if (dataAddedViaWebServices) {
log.debug "organism ${organism.id} was added via web services;"
File dataDirectory = new File(organismDirectory)
if (dataDirectory.deleteDir()) {
log.info "dataDirectory: ${organismDirectory} deleted successfully."
} else {
log.error "Could not delete data directory: ${organismDirectory}."
responseObject.put("warn", "Could not delete data directory: ${organismDirectory}")
}
} else {
log.warn "organism ${organism.id} was not added via web services; Organism deleted but cannot delete data directory ${organismDirectory}"
responseObject.put("warn", "Organism ${organism.id} was not added via web services; Organism deleted but cannot delete data directory ${organismDirectory}.")
File extendedDataDirectory = trackService.getExtendedDataDirectory(organism)
if (extendedDataDirectory.exists()) {
log.info "Extended data directory found: ${extendedDataDirectory.absolutePath}"
if (extendedDataDirectory.deleteDir()) {
log.info "extended data directory found and deleted"
} else {
log.error "Extended data directory found but could not be deleted"
responseObject.put("warn", responseObject.get("warn") + " Extended data directory found but could not be deleted.")
}
}
}
//render organismAsJSON
responseObject.put("organism", JSON.parse(organismAsJSON.toString()) as JSONObject)
log.info "Success deleting organism: ${requestObject.organism}"
} else {
log.error "Organism: ${requestObject.organism} not found"
responseObject.put("error", "Organism: ${requestObject.organism} not found.")
}
} else {
log.error "username not authorized to delete organism"
responseObject.put("error", "username not authorized to delete organism.")
}
} catch (Exception e) {
log.error(e.message)
responseObject.put("error", e.message)
}
render responseObject as JSON
}
@RestApiMethod(description = "Remove features from an organism", path = "/organism/deleteOrganismFeatures", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism.")
, @RestApiParam(name = "sequences", type = "string", paramType = RestApiParamType.QUERY, description = "(optional) Comma-delimited sequence names on that organism if only certain sequences should be deleted.")
])
@NotTransactional
def deleteOrganismFeatures() {
JSONObject organismJson = permissionService.handleInput(request, params)
if (organismJson.username == "" || organismJson.organism == "" || organismJson.password == "") {
def error = ['error': 'Empty fields in request JSON']
render error as JSON
log.error(error.error)
return
}
try {
if (!permissionService.hasPermissions(organismJson, PermissionEnum.ADMINISTRATE)) {
def error = [error: 'not authorized to delete all features from organism']
log.error(error.error)
render error as JSON
return
}
Organism organism = Organism.findByCommonName(organismJson.organism)
if (!organism) {
organism = Organism.findById(organismJson.organism)
}
if (!organism) {
throw new Exception("Can not find organism for ${organismJson.organism} to remove features of")
}
if (organismJson.sequences) {
List<String> sequenceNames = organismJson.sequences.toString().split(",")
List<Sequence> sequences = Sequence.findAllByOrganismAndNameInList(organism, sequenceNames)
organismService.deleteAllFeaturesForSequences(sequences)
} else {
organismService.deleteAllFeaturesForOrganism(organism)
}
render [:] as JSON
}
catch (e) {
def error = [error: 'problem removing organism features for organism: ' + e]
render error as JSON
e.printStackTrace()
log.error(error.error)
}
}
@RestApiMethod(description = "Adds an organism returning a JSON array of all organisms", path = "/organism/addOrganismWithSequence", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "species", type = "string", paramType = RestApiParamType.QUERY, description = "species name")
, @RestApiParam(name = "genus", type = "string", paramType = RestApiParamType.QUERY, description = "species genus")
, @RestApiParam(name = "blatdb", type = "string", paramType = RestApiParamType.QUERY, description = "filesystem path for a BLAT database (e.g. a .2bit file) if not uploaded")
, @RestApiParam(name = "publicMode", type = "boolean", paramType = RestApiParamType.QUERY, description = "a flag for whether the organism appears as in the public genomes list")
, @RestApiParam(name = "commonName", type = "string", paramType = RestApiParamType.QUERY, description = "commonName for an organism")
, @RestApiParam(name = "nonDefaultTranslationTable", type = "string", paramType = RestApiParamType.QUERY, description = "non-default translation table")
, @RestApiParam(name = "metadata", type = "string", paramType = RestApiParamType.QUERY, description = "organism metadata")
, @RestApiParam(name = "organismData", type = "file", paramType = RestApiParamType.QUERY, description = "zip or tar.gz compressed data directory (if other options not used). Blat data should include a .2bit suffix and be in a directory 'searchDatabaseData'")
, @RestApiParam(name = "sequenceData", type = "file", paramType = RestApiParamType.QUERY, description = "FASTA file (optionally compressed) to automatically upload with")
, @RestApiParam(name = "searchDatabaseData", type = "file", paramType = RestApiParamType.QUERY, description = "2bit file for blat search (optional)")
])
@Transactional
def addOrganismWithSequence() {
JSONObject returnObject = new JSONObject()
JSONObject requestObject = permissionService.handleInput(request, params)
log.info "Adding organism with SEQUENCE ${requestObject as String}"
String clientToken = requestObject.getString(FeatureStringEnum.CLIENT_TOKEN.value)
CommonsMultipartFile organismDataFile = request.getFile(FeatureStringEnum.ORGANISM_DATA.value)
CommonsMultipartFile sequenceDataFile = request.getFile(FeatureStringEnum.SEQUENCE_DATA.value)
CommonsMultipartFile searchDatabaseDataFile = request.getFile(FeatureStringEnum.SEARCH_DATABASE_DATA.value)
if (!requestObject.containsKey(FeatureStringEnum.ORGANISM_NAME.value)) {
returnObject.put("error", "/addOrganismWithSequence requires '${FeatureStringEnum.ORGANISM_NAME.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (organismDataFile == null && sequenceDataFile == null) {
returnObject.put("error", "/addOrganismWithSequence requires '${FeatureStringEnum.ORGANISM_DATA.value}' or ${FeatureStringEnum.SEQUENCE_DATA.value}.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (organismDataFile != null && sequenceDataFile != null) {
returnObject.put("error", "/addOrganismWithSequence requires ONLY one (not both) of '${FeatureStringEnum.ORGANISM_DATA.value}' or ${FeatureStringEnum.SEQUENCE_DATA.value}.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
try {
if (permissionService.isUserGlobalAdmin(permissionService.getCurrentUser(requestObject))) {
String organismName = requestObject.get(FeatureStringEnum.ORGANISM_NAME.value)
def organism = new Organism(
commonName: organismName,
directory: trackService.commonDataDirectory,
blatdb: requestObject.blatdb ?: "",
genus: requestObject.genus ?: "",
obsolete: false,
valid: true,
species: requestObject.species ?: "",
metadata: requestObject.metadata ? requestObject.metadata.toString() : "",
publicMode: requestObject.containsKey("publicMode") ? Boolean.valueOf(requestObject.publicMode as String) : false,
nonDefaultTranslationTable: requestObject.nonDefaultTranslationTable ?: null,
dataAddedViaWebServices: true
).save(failOnError: true, flush: true, insert: true)
User currentUser = permissionService.currentUser
String userId = null
if(currentUser){
userId = currentUser.id.toString()
}
else{
userId = requestObject.username as String
currentUser = User.findByUsername(userId)
userId = currentUser ? currentUser.id?.toString() : userId
}
organism.addMetaData("creator", userId)
File directory = trackService.getExtendedDataDirectory(organism)
if (directory.mkdirs() && directory.setWritable(true)) {
if (organismDataFile) {
log.debug "Successfully created directory ${directory.absolutePath}"
File archiveFile = new File(organismDataFile.getOriginalFilename())
organismDataFile.transferTo(archiveFile)
try {
fileService.decompress(archiveFile, directory.absolutePath, null, false)
log.debug "Adding ${organismName} with directory: ${directory.absolutePath}"
organism.directory = directory.absolutePath
// if directory has a "searchDatabaseData" directory then any file in that that is a 2bit is the blatdb
String blatdb = organismService.findBlatDB(directory.absolutePath)
if (blatdb) {
organism.blatdb = blatdb
}
organism.save()
sequenceService.loadRefSeqs(organism)
preferenceService.setCurrentOrganism(permissionService.getCurrentUser(requestObject), organism, clientToken)
findAllOrganisms()
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
organism.delete()
render returnObject
return
}
} else if (sequenceDataFile) {
SequenceTypeEnum sequenceTypeEnum = SequenceTypeEnum.getSequenceTypeForFile(sequenceDataFile.getOriginalFilename())
if (sequenceTypeEnum == null) {
returnObject.put("error", "Bad file input: " + sequenceDataFile.originalFilename)
render returnObject
return
}
// TODO: put this in a temp directory? ? ?
try {
File rawDirectory = new File(directory.absolutePath + "/seq")
assert rawDirectory.mkdir()
assert rawDirectory.setWritable(true)
File archiveFile = new File(rawDirectory.absolutePath + File.separator + organismName + "." + sequenceTypeEnum.suffix)
sequenceDataFile.transferTo(archiveFile)
organism.directory = directory.absolutePath
String fastaPath = rawDirectory.absolutePath + File.separator + organismName + ".fa"
// decompress if need be
if (sequenceTypeEnum.compression != null) {
List<String> fileNames = fileService.decompress(archiveFile, rawDirectory.absolutePath)
// move the filenames to the same original name, let's assume there is one
File oldFile = new File(fileNames[0])
assert oldFile.exists()
File newFile = new File(fastaPath)
oldFile.renameTo(newFile)
}
log.info "search db file : ${searchDatabaseDataFile.name} ${searchDatabaseDataFile.size} ${searchDatabaseDataFile.originalFilename} ${searchDatabaseDataFile.contentType}"
if (searchDatabaseDataFile != null && searchDatabaseDataFile.size>0) {
File searchDirectory = new File(directory.absolutePath + "/search")
assert searchDirectory.mkdir()
assert searchDirectory.setWritable(true)
File searchFile = new File(searchDirectory.absolutePath + File.separator + searchDatabaseDataFile.originalFilename)
searchDatabaseDataFile.transferTo(searchFile)
organism.blatdb = searchFile.absolutePath
}
log.info "faToTwoBit exec file specified ${configWrapperService.faToTwobitExe}"
if( (searchDatabaseDataFile==null || searchDatabaseDataFile.size==0) && configWrapperService.getFaToTwobitExe().size()>0 ){
try {
String searchPath = "${fastaPath}.2bit"
log.info "Creating 2bit file ${searchPath}"
String indexCommand = "${configWrapperService.faToTwobitExe} ${fastaPath} ${searchPath}"
log.info "executing command '${indexCommand}"
indexCommand.execute()
organism.blatdb = searchPath
} catch (e) {
log.error("Failed to create a twobit file ${e.message}")
organism.blatdb = ''
}
}
organism.save()
String trackListJson = TrackDefaults.getIndexedFastaConfig(organismName)
File trackListFile = new File(directory.absolutePath + File.separator + "trackList.json")
trackListFile.write(trackListJson)
// create an index
Path path = FileSystems.getDefault().getPath(fastaPath)
FastaSequenceIndexCreator.create(path, true)
sequenceService.loadRefSeqs(organism)
preferenceService.setCurrentOrganism(permissionService.getCurrentUser(requestObject), organism, clientToken)
findAllOrganisms()
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
organism.delete()
}
} else {
throw new RuntimeException("Not sure how we got here ")
}
} else {
log.error "Could not create ${directory.absolutePath}"
returnObject.put("error", "Could not create ${directory.absolutePath}.")
organism.delete()
}
} else {
log.error "username ${requestObject.get(FeatureStringEnum.USERNAME.value)} is not authorized to add organisms"
returnObject.put("error", "username ${requestObject.get(FeatureStringEnum.USERNAME.value)} is not authorized to add organisms.")
}
}
catch (e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
}
render returnObject as JSON
}
@RestApiMethod(description = "Removes an added track from an existing organism returning a JSON object containing all tracks for the current organism.", path = "/organism/removeTrackFromOrganism", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
, @RestApiParam(name = "trackLabel", type = "string", paramType = RestApiParamType.QUERY, description = "Name of track")
])
@Transactional
def removeTrackFromOrganism() {
JSONObject returnObject = new JSONObject()
JSONObject requestObject = permissionService.handleInput(request, params)
log.info "removing track from organism with ${requestObject}"
if (!requestObject.containsKey(FeatureStringEnum.ORGANISM.value)) {
returnObject.put("error", "/removeTrackFromOrganism requires '${FeatureStringEnum.ORGANISM.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (!requestObject.containsKey(FeatureStringEnum.TRACK_LABEL.value)) {
returnObject.put("error", "/removeTrackFromOrganism requires '${FeatureStringEnum.TRACK_LABEL.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
try {
permissionService.checkPermissions(requestObject, PermissionEnum.ADMINISTRATE)
Organism organism = preferenceService.getOrganismForTokenInDB(requestObject.get(FeatureStringEnum.ORGANISM.value)?.id)
// find in the extended track list and remove
File extendedDirectory = trackService.getExtendedDataDirectory(organism)
if (!extendedDirectory.exists()) {
returnObject.put("error", "No temporary directory found to remove tracks from ${extendedDirectory.absolutePath}")
render returnObject as JSON
return
}
File extendedTrackListJsonFile
if (new File(extendedDirectory.absolutePath + File.separator + TrackService.EXTENDED_TRACKLIST).exists()) {
extendedTrackListJsonFile = new File(extendedDirectory.absolutePath + File.separator + TrackService.EXTENDED_TRACKLIST)
} else {
if (organism.directory.contains(trackService.commonDataDirectory)) {
extendedTrackListJsonFile = new File(organism.directory + File.separator + trackService.TRACKLIST)
} else {
throw new RuntimeException("Can not delete tracks from a non-temporary directory: ${extendedTrackListJsonFile.absolutePath}")
}
}
JSONObject extendedTrackListObject = JSON.parse(extendedTrackListJsonFile.text)
JSONArray extendedTracksArray = extendedTrackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)
String trackLabel = requestObject.getString(FeatureStringEnum.TRACK_LABEL.value)
JSONObject trackObject = trackService.findTrackFromArray(extendedTracksArray, trackLabel)
extendedTracksArray = trackService.removeTrackFromArray(extendedTracksArray, trackLabel)
extendedTrackListObject.put(FeatureStringEnum.TRACKS.value, extendedTracksArray)
extendedTrackListJsonFile.write(extendedTrackListObject.toString())
TrackTypeEnum trackTypeEnum = TrackTypeEnum.valueOf(trackObject.apollo.type)
// delete any files with the patterns of key.suffix and key.suffixIndex
for (def suffix in trackTypeEnum.suffix) {
File fileToDelete = new File(extendedDirectory.absolutePath + File.separator + "raw/" + trackObject.label.replaceAll(" ", "_") + ".${suffix}")
if (fileToDelete.exists()) {
assert fileToDelete.delete()
}
}
for (def suffix in trackTypeEnum.suffixIndex) {
File fileToDelete = new File(extendedDirectory.absolutePath + File.separator + "raw/" + trackObject.label.replaceAll(" ", "_") + ".${suffix}")
if (fileToDelete.exists()) {
assert fileToDelete.delete()
}
}
render returnObject as JSON
} catch (Exception ce) {
log.error ce.message
returnObject.put("error", ce.message)
render returnObject as JSON
return
}
}
@RestApiMethod(description = "Adds a track to an existing organism returning a JSON object containing all tracks for the current organism.", path = "/organism/addTrackToOrganism", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
, @RestApiParam(name = "trackData", type = "string", paramType = RestApiParamType.QUERY, description = "zip or tar.gz compressed track data")
, @RestApiParam(name = "trackFile", type = "string", paramType = RestApiParamType.QUERY, description = "track file (*.bam, *.vcf, *.bw, *gff)")
, @RestApiParam(name = "trackFileIndex", type = "string", paramType = RestApiParamType.QUERY, description = "index (*.bai, *.tbi)")
, @RestApiParam(name = "trackConfig", type = "string", paramType = RestApiParamType.QUERY, description = "Track configuration (JBrowse JSON)")
])
@Transactional
def addTrackToOrganism() {
JSONObject returnObject = new JSONObject()
JSONObject requestObject = permissionService.handleInput(request, params)
String pathToJBrowseBinaries = servletContext.getRealPath("/jbrowse/bin")
log.debug "path to JBrowse binaries ${pathToJBrowseBinaries}"
if (!requestObject.containsKey(FeatureStringEnum.ORGANISM.value)) {
returnObject.put("error", "/addTrackToOrganism requires '${FeatureStringEnum.ORGANISM.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (requestObject.containsKey(FeatureStringEnum.TRACK_DATA.value) && requestObject.containsKey("trackFile")) {
returnObject.put("error", "Both 'trackData' and 'trackFile' specified; /addTrackToOrganism requires either '${FeatureStringEnum.TRACK_DATA.value}' or 'trackFile'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (!requestObject.containsKey(FeatureStringEnum.TRACK_DATA.value) && !requestObject.containsKey("trackFile")) {
returnObject.put("error", "/addTrackToOrganism requires either '${FeatureStringEnum.TRACK_DATA.value}' or 'trackFile'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (!requestObject.containsKey(FeatureStringEnum.TRACK_CONFIG.value)) {
returnObject.put("error", "/addTrackToOrganism requires '${FeatureStringEnum.TRACK_CONFIG.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
JSONObject trackConfigObject
try {
trackConfigObject = JSON.parse(params.get(FeatureStringEnum.TRACK_CONFIG.value) as String) as JSONObject
} catch (ConverterException ce) {
log.error ce.message
returnObject.put("error", ce.message)
render returnObject as JSON
return
}
if (!trackConfigObject.containsKey(FeatureStringEnum.LABEL.value) || !trackConfigObject.containsKey(FeatureStringEnum.URL_TEMPLATE.value)) {
log.error "trackConfig requires '${FeatureStringEnum.LABEL.value}' and '${FeatureStringEnum.URL_TEMPLATE.value}'"
returnObject.put("error", "trackConfig requires '${FeatureStringEnum.LABEL.value}' and '${FeatureStringEnum.URL_TEMPLATE.value}'.")
render returnObject as JSON
return
}
try {
permissionService.checkPermissions(requestObject, PermissionEnum.ADMINISTRATE)
// log.debug "user ${requestObject.get(FeatureStringEnum.USERNAME.value)} is admin"
Organism organism = preferenceService.getOrganismForTokenInDB(requestObject.get(FeatureStringEnum.ORGANISM.value))
if (organism) {
log.debug "Adding track to organism: ${organism.commonName}"
String organismDirectoryName = organism.directory
File organismDirectory = new File(organismDirectoryName)
File commonDataDirectory = new File(trackService.commonDataDirectory)
CommonsMultipartFile trackDataFile = request.getFile(FeatureStringEnum.TRACK_DATA.value)
CommonsMultipartFile trackFile = request.getFile(FeatureStringEnum.TRACK_FILE.value)
CommonsMultipartFile trackFileIndex = request.getFile(FeatureStringEnum.TRACK_FILE_INDEX.value)
if (organismDirectory.getParentFile().getCanonicalPath() == commonDataDirectory.getCanonicalPath()) {
// organism data is in common data directory
log.info "organism data is in common data directory"
File trackListJsonFile = new File(organism.directory + File.separator + trackService.TRACKLIST)
JSONObject trackListObject = JSON.parse(trackListJsonFile.text)
JSONArray tracksArray = trackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)
if (trackDataFile) {
// check if track exists in trackList.json
if (trackService.findTrackFromArray(tracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) == null) {
// add track config to trackList.json
tracksArray.add(trackConfigObject)
// unpack track data into organism directory
File archiveFile = new File(trackDataFile.getOriginalFilename())
trackDataFile.transferTo(archiveFile)
try {
String urlTemplate = trackConfigObject.get(FeatureStringEnum.URL_TEMPLATE.value)
String trackDirectoryName = urlTemplate.split("/").first()
String path = organismDirectoryName + File.separator + trackDirectoryName
fileService.decompress(archiveFile, path, trackConfigObject.get(FeatureStringEnum.LABEL.value), true)
// write to trackList.json
def trackListJsonWriter = trackListJsonFile.newWriter()
trackListJsonWriter << trackListObject.toString(4)
trackListJsonWriter.close()
returnObject.put(FeatureStringEnum.TRACKS.value, tracksArray)
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
}
} else {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}.")
}
} else {
// trackDataFile is null; use data from trackFile and trackFileIndex, if available
if (trackFile) {
if (trackService.findTrackFromArray(tracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) == null) {
// add track config to trackList.json
tracksArray.add(trackConfigObject)
try {
String urlTemplate = trackConfigObject.get(FeatureStringEnum.URL_TEMPLATE.value)
String trackDirectoryName = urlTemplate.split("/").first()
String path = organismDirectoryName + File.separator + trackDirectoryName
// fileService.store(trackFile, path)
TrackTypeEnum trackTypeEnum = org.bbop.apollo.gwt.shared.track.TrackTypeEnum.valueOf(trackConfigObject.apollo.type)
String newFileName = trackTypeEnum ? trackConfigObject.key + "." + trackTypeEnum.suffix[0] : trackFile.originalFilename
File destinationFile = fileService.storeWithNewName(trackFile, path, trackConfigObject.key, newFileName)
if (trackFileIndex.originalFilename) {
String newFileNameIndex = trackTypeEnum ? trackConfigObject.key + "." + trackTypeEnum.suffixIndex[0] : trackFileIndex.originalFilename
// fileService.store(trackFileIndex, path)
fileService.storeWithNewName(trackFileIndex, path, trackConfigObject.key, newFileNameIndex)
}
if (trackTypeEnum == TrackTypeEnum.GFF3_JSON || trackTypeEnum == TrackTypeEnum.GFF3_JSON_CANVAS) {
trackService.generateJSONForGff3(destinationFile, organismDirectoryName, pathToJBrowseBinaries, trackConfigObject.apollo.topType)
}
// write to trackList.json
def trackListJsonWriter = trackListJsonFile.newWriter()
trackListJsonWriter << trackListObject.toString(4)
trackListJsonWriter.close()
returnObject.put(FeatureStringEnum.TRACKS.value, tracksArray)
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
}
} else {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}.")
}
}
}
} else {
// organism data is somewhere on the server where we don't want to modify anything
File trackListJsonFile = new File(organism.directory + File.separator + trackService.TRACKLIST)
JSONObject trackListObject = JSON.parse(trackListJsonFile.text)
JSONArray tracksArray = trackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)
if (trackService.findTrackFromArray(tracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) != null) {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}.")
} else {
File extendedDirectory = trackService.getExtendedDataDirectory(organism)
if (!extendedDirectory.exists()) {
// make a new extended organism directory in common data directory
if (extendedDirectory.mkdirs() && extendedDirectory.setWritable(true)) {
// write extendedTrackList.json
File extendedTrackListJsonFile = trackService.getExtendedTrackList(organism)
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << "{'${FeatureStringEnum.TRACKS.value}':[]}"
trackListJsonWriter.close()
} else {
log.error "Cannot create directory ${extendedDirectory.absolutePath}"
returnObject.put("error", "Cannot create directory ${extendedDirectory.absolutePath}.")
}
}
if (trackDataFile) {
File extendedTrackListJsonFile = trackService.getExtendedTrackList(organism)
JSONObject extendedTrackListObject = JSON.parse(extendedTrackListJsonFile.text)
JSONArray extendedTracksArray = extendedTrackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)
// check if track exists in extendedTrackList.json
if (trackService.findTrackFromArray(extendedTracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) != null) {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${extendedDirectory.absolutePath}/${trackService.EXTENDED_TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${extendedDirectory.absolutePath}/${trackService.EXTENDED_TRACKLIST}.")
} else {
// add track config to extendedTrackList.json
extendedTracksArray.add(trackConfigObject)
// unpack track data into organism directory
File archiveFile = new File(trackDataFile.getOriginalFilename())
trackDataFile.transferTo(archiveFile)
try {
String urlTemplate = trackConfigObject.get(FeatureStringEnum.URL_TEMPLATE.value)
String trackDirectoryName = urlTemplate.split("/").first()
String path = extendedDirectory.absolutePath + File.separator + trackDirectoryName
fileService.decompress(archiveFile, path, trackConfigObject.get(FeatureStringEnum.LABEL.value), true)
// write to trackList.json
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << extendedTrackListObject.toString(4)
trackListJsonWriter.close()
returnObject.put(FeatureStringEnum.TRACKS.value, tracksArray + extendedTracksArray)
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
}
}
} else {
if (trackFile) {
if (trackService.findTrackFromArray(tracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) == null) {
// add track config to trackList.json
File extendedTrackListJsonFile = trackService.getExtendedTrackList(organism)
if (!extendedTrackListJsonFile.exists()) {
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << "{'${FeatureStringEnum.TRACKS.value}':[]}"
trackListJsonWriter.close()
} else {
log.info "FILE EXISTS, so nothing to do ${extendedTrackListJsonFile.text}"
}
JSONObject extendedTrackListObject = JSON.parse(extendedTrackListJsonFile.text)
JSONArray extendedTracksArray = extendedTrackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)
if (trackService.findTrackFromArray(extendedTracksArray, trackConfigObject.get(FeatureStringEnum.LABEL.value)) != null) {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}.")
} else {
try {
String path = extendedDirectory.absolutePath + File.separator + "raw"
TrackTypeEnum trackTypeEnum = org.bbop.apollo.gwt.shared.track.TrackTypeEnum.valueOf(trackConfigObject.apollo.type)
// TODO: if the suffix is 0 does not end with gzip, then we need to run it through the decrompressor
String newFileName = trackTypeEnum ? trackConfigObject.key + "." + trackTypeEnum.suffix[0] : trackFile.originalFilename
// File destinationFile
// if( (trackTypeEnum == TrackTypeEnum.GFF3_JSON || trackTypeEnum == TrackTypeEnum.GFF3_JSON_CANVAS) && trackFile.originalFilename.endsWith(".gz")){
// File archiveFile = new File(trackFile.originalFilename)
// trackFile.transferTo(archiveFile)
//// String outputFilePath = fileService.decompress(archiveFile, path, trackConfigObject.get(FeatureStringEnum.LABEL.value), true)[0]
// String outputFilePath = fileService.decompressGzipArchive(archiveFile, path, null,false)[0]
// destinationFile = new File(outputFilePath)
//// destinationFile = fileService.storeWithNewName(outputFile, path, trackConfigObject.key, newFileName)
// }
// else{
// destinationFile = fileService.storeWithNewName(trackFile, path, trackConfigObject.key, newFileName)
// }
File destinationFile = fileService.storeWithNewName(trackFile, path, trackConfigObject.key, newFileName)
if (trackFileIndex.getOriginalFilename()) {
String newFileNameIndex = trackTypeEnum ? trackConfigObject.key + "." + trackTypeEnum.suffixIndex[0] : trackFileIndex.originalFilename
fileService.storeWithNewName(trackFileIndex, path, trackConfigObject.key, newFileNameIndex)
}
if (trackTypeEnum == TrackTypeEnum.GFF3_JSON || trackTypeEnum == TrackTypeEnum.GFF3_JSON_CANVAS) {
trackService.generateJSONForGff3(destinationFile, extendedDirectory.absolutePath, pathToJBrowseBinaries, trackConfigObject.apollo.topType)
}
extendedTracksArray.add(trackConfigObject)
extendedTrackListObject.put(FeatureStringEnum.TRACKS.value, extendedTracksArray)
// write to trackList.json
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << extendedTrackListObject.toString(4)
trackListJsonWriter.close()
returnObject.put(FeatureStringEnum.TRACKS.value, tracksArray)
}
catch (IOException e) {
log.error e.printStackTrace()
returnObject.put("error", e.message)
}
}
log.debug "trackJsonWriter: -> ${extendedTrackListJsonFile.absolutePath}, ${extendedTrackListJsonFile.text}"
} else {
log.error "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}"
returnObject.put("error", "an entry for track with label '${trackConfigObject.get(FeatureStringEnum.LABEL.value)}' already exists in ${organism.directory}/${TRACKLIST}.")
}
}
}
}
}
} else {
log.error "Organism not found"
returnObject.put("error", "Organism not found.")
}
} catch (e) {
log.error e.message
returnObject.put("error", e.message)
}
render returnObject as JSON
}
@RestApiMethod(description = "Deletes a track from an existing organism and returns a JSON object of the deleted track's configuration", path = "/organism/deleteTrackFromOrganism", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
, @RestApiParam(name = "trackLabel", type = "string", paramType = RestApiParamType.QUERY, description = "Track label corresponding to the track that is to be deleted")
])
@Transactional
def deleteTrackFromOrganism() {
JSONObject returnObject = new JSONObject()
try {
JSONObject requestObject = permissionService.handleInput(request, params)
if (!requestObject.containsKey(FeatureStringEnum.ORGANISM.value)) {
returnObject.put("error", "/deleteTrackFromOrganism requires '${FeatureStringEnum.ORGANISM.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (!requestObject.containsKey(FeatureStringEnum.TRACK_LABEL.value)) {
returnObject.put("error", "/deleteTrackFromOrganism requires '${FeatureStringEnum.TRACK_LABEL.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
String trackLabel = requestObject.get(FeatureStringEnum.TRACK_LABEL.value)
permissionService.checkPermissions(requestObject, PermissionEnum.ADMINISTRATE)
log.debug "user ${requestObject.get(FeatureStringEnum.USERNAME.value)} is admin"
Organism organism = preferenceService.getOrganismForTokenInDB(requestObject.get(FeatureStringEnum.ORGANISM.value))
if (organism) {
log.debug "organism ${organism}"
File trackListJsonFile = new File(organism.trackList)
JSONObject trackListObject = JSON.parse(trackListJsonFile.text) as JSONObject
JSONObject trackObject = trackService.findTrackFromArray(trackListObject.getJSONArray(FeatureStringEnum.TRACKS.value), trackLabel)
if (trackObject == null) {
// track not found in trackList.json
log.debug "Track with label '${trackLabel}' not found; searching in extendedTrackList.json"
File extendedTrackListJsonFile = trackService.getExtendedTrackList(organism)
if (extendedTrackListJsonFile.exists()) {
JSONObject extendedTrackListObject = JSON.parse(extendedTrackListJsonFile.text) as JSONObject
trackObject = trackService.findTrackFromArray(extendedTrackListObject.getJSONArray(FeatureStringEnum.TRACKS.value), trackLabel)
if (trackObject == null) {
// track not found
log.error "Track with label '${trackLabel}' not found"
returnObject.put("error", "Track with label '${trackLabel}' not found.")
} else {
log.debug "Track with label '${trackLabel}' found; removing from extendedTrackList.json"
extendedTrackListObject.getJSONArray(FeatureStringEnum.TRACKS.value).remove(trackObject)
String urlTemplate = trackObject.get(FeatureStringEnum.URL_TEMPLATE.value)
String trackDirectory = urlTemplate.split("/").first()
File commonDirectory = trackService.getExtendedDataDirectory(organism)
File trackDir = new File(commonDirectory.absolutePath + File.separator + trackDirectory + File.separator + trackObject.get(FeatureStringEnum.LABEL.value))
if (trackDir.exists()) {
log.debug "Deleting ${trackDir.getAbsolutePath()}"
if (trackDir.deleteDir()) {
// updating extendedTrackList.json
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << extendedTrackListObject.toString(4)
trackListJsonWriter.close()
}
} else {
log.error "track directory ${trackDir.getAbsolutePath()} not found"
returnObject.put("error", "Track with label '${trackLabel}' removed from config but track directory not found.")
// updating extendedTrackList.json
def trackListJsonWriter = extendedTrackListJsonFile.newWriter()
trackListJsonWriter << extendedTrackListObject.toString(4)
trackListJsonWriter.close()
}
returnObject.put("track", trackObject)
}
} else {
log.error "Track with label '${trackLabel}' not found"
returnObject.put("error", "Track with label '${trackLabel}' not found.")
}
} else {
// track found in trackList.json
log.debug "track with label '${trackLabel}' found in trackList.json"
if (organism.dataAddedViaWebServices) {
log.debug "organism data was added via web services; thus can remove the track"
// track can be deleted since the organism and all subsequent tracks were added via web services
trackListObject.getJSONArray(FeatureStringEnum.TRACKS.value).remove(trackObject)
String urlTemplate = trackObject.get(FeatureStringEnum.URL_TEMPLATE.value)
String trackDirectory = urlTemplate.split("/").first()
File trackDir = new File(organism.directory + File.separator + trackDirectory + File.separator + trackObject.get(FeatureStringEnum.LABEL.value))
if (trackDir.exists()) {
log.debug "Deleting ${trackDir.getAbsolutePath()}"
if (trackDir.deleteDir()) {
// updating trackList.json
def trackListJsonWriter = trackListJsonFile.newWriter()
trackListJsonWriter << trackListObject.toString(4)
trackListJsonWriter.close()
}
} else {
log.error "track directory ${trackDir.getAbsolutePath()} not found"
returnObject.put("error", "Track with label '${trackLabel}' removed from config but track directory not found.")
// updating trackList.json
def trackListJsonWriter = trackListJsonFile.newWriter()
trackListJsonWriter << trackListObject.toString(4)
trackListJsonWriter.close()
}
returnObject.put("track", trackObject)
} else {
// cannot delete track since its part of the main data directory
log.error "Track with label '${trackLabel}' found but is part of the main data directory and cannot be deleted."
returnObject.put("error", "Track with label '${trackLabel}' found but is part of the main data directory and cannot be deleted.")
}
}
} else {
log.error("Organism not found")
returnObject.put("error", "Organism not found.")
}
} catch (Exception e) {
log.error(e.message)
returnObject.put("error", e.message)
}
render returnObject as JSON
}
@RestApiMethod(description = "Update a track in an existing organism returning a JSON object containing old and new track configurations", path = "/organism/updateTrackForOrganism", verb = RestApiVerb.POST)
@RestApiParams(params = [
@RestApiParam(name = "username", type = "email", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "password", type = "password", paramType = RestApiParamType.QUERY)
, @RestApiParam(name = "organism", type = "string", paramType = RestApiParamType.QUERY, description = "ID or commonName that can be used to uniquely identify an organism")
, @RestApiParam(name = "trackConfig", type = "string", paramType = RestApiParamType.QUERY, description = "Track configuration (JBrowse JSON)")
])
@Transactional
def updateTrackForOrganism() {
JSONObject returnObject = new JSONObject()
JSONObject requestObject = permissionService.handleInput(request, params)
if (!requestObject.containsKey(FeatureStringEnum.ORGANISM.value)) {
returnObject.put("error", "/updateTrackForOrganism requires '${FeatureStringEnum.ORGANISM.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
if (!requestObject.containsKey(FeatureStringEnum.TRACK_CONFIG.value)) {
returnObject.put("error", "/updateTrackForOrganism requires '${FeatureStringEnum.TRACK_CONFIG.value}'.")
response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
render returnObject as JSON
return
}
JSONObject trackConfigObject
try {
trackConfigObject = JSON.parse(params.get(FeatureStringEnum.TRACK_CONFIG.value)) as JSONObject
} catch (ConverterException ce) {
log.error ce.message
returnObject.put("error", ce.message)
render returnObject as JSON
return
}
if (!trackConfigObject.containsKey(FeatureStringEnum.LABEL.value) || !trackConfigObject.containsKey(FeatureStringEnum.URL_TEMPLATE.value)) {
log.error "trackConfig requires both '${FeatureStringEnum.LABEL.value}' and '${FeatureStringEnum.URL_TEMPLATE.value}'."
returnObject.put("error", "trackConfig requires both '${FeatureStringEnum.LABEL.value}' and '${FeatureStringEnum.URL_TEMPLATE.value}'.")
render returnObject as JSON
return
}
try {
permissionService.checkPermissions(requestObject, PermissionEnum.ADMINISTRATE)
log.debug "user ${requestObject.get(FeatureStringEnum.USERNAME.value)} is admin"
Organism organism = preferenceService.getOrganismForTokenInDB(requestObject.get(FeatureStringEnum.ORGANISM.value))
if (organism) {
String organismDirectoryName = organism.directory
File organismDirectory = new File(organismDirectoryName)
File commonDataDirectory = new File(trackService.commonDataDirectory)
if (organismDirectory.getParentFile().getAbsolutePath() == commonDataDirectory.getAbsolutePath()) {
// organism data is in common data directory
log.debug "organism data is in common data directory"
File trackListJsonFile = new File(organism.directory + File.separator + trackService.TRACKLIST)
JSONObject trackListObject = JSON.parse(trackListJsonFile.text)
JSONArray tracksArray = trackListObject.getJSONArray(FeatureStringEnum.TRACKS.value)