-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAbstractAssayProvider.java
More file actions
2247 lines (1919 loc) · 96 KB
/
AbstractAssayProvider.java
File metadata and controls
2247 lines (1919 loc) · 96 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) 2008-2019 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.api.assay;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.labkey.api.assay.actions.AssayRunUploadForm;
import org.labkey.api.assay.actions.DesignerAction;
import org.labkey.api.assay.actions.UploadWizardAction;
import org.labkey.api.assay.pipeline.AssayRunAsyncContext;
import org.labkey.api.assay.plate.FilterCriteria;
import org.labkey.api.assay.security.DesignAssayPermission;
import org.labkey.api.assay.transform.AnalysisScript;
import org.labkey.api.assay.transform.DataExchangeHandler;
import org.labkey.api.assay.transform.DataTransformService;
import org.labkey.api.audit.AuditLogService;
import org.labkey.api.data.ActionButton;
import org.labkey.api.data.ButtonBar;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerFilter;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.DataRegion;
import org.labkey.api.data.DetailsColumn;
import org.labkey.api.data.DisplayColumn;
import org.labkey.api.data.ImportAliasable;
import org.labkey.api.data.RuntimeSQLException;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.SqlExecutor;
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.defaults.DefaultValueService;
import org.labkey.api.exp.DomainNotFoundException;
import org.labkey.api.exp.ExperimentException;
import org.labkey.api.exp.Lsid;
import org.labkey.api.exp.LsidManager;
import org.labkey.api.exp.ObjectProperty;
import org.labkey.api.exp.OntologyManager;
import org.labkey.api.exp.PropertyDescriptor;
import org.labkey.api.exp.PropertyType;
import org.labkey.api.exp.XarContext;
import org.labkey.api.exp.api.DataType;
import org.labkey.api.exp.api.ExpData;
import org.labkey.api.exp.api.ExpDataRunInput;
import org.labkey.api.exp.api.ExpExperiment;
import org.labkey.api.exp.api.ExpMaterial;
import org.labkey.api.exp.api.ExpObject;
import org.labkey.api.exp.api.ExpProtocol;
import org.labkey.api.exp.api.ExpProtocolApplication;
import org.labkey.api.exp.api.ExpRun;
import org.labkey.api.exp.api.ExpSampleType;
import org.labkey.api.exp.api.ExperimentService;
import org.labkey.api.exp.api.ExperimentUrls;
import org.labkey.api.exp.api.IAssayDomainType;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainProperty;
import org.labkey.api.exp.property.PropertyService;
import org.labkey.api.exp.query.ExpRunTable;
import org.labkey.api.files.FileContentService;
import org.labkey.api.gwt.client.DefaultValueType;
import org.labkey.api.gwt.client.model.GWTDomain;
import org.labkey.api.gwt.client.model.GWTPropertyDescriptor;
import org.labkey.api.module.Module;
import org.labkey.api.pipeline.PipeRoot;
import org.labkey.api.pipeline.PipelineService;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.FilteredTable;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.QuerySettings;
import org.labkey.api.query.QueryView;
import org.labkey.api.query.SimpleValidationError;
import org.labkey.api.query.ValidationException;
import org.labkey.api.query.ValidationException.SEVERITY;
import org.labkey.api.reports.ExternalScriptEngine;
import org.labkey.api.reports.LabKeyScriptEngineManager;
import org.labkey.api.reports.report.r.ParamReplacementSvc;
import org.labkey.api.security.User;
import org.labkey.api.security.permissions.AdminPermission;
import org.labkey.api.settings.AppProps;
import org.labkey.api.study.Dataset;
import org.labkey.api.study.TimepointType;
import org.labkey.api.study.assay.ParticipantVisitResolverType;
import org.labkey.api.study.publish.PublishKey;
import org.labkey.api.study.publish.StudyPublishService;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.HelpTopic;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.DetailsView;
import org.labkey.api.view.NavTree;
import org.labkey.api.view.NotFoundException;
import org.labkey.api.view.ViewContext;
import org.labkey.vfs.FileSystemLike;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.script.ScriptEngine;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
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.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import static java.util.Collections.emptyList;
import static org.labkey.api.data.CompareType.IN;
import static org.labkey.api.util.PageFlowUtil.jsString;
public abstract class AbstractAssayProvider implements AssayProvider
{
public static final String ASSAY_NAME_SUBSTITUTION = "${AssayName}";
public static final String TARGET_STUDY_PROPERTY_NAME = "TargetStudy";
public static final String TARGET_STUDY_PROPERTY_CAPTION = "Target Study";
public static final String PARTICIPANT_VISIT_RESOLVER_PROPERTY_NAME = "ParticipantVisitResolver";
public static final String PARTICIPANT_VISIT_RESOLVER_PROPERTY_CAPTION = "Participant Visit Resolver";
public static final String PARTICIPANTID_PROPERTY_NAME = "ParticipantID";
public static final String VISITID_PROPERTY_NAME = "VisitID";
public static final String PARTICIPANTID_PROPERTY_CAPTION = "Participant ID";
public static final String VISITID_PROPERTY_CAPTION = "Visit ID";
public static final String SPECIMENID_PROPERTY_NAME = "SpecimenID";
public static final String SPECIMENID_PROPERTY_CAPTION = "Specimen ID";
public static final String DATE_PROPERTY_NAME = "Date";
public static final String DATE_PROPERTY_CAPTION = "Date";
public static final String ASSAY_SPECIMEN_MATCH_COLUMN_NAME = "AssayMatch";
public static final String IMPORT_DATA_LINK_NAME = "Import Data";
public static final String MANAGE_ASSAY_DESIGN_LINK = "Manage assay design";
public static final String SET_DEFAULT_VALUES_LINK = "Set default values";
public static final FieldKey BATCH_ROWID_FROM_RUN = FieldKey.fromParts(AssayService.BATCH_COLUMN_NAME, "RowId");
public static final DataType RELATED_FILE_DATA_TYPE = new DataType("RelatedFile");
public static final String SAVE_SCRIPT_FILES_PROPERTY_SUFFIX = "SaveScriptFiles";
public static final String EDITABLE_RUNS_PROPERTY_SUFFIX = "EditableRuns";
public static final String EDITABLE_RESULTS_PROPERTY_SUFFIX = "EditableResults";
public static final String BACKGROUND_UPLOAD_PROPERTY_SUFFIX = "BackgroundUpload";
public static final String QC_ENABLED_PROPERTY_SUFFIX = "QCEnabled";
public static final String PLATE_METADATA_PROPERTY_SUFFIX = "PlateMetadata";
// The result row LSID namespace prefix <code>_resultRowLSIDPrefix</code> should end with this constant.
public static final String RESULT_LSID_PREFIX_PART = "AssayResultRow";
protected final String _protocolLSIDPrefix;
protected final String _runLSIDPrefix;
protected final String _resultRowLSIDPrefix;
protected final Set<Module> _requiredModules = new HashSet<>();
private final Module _declaringModule;
@Nullable protected AssayDataType _dataType;
public int _maxFileInputs = 1;
public AbstractAssayProvider(String protocolLSIDPrefix, String runLSIDPrefix, @Nullable AssayDataType dataType, Module declaringModule)
{
this(protocolLSIDPrefix, runLSIDPrefix, null, dataType, declaringModule);
}
public AbstractAssayProvider(String protocolLSIDPrefix, String runLSIDPrefix, String resultRowLSIDPrefix, @Nullable AssayDataType dataType, Module declaringModule)
{
_protocolLSIDPrefix = protocolLSIDPrefix;
_runLSIDPrefix = runLSIDPrefix;
_resultRowLSIDPrefix = resultRowLSIDPrefix;
if (resultRowLSIDPrefix != null && !resultRowLSIDPrefix.endsWith(RESULT_LSID_PREFIX_PART))
throw new IllegalArgumentException("Assay result row LSID prefix should end with '" + RESULT_LSID_PREFIX_PART + "': " + resultRowLSIDPrefix);
_declaringModule = declaringModule;
_dataType = dataType;
}
@Override
public AssayProviderSchema createProviderSchema(User user, Container container, Container targetStudy)
{
return new AssayProviderSchema(user, container, this, targetStudy);
}
@Override
public ActionURL linkToStudy(User user, Container assayDataContainer, ExpProtocol protocol, @Nullable Container study, @Nullable String datasetCategory, Map<Integer, PublishKey> dataKeys, List<String> errors)
{
try
{
SimpleFilter filter = new SimpleFilter();
filter.addInClause(getTableMetadata(protocol).getResultRowIdFieldKey(), dataKeys.keySet());
AssayProtocolSchema schema = createProtocolSchema(user, assayDataContainer, protocol, study);
TableInfo dataTable = schema.createDataTable(ContainerFilter.Type.CurrentAndSubfolders.create(schema));
FieldKey objectIdFK = getTableMetadata(protocol).getResultRowIdFieldKey();
FieldKey runLSIDFK = new FieldKey(getTableMetadata(protocol).getRunFieldKeyFromResults(), ExpRunTable.Column.LSID.toString());
Map<FieldKey, ColumnInfo> columns = QueryService.get().getColumns(dataTable, Arrays.asList(objectIdFK, runLSIDFK));
ColumnInfo rowIdColumn = columns.get(objectIdFK);
ColumnInfo runLSIDColumn = columns.get(runLSIDFK);
SQLFragment sql = QueryService.get().getSelectSQL(dataTable, columns.values(), filter, null, Table.ALL_ROWS, Table.NO_OFFSET, false);
List<Map<String, Object>> dataMaps = new ArrayList<>();
Container sourceContainer = null;
Map<Container, Set<Integer>> rowIdsByTargetContainer = new HashMap<>();
try (ResultSet rs = new SqlSelector(dataTable.getSchema(), sql).getResultSet())
{
while (rs.next())
{
PublishKey publishKey = dataKeys.get(((Number)rowIdColumn.getValue(rs)).intValue());
Container targetStudyContainer = study;
if (publishKey.getTargetStudy() != null)
targetStudyContainer = publishKey.getTargetStudy();
assert targetStudyContainer != null;
TimepointType studyType = StudyPublishService.get().getTimepointType(targetStudyContainer);
Map<String, Object> dataMap = new HashMap<>();
String runLSID = (String)runLSIDColumn.getValue(rs);
int resultRowId = (int)rowIdColumn.getValue(rs);
String sourceLSID = getSourceLSID(runLSID, publishKey.getDataId(), resultRowId);
if (sourceContainer == null)
{
sourceContainer = ExperimentService.get().getExpRun(runLSID).getContainer();
}
dataMap.put(StudyPublishService.PARTICIPANTID_PROPERTY_NAME, publishKey.getParticipantId());
if (!studyType.isVisitBased())
{
dataMap.put(StudyPublishService.DATE_PROPERTY_NAME, publishKey.getDate());
}
else
{
// add the sequencenum only for visit-based studies, a date based sequencenum will get calculated
// for date-based studies in the ETL layer
dataMap.put(StudyPublishService.SEQUENCENUM_PROPERTY_NAME, publishKey.getVisitId());
}
dataMap.put(StudyPublishService.SOURCE_LSID_PROPERTY_NAME, sourceLSID);
dataMap.put(getTableMetadata(protocol).getDatasetRowIdPropertyName(), publishKey.getDataId());
dataMap.put(StudyPublishService.TARGET_STUDY_PROPERTY_NAME, targetStudyContainer);
// Remember which rows we're planning to link, partitioned by the target study
Set<Integer> rowIds = rowIdsByTargetContainer.get(targetStudyContainer);
if (rowIds == null)
{
rowIds = new HashSet<>();
rowIdsByTargetContainer.put(targetStudyContainer, rowIds);
}
rowIds.add(publishKey.getDataId());
dataMaps.add(dataMap);
}
StudyPublishService.get().checkForAlreadyLinkedRows(user, Pair.of(Dataset.PublishSource.Assay, protocol.getRowId()), errors, rowIdsByTargetContainer);
if (!errors.isEmpty())
{
return null;
}
return StudyPublishService.get().publishData(user, sourceContainer, study, datasetCategory, protocol.getName(),
Pair.of(Dataset.PublishSource.Assay, protocol.getRowId()),
dataMaps, getTableMetadata(protocol).getDatasetRowIdPropertyName(), errors);
}
}
catch (SQLException e)
{
throw new RuntimeSQLException(e);
}
}
protected String getSourceLSID(String runLSID, int dataId, int resultRowId)
{
return runLSID;
}
@Override
public void registerLsidHandler()
{
LsidManager.get().registerHandler(_runLSIDPrefix, new LsidManager.ExpRunLsidHandler());
String resultRowLSIDPrefix = getResultRowLSIDPrefix();
if (resultRowLSIDPrefix != null)
{
LsidManager.get().registerHandler(resultRowLSIDPrefix, new LsidManager.AssayResultLsidHandler(this));
}
}
@Override
public Priority getPriority(ExpProtocol protocol)
{
if (ExpProtocol.ApplicationType.ExperimentRun.equals(protocol.getApplicationType()))
{
Lsid lsid = new Lsid(protocol.getLSID());
if (_protocolLSIDPrefix.equals(lsid.getNamespacePrefix()))
{
return Priority.HIGH;
}
}
return null;
}
@Override
public String getProtocolPattern()
{
return "%:" + Lsid.encodePart(_protocolLSIDPrefix).replace("%", "\\%") + ".%";
}
@Override
@NotNull
public abstract AssayTableMetadata getTableMetadata(@NotNull ExpProtocol protocol);
public static String getDomainURIForPrefix(ExpProtocol protocol, String domainPrefix)
{
String result = getDomainURIForPrefixIfExists(protocol, domainPrefix);
if (result == null)
{
throw new IllegalArgumentException("No domain match for prefix '" + domainPrefix + "' in protocol with LSID '" + protocol.getLSID() + "'");
}
return result;
}
@Nullable
public static String getDomainURIForPrefixIfExists(ExpProtocol protocol, String domainPrefix)
{
String result = null;
for (String uri : protocol.getObjectProperties().keySet())
{
Lsid uriLSID = new Lsid(uri);
if (uriLSID.getNamespacePrefix() != null && uriLSID.getNamespacePrefix().startsWith(domainPrefix))
{
if (result == null)
{
result = uri;
}
else
{
throw new IllegalStateException("More than one domain matches for prefix '" + domainPrefix + "' in protocol with LSID '" + protocol.getLSID() + "'");
}
}
}
return result;
}
public static Domain getDomainByPrefix(ExpProtocol protocol, String domainPrefix, boolean forUpdate)
{
Container container = protocol.getContainer();
return PropertyService.get().getDomain(container, getDomainURIForPrefix(protocol, domainPrefix), forUpdate);
}
@Nullable
public static Domain getDomainByPrefixIfExists(ExpProtocol protocol, String domainPrefix, boolean forUpdate)
{
String domainURI = getDomainURIForPrefixIfExists(protocol, domainPrefix);
if (null == domainURI)
return null;
Container container = protocol.getContainer();
return PropertyService.get().getDomain(container, domainURI, forUpdate);
}
@Override
public Domain getResultsDomain(ExpProtocol protocol)
{
return getResultsDomain(protocol, false);
}
@Override
public Domain getResultsDomain(ExpProtocol protocol, boolean forUpdate)
{
return getDomainByPrefix(protocol, ExpProtocol.ASSAY_DOMAIN_DATA, forUpdate);
}
protected @Nullable Domain getResultsDomainIfExists(ExpProtocol protocol)
{
return getDomainByPrefixIfExists(protocol, ExpProtocol.ASSAY_DOMAIN_DATA, false);
}
@Override
public void beforeDomainChange(User user, ExpProtocol protocol, GWTDomain<GWTPropertyDescriptor> orig, GWTDomain<GWTPropertyDescriptor> update) throws ValidationException
{
}
@Override
public void afterDomainChange(User user, ExpProtocol protocol, GWTDomain<GWTPropertyDescriptor> orig, GWTDomain<GWTPropertyDescriptor> update) throws ValidationException
{
}
@Override
public Domain getBatchDomain(ExpProtocol protocol)
{
return getBatchDomain(protocol, false);
}
@Override
public Domain getBatchDomain(ExpProtocol protocol, boolean forUpdate)
{
return getDomainByPrefix(protocol, ExpProtocol.ASSAY_DOMAIN_BATCH, forUpdate);
}
@Override
public Domain getRunDomain(ExpProtocol protocol)
{
return getRunDomain(protocol,false);
}
@Override
public Domain getRunDomain(ExpProtocol protocol, boolean forUpdate)
{
return getDomainByPrefix(protocol, ExpProtocol.ASSAY_DOMAIN_RUN, forUpdate);
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, Integer value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(sourceContainer, name, value, PropertyType.INTEGER, dataMap, types);
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, Double value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(sourceContainer, name, value, PropertyType.DOUBLE, dataMap, types);
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, Boolean value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(sourceContainer, name, value, PropertyType.BOOLEAN, dataMap, types);
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, Date value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(sourceContainer, name, value, PropertyType.DATE_TIME, dataMap, types);
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, String value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(sourceContainer, name, value, PropertyType.STRING, dataMap, types);
}
protected PropertyDescriptor addProperty(PropertyDescriptor pd, ObjectProperty value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(pd, value == null ? null : value.getValueMvAware(), dataMap, types);
}
protected PropertyDescriptor addProperty(PropertyDescriptor pd, Object value, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
dataMap.put(pd.getName(), value);
if (types != null)
types.add(pd);
return pd;
}
protected PropertyDescriptor addProperty(Container sourceContainer, String name, Object value, PropertyType type, Map<String, Object> dataMap, Collection<PropertyDescriptor> types)
{
return addProperty(createPublishPropertyDescriptor(sourceContainer, name, type), value, dataMap, types);
}
protected PropertyDescriptor createPublishPropertyDescriptor(Container sourceContainer, String name, PropertyType type)
{
String label = name;
if (name.contains(" "))
name = name.replace(" ", "");
PropertyDescriptor pd = new PropertyDescriptor(null, type, name, label, sourceContainer);
if (type.getJavaType() == Double.class)
pd.setFormat("0.###");
return pd;
}
protected DomainProperty addProperty(Domain domain, String name, PropertyType type)
{
return addProperty(domain, name, name, type);
}
protected DomainProperty addProperty(Domain domain, String name, String label, PropertyType type)
{
return addProperty(domain, name, label, type, null);
}
protected DomainProperty addProperty(Domain domain, String name, String label, PropertyType type, @Nullable String description)
{
DomainProperty prop = domain.addProperty();
prop.setLabel(label);
prop.setName(name);
prop.setType(PropertyService.get().getType(domain.getContainer(), type.getXmlName()));
prop.setDescription(description);
if (AbstractAssayProvider.PARTICIPANTID_PROPERTY_NAME.equals(prop.getName()))
prop.setDimension(true);
if (AbstractAssayProvider.VISITID_PROPERTY_NAME.equals(prop.getName()))
prop.setMeasure(false);
if (allowDefaultValues(domain))
{
if (AbstractAssayProvider.PARTICIPANTID_PROPERTY_NAME.equals(prop.getName()) ||
AbstractAssayProvider.SPECIMENID_PROPERTY_NAME.equals(prop.getName()) ||
AbstractAssayProvider.VISITID_PROPERTY_NAME.equals(prop.getName()) ||
AbstractAssayProvider.DATE_PROPERTY_NAME.equals(prop.getName()))
{
prop.setDefaultValueTypeEnum(DefaultValueType.FIXED_EDITABLE);
}
else
{
prop.setDefaultValueTypeEnum(getDefaultValueDefault(domain));
}
}
return prop;
}
public static String getPresubstitutionLsid(String prefix)
{
return getPresubstitutionLsid(prefix, ASSAY_NAME_SUBSTITUTION);
}
public static String getPresubstitutionLsid(String prefix, String idSub)
{
return "urn:lsid:" + XarContext.LSID_AUTHORITY_SUBSTITUTION + ":" + prefix + ".Folder-" + XarContext.CONTAINER_ID_SUBSTITUTION + ":" + idSub;
}
protected String getPresubstitutionRunLsid()
{
return getPresubstitutionLsid(ExpProtocol.ASSAY_DOMAIN_RUN);
}
protected String getPresubstitutionBatchLsid()
{
return getPresubstitutionLsid(ExpProtocol.ASSAY_DOMAIN_BATCH);
}
protected Pair<Domain, Map<DomainProperty, Object>> createRunDomain(Container c, User user)
{
Domain domain = PropertyService.get().createDomain(c, getPresubstitutionRunLsid(), "Run Fields");
domain.setDescription("Define the run fields for this assay design. The user is prompted for these fields once per run and they will be applied to all rows in the run.");
return new Pair<>(domain, Collections.emptyMap());
}
protected Pair<Domain, Map<DomainProperty, Object>> createBatchDomain(Container c, User user)
{
return createBatchDomain(c, user, true);
}
protected Pair<Domain, Map<DomainProperty, Object>> createBatchDomain(Container c, User user, boolean includeStandardProperties)
{
Domain domain = PropertyService.get().createDomain(c, getPresubstitutionBatchLsid(), "Batch Fields");
domain.setDescription("Define the batch fields for this assay design. The user is prompted for these fields once for each set of runs they import to this assay.");
if (includeStandardProperties)
{
List<ParticipantVisitResolverType> resolverTypes = getParticipantVisitResolverTypes();
if (resolverTypes != null && resolverTypes.size() > 0)
{
DomainProperty resolverProperty = addProperty(domain, PARTICIPANT_VISIT_RESOLVER_PROPERTY_NAME, PARTICIPANT_VISIT_RESOLVER_PROPERTY_CAPTION, PropertyType.STRING);
resolverProperty.setHidden(true);
}
DomainProperty studyProp = addProperty(domain, TARGET_STUDY_PROPERTY_NAME, TARGET_STUDY_PROPERTY_CAPTION, PropertyType.STRING);
studyProp.setShownInInsertView(true);
}
return new Pair<>(domain, Collections.emptyMap());
}
/**
* @return domains and their default property values
*/
@Override
public List<Pair<Domain, Map<DomainProperty, Object>>> createDefaultDomains(Container c, User user)
{
List<Pair<Domain, Map<DomainProperty, Object>>> result = new ArrayList<>();
result.add(createBatchDomain(c, user));
result.add(createRunDomain(c, user));
return result;
}
@Override
public List<AssayDataCollector> getDataCollectors(@Nullable Map<String, File> uploadedFiles, AssayRunUploadForm context)
{
return getDataCollectors(uploadedFiles, context, true);
}
@Override
public String getResourceName()
{
return getName();
}
public List<AssayDataCollector> getDataCollectors(@Nullable Map<String, File> uploadedFiles, AssayRunUploadForm<?> context, boolean allowFileReuseOnReRun)
{
List<AssayDataCollector> result = new ArrayList<>();
if (!PipelineDataCollector.getFileQueue(context).isEmpty())
{
result.add(new PipelineDataCollector<>());
}
else
{
if (allowFileReuseOnReRun && context.getReRun() != null)
{
// In the re-run scenario, figure out what files to offer up for reuse
Map<String, File> reusableFiles = new HashMap<>();
// Include any files that were uploaded as part of this request
if (uploadedFiles != null && !uploadedFiles.isEmpty())
{
reusableFiles.putAll(uploadedFiles);
}
else
{
// Look for input data files to the original version of the run
List<? extends ExpData> inputDatas = context.getReRun().getInputDatas(ExpDataRunInput.DEFAULT_ROLE, ExpProtocol.ApplicationType.ExperimentRunOutput);
if (inputDatas.size() == 1)
{
// There's exactly one input, so just use it
addReusableData(reusableFiles, inputDatas.get(0));
}
else if (inputDatas.size() > 1)
{
// The original run was likely run through a transform script
// See https://www.labkey.org/issues/home/Developer/issues/details.view?issueId=16952
for (ExpData inputData : inputDatas)
{
// Look for a file that was created by the "core" step in the protocol. Transformed files
// are created by the ExperimentRunOutput step, and will have a different ActionSequence
if (inputData.getSourceApplication().getApplicationType() == ExpProtocol.ApplicationType.ProtocolApplication && inputData.getSourceApplication().getActionSequence() == ExperimentService.SIMPLE_PROTOCOL_CORE_STEP_SEQUENCE && inputData.getSourceApplication().getActionSequence() == ExperimentService.SIMPLE_PROTOCOL_CORE_STEP_SEQUENCE)
{
if (reusableFiles.size() >= getMaxFileInputs())
{
throw new IllegalStateException("More than " + getMaxFileInputs() + " primary data file(s) associated with run: " + context.getReRun().getRowId() + "(\"" + reusableFiles.values() + "\" and \"" + inputData + "\")");
}
addReusableData(reusableFiles, inputData);
}
}
}
}
// Filter out any files that aren't under the current pipeline root, since we won't be able to resolve
// them successfully due to security restrictions for what's an allowable input to the new run. See issue 18387.
PipeRoot pipeRoot = PipelineService.get().findPipelineRoot(context.getContainer());
for (Iterator<Map.Entry<String, File>> iter = reusableFiles.entrySet().iterator(); iter.hasNext(); )
{
Map.Entry<String, File> entry = iter.next();
// If it's not under the current pipeline root
if (pipeRoot == null || !pipeRoot.isUnderRoot(entry.getValue()))
{
// Remove it from the collection
iter.remove();
}
}
if (getMaxFileInputs() == 1)
{
// This assay only allows for one input file, so keep it simple with separate options
// to reuse or re-upload
if (!reusableFiles.isEmpty())
{
var reusableFileLike = FileSystemLike.wrapFiles(reusableFiles);
result.add(new PreviouslyUploadedDataCollector<>(reusableFileLike));
}
result.add(new FileUploadDataCollector<>(getMaxFileInputs()));
}
else
{
// We allow multiple files per assay run, so give a UI that lets the user mix and match
// between existing ones and new ones
result.add(new FileUploadDataCollector<>(getMaxFileInputs(), reusableFiles));
}
}
else
{
// Normal (non-rerun) scenario
if (uploadedFiles != null)
{
var uploadedFileLikes = FileSystemLike.wrapFiles(uploadedFiles);
result.add(new PreviouslyUploadedDataCollector<>(uploadedFileLikes));
}
result.add(new FileUploadDataCollector<>(getMaxFileInputs()));
}
}
return result;
}
private void addReusableData(Map<String, File> reusableFiles, ExpData inputData)
{
// Not all datas are associated with a file
if (inputData.getFile() != null)
{
reusableFiles.put(AssayDataCollector.PRIMARY_FILE + (reusableFiles.size() == 0 ? "" : Integer.toString(reusableFiles.size())), inputData.getFile());
}
}
@Override
public AssayRunCreator getRunCreator()
{
return new DefaultAssayRunCreator<>(this);
}
@Override
public ExpProtocol createAssayDefinition(User user, Container container, String name, String description, ExpProtocol.Status status, XarContext context)
throws ExperimentException
{
String protocolLsid = getAssayProtocolLsid(container, name, context);
ExpProtocol protocol = ExperimentService.get().createExpProtocol(container, ExpProtocol.ApplicationType.ExperimentRun, name);
protocol.setProtocolDescription(description);
protocol.setLSID(protocolLsid);
protocol.setMaxInputMaterialPerInstance(1);
protocol.setMaxInputDataPerInstance(1);
protocol.setStatus(status);
return ExperimentService.get().insertSimpleProtocol(protocol, user);
}
protected String getAssayProtocolLsid(Container container, String assayName, XarContext context)
{
return new Lsid(_protocolLSIDPrefix, "Folder-" + container.getRowId(), assayName).toString();
}
@Override
@Nullable
public Pair<ExpProtocol.AssayDomainTypes, DomainProperty> findTargetStudyProperty(ExpProtocol protocol)
{
DomainProperty targetStudyDP;
Domain domain = getResultsDomain(protocol);
if (domain != null && null != (targetStudyDP = domain.getPropertyByName(AbstractAssayProvider.TARGET_STUDY_PROPERTY_NAME)))
return new Pair<>(ExpProtocol.AssayDomainTypes.Result, targetStudyDP);
domain = getRunDomain(protocol);
if (domain != null && null != (targetStudyDP = domain.getPropertyByName(AbstractAssayProvider.TARGET_STUDY_PROPERTY_NAME)))
return new Pair<>(ExpProtocol.AssayDomainTypes.Run, targetStudyDP);
domain = getBatchDomain(protocol);
if (domain != null && null != (targetStudyDP = domain.getPropertyByName(AbstractAssayProvider.TARGET_STUDY_PROPERTY_NAME)))
return new Pair<>(ExpProtocol.AssayDomainTypes.Batch, targetStudyDP);
return null;
}
// CONSIDER: combining with .getTargetStudy()
// UNDONE: Doesn't look at TargetStudy in Results domain yet.
@Override
public Set<Container> getAssociatedStudyContainers(ExpProtocol protocol, Collection<Integer> rowIds)
{
Pair<ExpProtocol.AssayDomainTypes, DomainProperty> pair = findTargetStudyProperty(protocol);
if (pair == null)
return Collections.emptySet();
DomainProperty targetStudyColumn = pair.second;
ResolverCache cache = new ResolverCache();
Set<Container> result = new HashSet<>();
for (ExpData data : getDatasForResultRows(rowIds, protocol, cache))
{
Container container = null;
if (data.getRunId() != null)
{
ExpRun run = cache.getRun(data.getRunId());
if (run != null)
{
// Ignore Results domain TargetStudy for now.
// The participant resolver will find the TargetStudy on the row.
ExpObject source = switch (pair.first)
{
case Run -> run;
default -> cache.getBatch(run);
};
if (source != null)
{
Map<String, Object> properties = OntologyManager.getProperties(source.getContainer(), source.getLSID());
String targetStudyId = (String) properties.get(targetStudyColumn.getPropertyURI());
if (targetStudyId != null)
container = ContainerManager.getForId(targetStudyId);
}
}
}
result.add(container);
}
return result;
}
@Nullable
public final ExpData getDataForDataRow(int resultRowId, ExpProtocol protocol)
{
Set<ExpData> matches = getDatasForResultRows(Collections.singleton(resultRowId), protocol, new ResolverCache());
return matches.isEmpty() ? null : matches.iterator().next();
}
/** Resolve result rows to their owning ExpData object. Optional method for assays that support link to study */
public Set<ExpData> getDatasForResultRows(Collection<Integer> rowIds, ExpProtocol protocol, ResolverCache cache)
{
return Collections.emptySet();
}
public static class ResolverCache
{
private final Map<Integer, ExpData> _dataById = new HashMap<>();
private final Map<Integer, ExpRun> _runById = new HashMap<>();
private final Map<ExpRun, ExpExperiment> _batchByRun = new HashMap<>();
private <K, T extends ExpObject> T get(K key, Map<K, T> cache, Supplier<T> supplier)
{
if (key == null)
{
return null;
}
// Don't use computeIfAbsent() because it treats null values as if they weren't in the map at all
if (cache.containsKey(key))
{
return cache.get(key);
}
T result = supplier.get();
cache.put(key, result);
return result;
}
public ExpData getDataById(int dataId)
{
return get(dataId, _dataById, () -> ExperimentService.get().getExpData(dataId));
}
public ExpRun getRun(int runId)
{
return get(runId, _runById, () -> ExperimentService.get().getExpRun(runId));
}
public ExpExperiment getBatch(ExpRun run)
{
return get(run, _batchByRun, () -> AssayService.get().findBatch(run));
}
}
@Override
public ActionURL getImportURL(Container container, ExpProtocol protocol)
{
return PageFlowUtil.urlProvider(AssayUrls.class).getProtocolURL(container, protocol, UploadWizardAction.class);
}
public static ParticipantVisitResolverType findType(String name, List<ParticipantVisitResolverType> types)
{
if (name == null)
{
return null;
}
String decodedName = ParticipantVisitResolverType.Serializer.decodeBaseStringValue(name);
if (decodedName == null)
{
return null;
}
for (ParticipantVisitResolverType type : types)
{
if (decodedName.equals(type.getName()))
{
return type;
}
}
throw new NotFoundException("Unexpected resolver type: " + name);
}
private Set<String> getPropertyDomains(ExpProtocol protocol)
{
Set<String> result = new HashSet<>();
for (ObjectProperty prop : protocol.getObjectProperties().values())
{
Lsid lsid = new Lsid(prop.getPropertyURI());
if (lsid.getNamespacePrefix() != null && lsid.getNamespacePrefix().startsWith(ExpProtocol.ASSAY_DOMAIN_PREFIX))
{
result.add(prop.getPropertyURI());
}
}
return result;
}
@Override
public @NotNull List<Domain> getDomains(ExpProtocol protocol)
{
List<Domain> domains = new ArrayList<>();
for (String uri : getPropertyDomains(protocol))
{
Domain domain = PropertyService.get().getDomain(protocol.getContainer(), uri);
if (domain != null)
domains.add(domain);
}
// Rely on the assay provider to return a list of default domains in the right order (Collections.sort() is
// stable so that domains that haven't been inserted and have id 0 stay in the same order), and rely on the fact
// that they get inserted in the same order, so they will have ascending ids.
domains.sort(Comparator.comparing(Domain::getTypeId));
return domains;
}
@Override
public @NotNull List<Pair<Domain, Map<DomainProperty, Object>>> getDomainsAndDefaultValues(ExpProtocol protocol)
{
List<Pair<Domain, Map<DomainProperty, Object>>> domainAndDefaultValues = new ArrayList<>();
for (Domain domain : getDomains(protocol))
{
Map<DomainProperty, Object> values = DefaultValueService.get().getDefaultValues(domain.getContainer(), domain);
domainAndDefaultValues.add(Pair.of(domain, values));
}
return domainAndDefaultValues;
}
@Override
public Pair<ExpProtocol, List<Pair<Domain, Map<DomainProperty, Object>>>> getAssayTemplate(User user, Container targetContainer)
{
ExpProtocol copy = ExperimentService.get().createExpProtocol(targetContainer, ExpProtocol.ApplicationType.ExperimentRun, "Unknown");
copy.setName(null);
return new Pair<>(copy, createDefaultDomains(targetContainer, user));
}
@Override
public Pair<ExpProtocol, List<Pair<Domain, Map<DomainProperty, Object>>>> getAssayTemplate(User user, Container targetContainer, ExpProtocol toCopy)
{
ExpProtocol copy = ExperimentService.get().createExpProtocol(targetContainer, toCopy.getApplicationType(), toCopy.getName());
copy.setDescription(toCopy.getDescription());
Map<String, ObjectProperty> copiedProps = new HashMap<>();
for (ObjectProperty prop : toCopy.getObjectProperties().values())
{
copiedProps.put(createPropertyURI(copy, prop.getName()), prop);
}
copy.setObjectProperties(copiedProps);
List<Pair<Domain, Map<DomainProperty, Object>>> originalDomains = getDomainsAndDefaultValues(toCopy);
List<Pair<Domain, Map<DomainProperty, Object>>> copiedDomains = new ArrayList<>(originalDomains.size());
for (Pair<Domain, Map<DomainProperty, Object>> domainInfo : originalDomains)
{
Domain domain = domainInfo.getKey();
Map<DomainProperty, Object> originalDefaults = domainInfo.getValue();
Map<DomainProperty, Object> copiedDefaults = new HashMap<>();
String uri = domain.getTypeURI();
Lsid domainLsid = new Lsid(uri);
String name = domain.getName();
String defaultPrefix = toCopy.getName() + " ";
if (name.startsWith(defaultPrefix))
name = name.substring(defaultPrefix.length());
Domain domainCopy = PropertyService.get().createDomain(targetContainer, getPresubstitutionLsid(domainLsid.getNamespacePrefix()), name);
domainCopy.setDescription(domain.getDescription());
for (DomainProperty propSrc : domain.getProperties())
{
DomainProperty propCopy = domainCopy.addProperty();
copiedDefaults.put(propCopy, originalDefaults.get(propSrc));
propCopy.copyFrom(propSrc, targetContainer);
}
copiedDomains.add(new Pair<>(domainCopy, copiedDefaults));
}
return new Pair<>(copy, copiedDomains);
}
@Override
public boolean isFileLinkPropertyAllowed(ExpProtocol protocol, Domain domain)
{
Lsid domainLsid = new Lsid(domain.getTypeURI());
return domainLsid.getNamespacePrefix().equals(ExpProtocol.ASSAY_DOMAIN_BATCH) ||
domainLsid.getNamespacePrefix().equals(ExpProtocol.ASSAY_DOMAIN_RUN) ||
domainLsid.getNamespacePrefix().equals(ExpProtocol.ASSAY_DOMAIN_DATA);