forked from BimberLab/DiscvrLabKeyModules
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSequenceAnalysisController.java
More file actions
5247 lines (4475 loc) · 194 KB
/
SequenceAnalysisController.java
File metadata and controls
5247 lines (4475 loc) · 194 KB
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) 2011-2012 LabKey Corporation
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.sequenceanalysis;
import htsjdk.samtools.SAMException;
import htsjdk.tribble.TribbleException;
import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFHeader;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.biojava.nbio.core.sequence.DNASequence;
import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet;
import org.biojava.nbio.core.sequence.compound.NucleotideCompound;
import org.biojava.nbio.core.sequence.io.DNASequenceCreator;
import org.biojava.nbio.core.sequence.io.FastaReader;
import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.labkey.api.action.AbstractFileUploadAction;
import org.labkey.api.action.ApiJsonWriter;
import org.labkey.api.action.ApiResponse;
import org.labkey.api.action.ApiSimpleResponse;
import org.labkey.api.action.ApiUsageException;
import org.labkey.api.action.ConfirmAction;
import org.labkey.api.action.ExportAction;
import org.labkey.api.action.MutatingApiAction;
import org.labkey.api.action.ReadOnlyApiAction;
import org.labkey.api.action.ReturnUrlForm;
import org.labkey.api.action.SimpleApiJsonForm;
import org.labkey.api.action.SimpleViewAction;
import org.labkey.api.action.SpringActionController;
import org.labkey.api.assay.AssayFileWriter;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.collections.CaseInsensitiveHashSet;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.CompareType;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerFilter;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.ConvertHelper;
import org.labkey.api.data.DataRegionSelection;
import org.labkey.api.data.PropertyManager;
import org.labkey.api.data.PropertyManager.WritablePropertyMap;
import org.labkey.api.data.Results;
import org.labkey.api.data.ResultsImpl;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.Selector;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.Sort;
import org.labkey.api.data.SqlSelector;
import org.labkey.api.data.Table;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.discvrcore.annotation.UtilityAction;
import org.labkey.api.exceptions.OptimisticConflictException;
import org.labkey.api.exp.ExperimentException;
import org.labkey.api.exp.api.DataType;
import org.labkey.api.exp.api.ExpData;
import org.labkey.api.exp.api.ExpRun;
import org.labkey.api.exp.api.ExperimentService;
import org.labkey.api.files.FileContentService;
import org.labkey.api.laboratory.NavItem;
import org.labkey.api.laboratory.security.LaboratoryAdminPermission;
import org.labkey.api.module.Module;
import org.labkey.api.module.ModuleHtmlView;
import org.labkey.api.module.ModuleLoader;
import org.labkey.api.pipeline.PipeRoot;
import org.labkey.api.pipeline.PipelineJob;
import org.labkey.api.pipeline.PipelineJobException;
import org.labkey.api.pipeline.PipelineService;
import org.labkey.api.pipeline.PipelineStatusFile;
import org.labkey.api.pipeline.PipelineUrls;
import org.labkey.api.pipeline.PipelineValidationException;
import org.labkey.api.query.BatchValidationException;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryForm;
import org.labkey.api.query.QueryService;
import org.labkey.api.security.IgnoresTermsOfUse;
import org.labkey.api.security.RequiresPermission;
import org.labkey.api.security.RequiresSiteAdmin;
import org.labkey.api.security.permissions.AdminPermission;
import org.labkey.api.security.permissions.DeletePermission;
import org.labkey.api.security.permissions.InsertPermission;
import org.labkey.api.security.permissions.ReadPermission;
import org.labkey.api.security.permissions.UpdatePermission;
import org.labkey.api.sequenceanalysis.RefNtSequenceModel;
import org.labkey.api.sequenceanalysis.SequenceAnalysisService;
import org.labkey.api.sequenceanalysis.SequenceDataProvider;
import org.labkey.api.sequenceanalysis.SequenceOutputFile;
import org.labkey.api.sequenceanalysis.model.AnalysisModel;
import org.labkey.api.sequenceanalysis.model.ReadData;
import org.labkey.api.sequenceanalysis.model.Readset;
import org.labkey.api.sequenceanalysis.pipeline.JobResourceSettings;
import org.labkey.api.sequenceanalysis.pipeline.ParameterizedOutputHandler;
import org.labkey.api.sequenceanalysis.pipeline.PipelineStep;
import org.labkey.api.sequenceanalysis.pipeline.PipelineStepProvider;
import org.labkey.api.sequenceanalysis.pipeline.SequenceOutputHandler;
import org.labkey.api.sequenceanalysis.pipeline.SequencePipelineService;
import org.labkey.api.sequenceanalysis.pipeline.ToolParameterDescriptor;
import org.labkey.api.sequenceanalysis.pipeline.VariantProcessingStep;
import org.labkey.api.util.ExceptionUtil;
import org.labkey.api.util.FileType;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.JsonUtil;
import org.labkey.api.util.NetworkDrive;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.Path;
import org.labkey.api.util.StringExpressionFactory;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.URLHelper;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.HtmlView;
import org.labkey.api.view.JspView;
import org.labkey.api.view.NavTree;
import org.labkey.api.view.NotFoundException;
import org.labkey.api.view.UnauthorizedException;
import org.labkey.api.view.ViewContext;
import org.labkey.api.view.template.ClientDependency;
import org.labkey.api.view.template.PageConfig;
import org.labkey.api.writer.PrintWriters;
import org.labkey.sequenceanalysis.model.AnalysisModelImpl;
import org.labkey.sequenceanalysis.model.ReferenceLibraryMember;
import org.labkey.sequenceanalysis.pipeline.AlignmentAnalysisJob;
import org.labkey.sequenceanalysis.pipeline.AlignmentImportJob;
import org.labkey.sequenceanalysis.pipeline.IlluminaImportJob;
import org.labkey.sequenceanalysis.pipeline.ImportFastaSequencesPipelineJob;
import org.labkey.sequenceanalysis.pipeline.ImportGenomeTrackPipelineJob;
import org.labkey.sequenceanalysis.pipeline.OrphanFilePipelineJob;
import org.labkey.sequenceanalysis.pipeline.ReadsetImportJob;
import org.labkey.sequenceanalysis.pipeline.ReferenceGenomeImpl;
import org.labkey.sequenceanalysis.pipeline.ReferenceLibraryPipelineJob;
import org.labkey.sequenceanalysis.pipeline.SequenceAlignmentJob;
import org.labkey.sequenceanalysis.pipeline.SequenceConcatPipelineJob;
import org.labkey.sequenceanalysis.pipeline.SequenceJob;
import org.labkey.sequenceanalysis.pipeline.SequenceOutputHandlerJob;
import org.labkey.sequenceanalysis.pipeline.SequenceReadsetHandlerJob;
import org.labkey.sequenceanalysis.pipeline.SequenceTaskHelper;
import org.labkey.sequenceanalysis.pipeline.VariantProcessingJob;
import org.labkey.sequenceanalysis.run.BamHaplotyper;
import org.labkey.sequenceanalysis.run.analysis.AASnpByCodonAggregator;
import org.labkey.sequenceanalysis.run.analysis.AASnpByReadAggregator;
import org.labkey.sequenceanalysis.run.analysis.AlignmentAggregator;
import org.labkey.sequenceanalysis.run.analysis.AvgBaseQualityAggregator;
import org.labkey.sequenceanalysis.run.analysis.BamIterator;
import org.labkey.sequenceanalysis.run.analysis.NtCoverageAggregator;
import org.labkey.sequenceanalysis.run.analysis.NtSnpByPosAggregator;
import org.labkey.sequenceanalysis.run.util.FastqcRunner;
import org.labkey.sequenceanalysis.util.ChainFileValidator;
import org.labkey.sequenceanalysis.util.FastqUtils;
import org.labkey.sequenceanalysis.util.SequenceUtil;
import org.labkey.vfs.FileLike;
import org.labkey.vfs.FileSystemLike;
import org.springframework.beans.PropertyValues;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.servlet.ModelAndView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URI;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.labkey.sequenceanalysis.SequenceIntegrationTests.PIPELINE_PROP_NAME;
public class SequenceAnalysisController extends SpringActionController
{
private static final Logger _log = LogManager.getLogger(SequenceAnalysisController.class);
private static final DefaultActionResolver _actionResolver = new DefaultActionResolver(SequenceAnalysisController.class);
public final static String CONFIG_PROPERTY_DOMAIN_IMPORT = "org.labkey.sequenceanalysis.importsettings";
public SequenceAnalysisController()
{
setActionResolver(_actionResolver);
}
@RequiresPermission(ReadPermission.class)
public static class FastqcReportAction extends SimpleViewAction<FastqcForm>
{
@Override
public void validate(FastqcForm form, BindException errors)
{
if (form.getReadsets() == null && form.getFilenames() == null && form.getDataIds() == null && form.getAnalysisIds() == null)
{
errors.reject(ERROR_MSG, "Must provide a filename or Exp data Ids");
}
}
@Override
public ModelAndView getView(FastqcForm form, BindException errors) throws Exception
{
//resolve files
List<File> files = new ArrayList<>();
Map<File, String> labels = new HashMap<>();
if (form.getFilenames() != null)
{
for (String fn : form.getFilenames())
{
File root = FileContentService.get().getFileRoot(getContainer(), FileContentService.ContentType.files);
File target = new File(root, fn);
if (target.exists())
{
files.add(target);
}
}
}
if (form.getDataIds() != null)
{
if (ArrayUtils.isEmpty(form.getDataIds()))
{
errors.reject(ERROR_MSG, "List of data IDs is empty");
return null;
}
for (Integer id : form.getDataIds())
{
if (id == null)
{
continue;
}
ExpData data = ExperimentService.get().getExpData(id);
if (data != null && data.getContainer().hasPermission(getUser(), ReadPermission.class))
{
if (data.getFile().exists())
files.add(data.getFile());
}
}
}
if (form.getReadsets() != null)
{
for (int id : form.getReadsets())
{
SequenceReadsetImpl rs = SequenceAnalysisServiceImpl.get().getReadset(id, getUser());
for (ReadDataImpl d : rs.getReadDataImpl())
{
if (d.getFile1() != null)
{
files.add(d.getFile1());
labels.put(d.getFile1(), "Readset " + rs.getName());
}
if (d.getFile2() != null)
{
files.add(d.getFile2());
labels.put(d.getFile2(), "Readset " + rs.getName());
}
}
}
}
if (form.getAnalysisIds() != null)
{
for (int id : form.getAnalysisIds())
{
AnalysisModel m = AnalysisModelImpl.getFromDb(id, getUser());
if (m != null && m.getAlignmentFileObject() != null)
{
files.add(m.getAlignmentFileObject());
labels.put(m.getAlignmentFileObject(), "Analysis " + m.getRowId());
}
}
}
if (files.isEmpty())
{
return HtmlView.of("Error: either no files provided or the files did not exist on the server");
}
FastqcRunner runner = new FastqcRunner(null);
if (!form.isCacheResults())
{
runner.setCacheResults(false);
}
try
{
String html = runner.execute(files, labels);
return new HtmlView("FastQC Report", HtmlString.unsafe(html));
}
catch (FileNotFoundException e)
{
return HtmlView.of("Error: " + e.getMessage());
}
}
@Override
public void addNavTrail(NavTree root)
{
root.addChild("FastQC Report"); //necessary to set page title, it seems
}
}
@RequiresPermission(InsertPermission.class)
public static class SequenceAnalysisAction extends BasePipelineStepAction
{
public SequenceAnalysisAction()
{
super("views/sequenceAnalysis.html");
}
@Override
public void addNavTrail(NavTree tree)
{
tree.addChild("Sequence Analysis");
}
}
@RequiresPermission(InsertPermission.class)
public static class VariantProcessingAction extends BasePipelineStepAction
{
public VariantProcessingAction()
{
super("views/variantProcessing.html");
}
@Override
public void addNavTrail(NavTree tree)
{
tree.addChild("1".equals(getViewContext().getActionURL().getParameter("showGenotypeGVCFs")) ? "Genotype gVCFs" : "Filter/Process Variants");
}
}
@RequiresPermission(InsertPermission.class)
public static class AlignmentImportAction extends BasePipelineStepAction
{
public AlignmentImportAction()
{
super("views/alignmentImport.html");
}
@Override
public void addNavTrail(NavTree tree)
{
tree.addChild("Import Alignments");
}
}
abstract public static class BasePipelineStepAction extends SimpleViewAction<Object>
{
protected String _htmlFile;
public BasePipelineStepAction(String htmlFile)
{
_htmlFile = htmlFile;
}
@Override
public ModelAndView getView(Object form, BindException errors)
{
LinkedHashSet<ClientDependency> cds = new LinkedHashSet<>();
for (PipelineStepProvider<?> fact : SequencePipelineService.get().getAllProviders())
{
cds.addAll(fact.getClientDependencies());
}
Module module = ModuleLoader.getInstance().getModule(SequenceAnalysisModule.class);
ModuleHtmlView view = ModuleHtmlView.get(module, Path.parse(_htmlFile));
assert view != null;
view.addClientDependencies(cds);
getPageConfig().setIncludePostParameters(true);
return view;
}
}
@RequiresPermission(InsertPermission.class)
public static class AlignmentAnalysisAction extends BasePipelineStepAction
{
public AlignmentAnalysisAction()
{
super("views/alignmentAnalysis.html");
}
@Override
public void addNavTrail(NavTree tree)
{
tree.addChild("Analyze Alignments");
}
}
@UtilityAction(label = "Find Orphan Files", description = "This will start a pipeline job that will inspect all files in this folder to identify potential orphan or otherwise unnecessary files")
@RequiresPermission(ReadPermission.class)
public static class FindOrphanFilesAction extends ConfirmAction<Object>
{
@Override
public ModelAndView getConfirmView(Object o, BindException errors) throws Exception
{
setTitle("Find Orphan Sequence Files");
HtmlView view = HtmlView.of("This will start a pipeline job that will inspect all files in this folder to identify potential orphan or otherwise unnecessary files. Do you want to continue?");
return view;
}
@Override
public boolean handlePost(Object o, BindException errors) throws Exception
{
PipeRoot pipelineRoot = PipelineService.get().findPipelineRoot(getContainer());
PipelineService.get().queueJob(new OrphanFilePipelineJob(getContainer(), getUser(), getViewContext().getActionURL(), pipelineRoot));
return true;
}
@Override
public void validateCommand(Object o, Errors errors)
{
}
@NotNull
@Override
public URLHelper getSuccessURL(Object o)
{
return PageFlowUtil.urlProvider(PipelineUrls.class).urlBegin(getContainer());
}
}
@RequiresSiteAdmin
public static class UpdateSequenceLengthAction extends ConfirmAction<Object>
{
@Override
public ModelAndView getConfirmView(Object form, BindException errors) throws Exception
{
if (!getContainer().isRoot())
{
throw new UnauthorizedException("This can only be used from the root container");
}
return HtmlView.of("This will calculate the sequence length field for any reference NT sequences lacking it. Do you want to continue?");
}
@Override
public boolean handlePost(Object form, BindException errors) throws Exception
{
SequenceAnalysisManager.get().apppendSequenceLength(getUser(), _log);
return true;
}
@Override
public void validateCommand(Object form, Errors errors)
{
}
@NotNull
@Override
public URLHelper getSuccessURL(Object form)
{
return getContainer().getStartURL(getUser());
}
}
public static class DeleteForm extends QueryForm
{
private Integer[] _jobIds;
private boolean _doDelete = false;
public Integer[] getJobIds()
{
return _jobIds;
}
public void setJobIds(Integer[] jobIds)
{
_jobIds = jobIds;
}
public boolean isDoDelete()
{
return _doDelete;
}
public void setDoDelete(boolean doDelete)
{
_doDelete = doDelete;
}
}
//TODO: add genome
@RequiresPermission(DeletePermission.class)
public static class DeleteRecordsAction extends ConfirmAction<DeleteForm>
{
private TableInfo _table;
@Override
public void validateCommand(DeleteForm form, Errors errors)
{
if (form.getSchema() == null)
{
errors.reject(ERROR_MSG, "No schema provided");
return;
}
if (form.getQueryName() == null)
{
errors.reject(ERROR_MSG, "No queryName provided");
return;
}
_table = SequenceAnalysisSchema.getInstance().getSchema().getTable(form.getQueryName());
if (_table == null)
{
errors.reject(ERROR_MSG, "Unknown table: " + form.getQueryName());
return;
}
if (_table.getColumn("container") != null)
{
Set<String> ids = DataRegionSelection.getSelected(form.getViewContext(), true);
List<Integer> keys = new ArrayList<>();
for (String key : ids)
{
keys.add(ConvertHelper.convert(key, Integer.class));
}
SimpleFilter filter = new SimpleFilter(FieldKey.fromString(_table.getPkColumns().get(0).getColumnName()), keys, CompareType.IN);
TableSelector ts = new TableSelector(_table, Collections.singleton("container"), filter, null);
ts.forEachResults(rs -> {
Container c = ContainerManager.getForId(rs.getString("container"));
if (!c.hasPermission(getUser(), DeletePermission.class))
throw new UnauthorizedException("User does not have delete permission on folder: " + c.getTitle());
});
}
}
private void findAnalysesToDelete(Collection<Integer> keys, StringBuilder msg, Set<Integer> outputFileIds, Set<Integer> expRunsToDelete)
{
appendTotal(msg, SequenceAnalysisSchema.TABLE_ALIGNMENT_SUMMARY, "Alignment Records", keys, "analysis_id", "rowid");
outputFileIds.addAll(appendTotal(msg, SequenceAnalysisSchema.TABLE_OUTPUTFILES, "Output Files", keys, "analysis_id", "rowid"));
appendTotal(msg, SequenceAnalysisSchema.TABLE_COVERAGE, "Coverage Records", keys, "analysis_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_NT_SNP_BY_POS, "NT SNP Records", keys, "analysis_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_AA_SNP_BY_CODON, "AA SNP Records", keys, "analysis_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_QUALITY_METRICS, "Quality Metrics", keys, "analysis_id", "rowid");
expRunsToDelete.addAll(getExpRunIds(SequenceAnalysisSchema.TABLE_ANALYSES, keys, "rowid", "runId"));
}
@Override
public ModelAndView getConfirmView(DeleteForm form, BindException errors) throws Exception
{
Set<String> ids = DataRegionSelection.getSelected(form.getViewContext(), true);
List<Integer> keys = new ArrayList<>();
for (String key : ids)
{
keys.add(ConvertHelper.convert(key, Integer.class));
}
Set<Integer> expRunsToDelete = new HashSet<>();
Set<Integer> readsetIds = new HashSet<>();
Set<Integer> readDataIds = new HashSet<>();
Set<Integer> analysisIds = new HashSet<>();
Set<Integer> outputFileIds = new HashSet<>();
StringBuilder msg = new StringBuilder("Are you sure you want to delete the following " + keys.size() + " ");
if (SequenceAnalysisSchema.TABLE_ANALYSES.equals(_table.getName()))
{
msg.append("analyses: " + StringUtils.join(keys, ", ") + "? This will delete the analyses, plus all associated data. This includes:<br>");
analysisIds.addAll(keys);
findAnalysesToDelete(keys, msg, outputFileIds, expRunsToDelete);
}
else if (SequenceAnalysisSchema.TABLE_READSETS.equals(_table.getName()))
{
msg.append("readsets: " + StringUtils.join(keys, ", ") + "? This will delete the readsets, plus all associated data. This includes:<br>");
readsetIds.addAll(keys);
readDataIds.addAll(appendTotal(msg, SequenceAnalysisSchema.TABLE_READ_DATA, "Sequence File Records", keys, "readset", "rowid"));
analysisIds.addAll(appendTotal(msg, SequenceAnalysisSchema.TABLE_ANALYSES, "Analyses", keys, "readset", "rowid"));
outputFileIds.addAll(appendTotal(msg, SequenceAnalysisSchema.TABLE_OUTPUTFILES, "Output Files", keys, "readset", "rowid"));
appendTotal(msg, SequenceAnalysisSchema.TABLE_ALIGNMENT_SUMMARY, "Alignment Records", keys, "analysis_id/readset", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_COVERAGE, "Coverage Records", keys, "analysis_id/readset", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_NT_SNP_BY_POS, "NT SNP Records", keys, "analysis_id/readset", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_AA_SNP_BY_CODON, "AA SNP Records", keys, "analysis_id/readset", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_QUALITY_METRICS, "Quality Metrics", keys, "readset", "rowid");
expRunsToDelete.addAll(getExpRunIds(SequenceAnalysisSchema.TABLE_READSETS, keys, "rowid", "runId"));
}
else if (SequenceAnalysisSchema.TABLE_REF_NT_SEQUENCES.equals(_table.getName()))
{
msg.append("NT reference sequences: " + StringUtils.join(keys, ", ") + "? This will delete the reference sequences, plus all associated data. This includes:<br>");
appendTotal(msg, SequenceAnalysisSchema.TABLE_REF_AA_SEQUENCES, "Reference AA Sequences", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_NT_FEATURES, "NT Features", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_COVERAGE, "Coverage Records", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_ALIGNMENT_SUMMARY_JUNCTION, "Alignment Records", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_REF_LIBRARY_MEMBERS, "Reference Library Member Records", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_NT_SNP_BY_POS, "NT SNP Records", keys, "ref_nt_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_AA_SNP_BY_CODON, "AA SNP Records", keys, "ref_nt_id", "rowid");
}
else if (SequenceAnalysisSchema.TABLE_REF_AA_SEQUENCES.equals(_table.getName()))
{
msg.append("AA reference sequences: " + StringUtils.join(keys, ", ") + "? This will delete the reference sequences, plus all associated data. This includes:<br>");
appendTotal(msg, SequenceAnalysisSchema.TABLE_AA_FEATURES, "AA features", keys, "ref_aa_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_DRUG_RESISTANCE, "drug resistance mutations", keys, "ref_aa_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_AA_SNP_BY_CODON, "AA SNP Records", keys, "ref_aa_id", "rowid");
}
else if (SequenceAnalysisSchema.TABLE_REF_LIBRARIES.equals(_table.getName()))
{
msg.append("Reference genomes: " + StringUtils.join(keys, ", ") + "? This will delete the reference genomes, plus all associated data. This includes:<br>");
appendTotal(msg, SequenceAnalysisSchema.TABLE_REF_LIBRARY_MEMBERS, "genome sequences", keys, "library_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_LIBRARY_TRACKS, "tracks", keys, "library_id", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_CHAIN_FILES, "chain files from this genome", keys, "genomeId1", "rowid");
appendTotal(msg, SequenceAnalysisSchema.TABLE_CHAIN_FILES, "chain files to this genome", keys, "genomeId2", "rowid");
}
else if (SequenceAnalysisSchema.TABLE_OUTPUTFILES.equals(_table.getName()))
{
msg.append("output files: " + StringUtils.join(keys, ", ") + "?<br>");
outputFileIds.addAll(keys);
//we will delete these expDatas, so find any analysis records matching this file
Collection<Integer> additionalAnalysisIds = SequenceAnalysisManager.get().deleteOutputFiles(keys, getUser(), getContainer(), false);
analysisIds.addAll(additionalAnalysisIds);
if (!additionalAnalysisIds.isEmpty())
{
msg.append("<br><br>");
msg.append("The following " + additionalAnalysisIds.size() + " analyses will also be deleted, along with these associated records/files:<br>");
findAnalysesToDelete(additionalAnalysisIds, msg, outputFileIds, expRunsToDelete);
}
//also pipeline jobs
expRunsToDelete.addAll(getExpRunIds(SequenceAnalysisSchema.TABLE_OUTPUTFILES, keys, "rowid", "runId"));
expRunsToDelete.addAll(getExpRunIds(SequenceAnalysisSchema.TABLE_ANALYSES, additionalAnalysisIds, "rowid", "runId"));
//Note: this number could be reduced if there are other records from the same ExpData. A check is performed at actual delete-time.
List<Integer> dataIds = new TableSelector(SequenceAnalysisSchema.getTable(SequenceAnalysisSchema.TABLE_OUTPUTFILES), PageFlowUtil.set("dataId"), new SimpleFilter(FieldKey.fromString("rowid"), outputFileIds, CompareType.IN), null).getArrayList(Integer.class);
if (!dataIds.isEmpty())
{
appendTotal(msg, SequenceAnalysisSchema.TABLE_QUALITY_METRICS, "quality metrics", dataIds, "dataId", "rowid");
}
}
if (!expRunsToDelete.isEmpty())
{
getAdditionalRuns(readsetIds, readDataIds, analysisIds, outputFileIds, expRunsToDelete);
}
if (!expRunsToDelete.isEmpty())
{
msg.append("<br><br>");
msg.append("The following pipeline jobs appear to be unused, and will be deleted. Be aware, this will delete all files as well:<br><br>");
for (Integer runId : expRunsToDelete)
{
if (runId == null)
{
_log.error("attempting to delete a null runId");
continue;
}
ExpRun run = ExperimentService.get().getExpRun(runId);
if (run != null)
{
msg.append("Pipeline run: " + run.getName() + "<br>");
if (run.getJobId() != null)
{
PipelineStatusFile sf = PipelineService.get().getStatusFile(run.getJobId());
if (sf != null)
{
File target = new File(sf.getFilePath()).getParentFile();
String relativePath = FileUtil.relativize(PipelineService.get().getPipelineRootSetting(run.getContainer()).getRootPath(), target, false);
ActionURL url = PageFlowUtil.urlProvider(PipelineUrls.class).urlBrowse(sf.lookupContainer(), getViewContext().getActionURL(), relativePath);
msg.append("Folder: <a href='" + url.toString() + "' target='_blank'>" + target.getPath() + "</a><br><input type='hidden' name='jobIds' value='" + sf.getRowId() + "'/>");
}
}
msg.append("<br>");
}
}
}
msg.append("<input type='hidden' name='doDelete' value='1'");
setTitle("Delete Sequence Records");
return new HtmlView(msg.toString());
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
{
PropertyValues values = getPropertyValues();
if (null == values)
values = new ServletRequestParameterPropertyValues(request);
BindException errors = bindParameters(values);
DeleteForm form = (DeleteForm)errors.getTarget();
if (!form.isDoDelete()) {
validate(form, errors);
boolean success = !errors.hasErrors();
if (success)
{
setProperties(values);
getViewContext().setBindPropertyValues(getPropertyValues());
ModelAndView confirmView = getConfirmView(form, errors);
JspView<ConfirmAction> confirmWrapper = new JspView<>("/org/labkey/api/action/confirmWrapper.jsp", this);
confirmWrapper.setBody(confirmView);
getPageConfig().setTemplate(PageConfig.Template.Dialog);
return confirmWrapper;
}
}
return super.handleRequest(request, response);
}
private void getAdditionalRuns(Set<Integer> readsetIds, Set<Integer> readDataIds, Set<Integer> analysisIds, Set<Integer> outputFileIds, Set<Integer> expRunsToDelete)
{
Set<Integer> runIdsStillInUse = new HashSet<>();
//work backwards, adding additional pipeline jobs that will become orphans:
runIdsStillInUse.addAll(getRunIdsInUse(SequenceAnalysisSchema.TABLE_READSETS, expRunsToDelete, readsetIds));
runIdsStillInUse.addAll(getRunIdsInUse(SequenceAnalysisSchema.TABLE_READ_DATA, expRunsToDelete, readDataIds));
runIdsStillInUse.addAll(getRunIdsInUse(SequenceAnalysisSchema.TABLE_ANALYSES, expRunsToDelete, analysisIds));
runIdsStillInUse.addAll(getRunIdsInUse(SequenceAnalysisSchema.TABLE_OUTPUTFILES, expRunsToDelete, outputFileIds));
expRunsToDelete.removeAll(runIdsStillInUse);
}
private List<Integer> getRunIdsInUse(String tableName, Collection<Integer> expRunsToDelete, Collection<Integer> pks)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromString("runId"), expRunsToDelete, CompareType.IN);
filter.addCondition(FieldKey.fromString("rowid"), pks, CompareType.NOT_IN);
filter.addCondition(FieldKey.fromString("runId"), null, CompareType.NONBLANK);
return new TableSelector(SequenceAnalysisSchema.getTable(tableName), PageFlowUtil.set("runId"), filter, null).getArrayList(Integer.class);
}
private Set<Integer> getExpRunIds(String tableName, Collection<Integer> keys, String pkColName, String runIdCol)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromString(pkColName), keys, CompareType.IN);
filter.addCondition(FieldKey.fromString(runIdCol), null, CompareType.NONBLANK);
TableSelector ts = new TableSelector(SequenceAnalysisSchema.getInstance().getSchema().getTable(tableName), PageFlowUtil.set(runIdCol), filter, null);
return new HashSet<>(ts.getArrayList(Integer.class));
}
private Set<Integer> appendTotal(StringBuilder sb, String tableName, String noun, Collection<Integer> keys, String filterCol, String pkCol)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromString(filterCol), keys, CompareType.IN);
TableSelector ts = new TableSelector(SequenceAnalysisSchema.getInstance().getSchema().getTable(tableName), PageFlowUtil.set(pkCol), filter, null);
Set<Integer> total = new HashSet<>(ts.getArrayList(Integer.class));
sb.append("<br>" + total.size() + " " + noun);
return total;
}
@Override
public boolean handlePost(DeleteForm form, BindException errors) throws Exception
{
try
{
Set<String> ids = DataRegionSelection.getSelected(form.getViewContext(), true);
List<Integer> rowIds = new ArrayList<>();
for (String id : ids)
{
rowIds.add(Integer.parseInt(id));
}
if (SequenceAnalysisSchema.TABLE_ANALYSES.equals(_table.getName()))
{
SequenceAnalysisManager.get().deleteAnalysis(getUser(), getContainer(), rowIds);
}
else if (SequenceAnalysisSchema.TABLE_READSETS.equals(_table.getName()))
{
SequenceAnalysisManager.get().deleteReadset(rowIds, getUser(), getContainer());
}
else if (SequenceAnalysisSchema.TABLE_REF_NT_SEQUENCES.equals(_table.getName()))
{
SequenceAnalysisManager.get().deleteRefNtSequence(getUser(), getContainer(), rowIds);
}
else if (SequenceAnalysisSchema.TABLE_REF_LIBRARIES.equals(_table.getName()))
{
SequenceAnalysisManager.deleteReferenceLibraries(getUser(), rowIds);
}
else if (SequenceAnalysisSchema.TABLE_REF_AA_SEQUENCES.equals(_table.getName()))
{
SequenceAnalysisManager.get().deleteRefAaSequence(rowIds);
}
else if (SequenceAnalysisSchema.TABLE_OUTPUTFILES.equals(_table.getName()))
{
SequenceAnalysisManager.get().deleteOutputFiles(rowIds, getUser(), getContainer(), true);
}
if (form.getJobIds() != null)
{
PipelineService.get().deleteStatusFile(getContainer(), getUser(), true, Arrays.asList(form.getJobIds()));
}
}
catch (OptimisticConflictException e)
{
//if someone else already deleted this, no need to throw exception
_log.error(e.getMessage(), e);
}
catch (Exception e)
{
_log.error(e.getMessage(), e);
errors.reject(ERROR_MSG, e.getMessage());
return false;
}
return true;
}
@Override
public @NotNull URLHelper getSuccessURL(DeleteForm form)
{
URLHelper url = form.getReturnUrlHelper();
return url != null ? url : _table.getGridURL(getContainer()) != null ? _table.getGridURL(getContainer()) : getContainer().getStartURL(getUser());
}
}
@RequiresPermission(ReadPermission.class)
public static class GetSequencePipelineEnabledAction extends ReadOnlyApiAction<Object>
{
@Override
public Object execute(Object o, BindException errors)
{
boolean isExternalPipelineEnabled = Boolean.parseBoolean(System.getProperty(PIPELINE_PROP_NAME));
JSONObject ret = new JSONObject();
ret.put("isPipelineEnabled", isExternalPipelineEnabled);
return new ApiSimpleResponse(ret);
}
}
@RequiresPermission(ReadPermission.class)
public static class GetAnalysisToolDetailsAction extends ReadOnlyApiAction<Object>
{
@Override
public ApiResponse execute(Object form, BindException errors)
{
Map<String, Object> ret = new HashMap<>();
Map<Class<? extends PipelineStep>, String> map = SequencePipelineServiceImpl.get().getPipelineStepTypes();
for (Class<? extends PipelineStep> step : map.keySet())
{
JSONArray list = new JSONArray();
for (PipelineStepProvider<?> fact : SequencePipelineService.get().getProviders(step))
{
list.put(fact.toJSON());
}
ret.put(map.get(step), list);
}
JSONObject resourceSettings = getReourceSettingsJson(getContainer());
if (resourceSettings != null)
{
JSONArray arr = new JSONArray();
arr.put(resourceSettings);
ret.put("resourceSettings", arr);
}
return new ApiSimpleResponse(ret);
}
}
@RequiresPermission(ReadPermission.class)
public static class GetResourceSettingsJsonAction extends ReadOnlyApiAction<Object>
{
@Override
public ApiResponse execute(Object form, BindException errors)
{
Map<String, Object> ret = new HashMap<>();
JSONObject resourceSettings = getReourceSettingsJson(getContainer());
if (resourceSettings != null)
{
JSONArray arr = new JSONArray();
arr.put(resourceSettings);
ret.put("resourceSettings", arr);
}
return new ApiSimpleResponse(ret);
}
}
@RequiresPermission(UpdatePermission.class)
public static class SaveAnalysisAsTemplateAction extends MutatingApiAction<SaveAnalysisAsTemplateForm>
{
@Override
public ApiResponse execute(SaveAnalysisAsTemplateForm form, BindException errors) throws Exception
{
if (StringUtils.isEmpty(form.getJson()))
{
errors.reject(ERROR_MSG, "No analysis Id provided");
return null;
}
if (StringUtils.isEmpty(form.getTaskId()))
{
errors.reject(ERROR_MSG, "No taskId provided");
return null;
}
Map<String, Object> toSave = new CaseInsensitiveHashMap<>();
toSave.put("name", form.getName());
toSave.put("description", form.getDescription());
toSave.put("taskid", form.getTaskId());
toSave.put("json", new JSONObject(form.getJson()));
Container c = getContainer().isWorkbook() ? getContainer().getParent() : getContainer();
TableInfo ti = QueryService.get().getUserSchema(getUser(), c, SequenceAnalysisSchema.SCHEMA_NAME).getTable(SequenceAnalysisSchema.TABLE_SAVED_ANALYSES);
//check if there is an existing
SimpleFilter filter = new SimpleFilter(FieldKey.fromString("name"), form.getName());
filter.addCondition(FieldKey.fromString("taskid"), form.getTaskId());
TableSelector ts = new TableSelector(ti, PageFlowUtil.set("rowid"), filter, null);
if (ts.exists())
{
List<Map<String, Object>> oldKeys = Arrays.asList(ts.getMapArray());
ti.getUpdateService().updateRows(getUser(), getContainer(), Arrays.asList(toSave), oldKeys, null, new HashMap<>());
}
else
{
ti.getUpdateService().insertRows(getUser(), getContainer(), Arrays.asList(toSave), new BatchValidationException(), null, new HashMap<>());
}
return new ApiSimpleResponse("Success", true);
}
}
public static class SaveAnalysisAsTemplateForm
{
private String _name;
private String _description;
private String _taskId;
private String _json;
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
public String getDescription()
{
return _description;
}
public String getTaskId()
{
return _taskId;
}
public void setTaskId(String taskId)