-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathNameGenerator.java
More file actions
2963 lines (2533 loc) · 136 KB
/
NameGenerator.java
File metadata and controls
2963 lines (2533 loc) · 136 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) 2018-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.data;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.action.ApiUsageException;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.collections.CaseInsensitiveHashSet;
import org.labkey.api.exp.PropertyType;
import org.labkey.api.exp.api.ExpData;
import org.labkey.api.exp.api.ExpDataClass;
import org.labkey.api.exp.api.ExpLineageOptions;
import org.labkey.api.exp.api.ExpMaterial;
import org.labkey.api.exp.api.ExpObject;
import org.labkey.api.exp.api.ExpSampleType;
import org.labkey.api.exp.api.ExperimentService;
import org.labkey.api.exp.api.SampleTypeService;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainProperty;
import org.labkey.api.gwt.client.model.GWTPropertyDescriptor;
import org.labkey.api.query.BatchValidationException;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.UserSchema;
import org.labkey.api.query.ValidationException;
import org.labkey.api.security.User;
import org.labkey.api.util.GUID;
import org.labkey.api.util.JunitUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.StringExpression;
import org.labkey.api.util.StringExpressionFactory;
import org.labkey.api.util.StringExpressionFactory.AbstractStringExpression.NullValueBehavior;
import org.labkey.api.util.StringExpressionFactory.FieldKeyStringExpression;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.SubstitutionFormat;
import java.io.IOException;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.labkey.api.exp.api.ExpMaterial.ALIQUOTED_FROM_INPUT;
import static org.labkey.api.exp.api.ExpMaterial.ALIQUOTED_FROM_INPUT_LABEL;
import static org.labkey.api.exp.api.ExpRunItem.INPUT_PARENT;
import static org.labkey.api.exp.api.ExperimentJSONConverter.DATA_INPUTS;
import static org.labkey.api.exp.api.ExperimentJSONConverter.MATERIAL_INPUTS;
import static org.labkey.api.exp.api.ExperimentJSONConverter.MATERIAL_INPUTS_ALIAS_PREFIX;
import static org.labkey.api.util.SubstitutionFormat.dailySampleCount;
import static org.labkey.api.util.SubstitutionFormat.monthlySampleCount;
import static org.labkey.api.util.SubstitutionFormat.weeklySampleCount;
import static org.labkey.api.util.SubstitutionFormat.yearlySampleCount;
public class NameGenerator
{
/**
* full expression: ${NamePrefix:withCounter(counterStartIndex?: number, counterNumberFormat?: string, extraparam: enum)}
* use regex to match the content inside the outer ${}
* Examples:
* ${AliquotedFrom}-:withCounter : parentSample-1
* ${AliquotedFrom}-${SourceParent/Property}-:withCounter : parentSample-parentSource-1
* ${AliquotedFrom}.:withCounter() : parentSample.1
* ${AliquotedFrom}-:withCounter(1000) : parentSample-1000
* ${AliquotedFrom}-:withCounter(1, '000') : parentSample-001
* ${AliquotedFrom}-:withCounter(1, '000', NoGap) : parentSample-001
*/
public static final String WITH_COUNTER_REGEX = "(.+):withCounter\\(?(\\d*)?,?\\s*'?(\\d*)?'?,?\\s*'?([a-zA-Z]*)?'?\\)?";
public static final Pattern WITH_COUNTER_PATTERN = Pattern.compile(WITH_COUNTER_REGEX, Pattern.CASE_INSENSITIVE);
public static final String WITH_COUNTER_NO_GAP_PARAM = "NoGap"; // named parameter to enforce continuity in sequence
public static final String EXPERIMENTAL_WITH_COUNTER = "UseStrictIncrementCounter"; // sql server
public static final String EXPERIMENTAL_ALLOW_GAP_COUNTER = "AllowCounterGap"; // postgres
/**
* Examples:
* ${genId:minValue(100)}
* ${genId:minValue('100')}
* ${sampleCount:minValue(10)}
*/
public static final String WITH_START_IND_REGEX = ".*\\$\\{%s:minValue\\('?(\\d*)?'?\\).*";
/**
* Ancestor lookup example:
* ..[MaterialInputs]
* ..[DataInputs]
* ..[MaterialInputs/SampleType1]
* ..[MaterialInputs::SampleType1]
*/
public static final String ANCESTOR_INPUT_PREFIX_MATERIAL = "..[MaterialInputs/";
public static final String ANCESTOR_INPUT_PREFIX_MATERIAL_NOSLASH = "..[MaterialInputs::";
public static final String ANCESTOR_INPUT_PREFIX_DATA = "..[DataInputs/";
public static final String ANCESTOR_INPUT_PREFIX_DATA_NOSLASH = "..[DataInputs::";
public static final String ANCESTOR_INPUT_REGEX = "\\.\\.\\[((Material|Data)Inputs(/|::)?(.*))]";
public static final Pattern ANCESTOR_INPUT_PATTERN = Pattern.compile(ANCESTOR_INPUT_REGEX);
public static Date PREVIEW_DATETIME_VALUE;
public static java.sql.Date PREVIEW_DATE_VALUE;
public static java.sql.Time PREVIEW_TIME_VALUE;
public static Date PREVIEW_MODIFIED_DATE_VALUE;
static
{
try
{
PREVIEW_DATETIME_VALUE = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse("2021/04/28 08:30");
PREVIEW_DATE_VALUE = new java.sql.Date(PREVIEW_DATETIME_VALUE.getTime());
PREVIEW_TIME_VALUE = new java.sql.Time(PREVIEW_DATETIME_VALUE.getTime());
PREVIEW_MODIFIED_DATE_VALUE = new SimpleDateFormat("yyyy/MM/dd").parse("2021/05/11");
}
catch (ParseException e)
{
PREVIEW_DATE_VALUE = null;
PREVIEW_DATETIME_VALUE = null;
PREVIEW_TIME_VALUE = null;
PREVIEW_MODIFIED_DATE_VALUE = null;
}
}
public static final String COUNTER_SEQ_PREFIX = "NameGenCounter-";
public enum EntityCounter
{
genId,
rootSampleCount,
sampleCount
}
public enum SubstitutionValue
{
AliquotedFrom("Sample112"),
DataInputsSearch(null, "~DataInputs"),
DataInputs("Data101"),
Inputs("Parent101"),
MaterialInputsSearch(null, "~MaterialInputs"),
MaterialInputs("Sample101"),
batchRandomId(3294),
containerPath("containerPathValue"),
contextPath("contextPathValue"),
sampleCount(240),
rootSampleCount(124),
dailySampleCount(14), // sample counts can both be SubstitutionValue as well as modifiers
dataRegionName("dataRegionNameValue"),
genId(1001),
monthlySampleCount(150),
now(null)
{
@Override
public Object getPreviewValue()
{
return PREVIEW_DATETIME_VALUE;
}
},
queryName("queryNameValue"),
randomId(3294),
schemaName("schemaNameValue"),
schemaPath("schemaPathValue"),
selectionKey("selectionKeyValue"),
weeklySampleCount(25),
withCounter(null), // see CounterExpressionPart.getValue
yearlySampleCount(412),
folderPrefix("folderPrefixValue");
private final String _key;
private final Object _previewValue;
SubstitutionValue(Object previewValue, String key)
{
_key = key == null ? this.name() : key;
_previewValue = previewValue;
}
SubstitutionValue(Object previewValue)
{
this(previewValue, null);
}
public Object getPreviewValue()
{
return _previewValue;
}
public String getKey()
{
return _key;
}
public static Map<String, Object> getPreviewMap()
{
Map<String, Object> values = new CaseInsensitiveHashMap<>();
for (SubstitutionValue substitutionValue : SubstitutionValue.values())
{
if (substitutionValue.getPreviewValue() != null)
values.put(substitutionValue.getKey(), substitutionValue.getPreviewValue());
}
return values;
}
}
public static final Set<String> SAMPLE_COUNTER_SUBSTITUTIONS = new HashSet<>(Arrays.asList(SubstitutionValue.dailySampleCount.name(), SubstitutionValue.weeklySampleCount.name(), SubstitutionValue.monthlySampleCount.name(), SubstitutionValue.yearlySampleCount.name()));
private final TableInfo _parentTable;
public FieldKeyStringExpression getParsedNameExpression()
{
return _parsedNameExpression;
}
private final FieldKeyStringExpression _parsedNameExpression;
public TableInfo getParentTable()
{
return _parentTable;
}
public Map<FieldKey, TableInfo> getExprLookups()
{
return _exprLookups;
}
public Map<FieldKey, List<String>> getExpParentLookupFields()
{
return _expParentLookupFields;
}
public Map<FieldKey, NameExpressionAncestorPartOption> getPartAncestorOptions()
{
return _partAncestorOptions;
}
public Map<String, ExpSampleType> getSampleTypes()
{
return _sampleTypes;
}
public Map<String, ExpDataClass> getDataClasses()
{
return _dataClasses;
}
public boolean isAllBulkRemapCache()
{
return _allBulkRemapCache;
}
public Container getContainer()
{
return _container;
}
public record SampleNameExpressionSummary(boolean hasProjectSampleCounter, boolean hasProjectSampleRootCounter, long minProjectSampleCounter, long minProjectSampleRootCounter) {}
public record ExpressionSummary(SampleNameExpressionSummary sampleSummary, boolean hasDateBasedSampleCounter, boolean hasParentInputs, boolean hasParentLookup, boolean hasAncestorSearch) {}
// extracted from name expression after parsing
private ExpressionSummary _expressionSummary;
private Map<FieldKey, TableInfo> _exprLookups = Collections.emptyMap();
private Map<FieldKey, List<String>> _expParentLookupFields = new HashMap<>();
private Map<FieldKey, NameExpressionAncestorPartOption> _partAncestorOptions;
private final Map<String, ExpSampleType> _sampleTypes = new HashMap<>();
private final Map<String, ExpDataClass> _dataClasses = new HashMap<>();
private final Container _container;
private final boolean _validateSyntax;
private final List<String> _syntaxErrors = new ArrayList<>();
private final List<String> _syntaxWarnings = new ArrayList<>();
private String _previewName;
private final List<? extends GWTPropertyDescriptor> _domainProperties; // used for name expression validation at creation time, before the tableInfo is available
private final String _currentDataTypeName; // used for name expression validation/preview at creation time, before the SampleType or DataClass is created
private final boolean _allBulkRemapCache;
public NameGenerator(@NotNull String nameExpression, @Nullable TableInfo parentTable, boolean allowSideEffects, @Nullable Map<String, String> importAliases, @Nullable Container container, Function<String, Long> getNonConflictCountFn, String counterSeqPrefix, boolean validateSyntax, @Nullable List<? extends GWTPropertyDescriptor> domainProperties, String currentDataTypeName, boolean allBulkRemapCache)
{
_parentTable = parentTable;
_container = container;
_parsedNameExpression = NameGenerationExpression.create(nameExpression, false, NullValueBehavior.ReplaceNullWithBlank, allowSideEffects, container, getNonConflictCountFn, counterSeqPrefix, validateSyntax);
_validateSyntax = validateSyntax;
_domainProperties = domainProperties;
_currentDataTypeName = currentDataTypeName;
_allBulkRemapCache = allBulkRemapCache;
initialize(importAliases);
}
public NameGenerator(@NotNull String nameExpression, @Nullable TableInfo parentTable, boolean allowSideEffects, @Nullable Map<String, String> importAliases, @Nullable Container container, Function<String, Long> getNonConflictCountFn, String counterSeqPrefix, boolean validateSyntax, @Nullable List<? extends GWTPropertyDescriptor> domainProperties, String currentDataTypeName)
{
this(nameExpression, parentTable, allowSideEffects, importAliases, container, getNonConflictCountFn, counterSeqPrefix, validateSyntax, domainProperties, currentDataTypeName, false);
}
public NameGenerator(@NotNull String nameExpression, @Nullable TableInfo parentTable, boolean allowSideEffects, @Nullable Map<String, String> importAliases, @Nullable Container container, Function<String, Long> getNonConflictCountFn, String counterSeqPrefix, boolean validateSyntax, @Nullable List<? extends GWTPropertyDescriptor> domainProperties)
{
this(nameExpression, parentTable, allowSideEffects, importAliases, container, getNonConflictCountFn, counterSeqPrefix, validateSyntax, domainProperties, null);
}
public NameGenerator(@NotNull String nameExpression, @Nullable TableInfo parentTable, boolean allowSideEffects, @Nullable Map<String, String> importAliases, @Nullable Container container, Function<String, Long> getNonConflictCountFn, String counterSeqPrefix)
{
this(nameExpression, parentTable, allowSideEffects, importAliases, container, getNonConflictCountFn, counterSeqPrefix, false, null);
}
public NameGenerator(@NotNull String nameExpression, @Nullable TableInfo parentTable, boolean allowSideEffects, Container container, Function<String, Long> getNonConflictCountFn, String counterSeqPrefix)
{
this(nameExpression, parentTable, allowSideEffects, null, container, getNonConflictCountFn, counterSeqPrefix);
}
public NameGenerator(@NotNull FieldKeyStringExpression nameExpression, @Nullable TableInfo parentTable, @Nullable Container container)
{
_parentTable = parentTable;
_parsedNameExpression = nameExpression;
_container = container;
_validateSyntax = false;
_domainProperties = null;
_currentDataTypeName = null;
_allBulkRemapCache = true;
initialize(null);
}
public NameGenerator(@NotNull FieldKeyStringExpression nameExpression, @Nullable TableInfo parentTable)
{
this(nameExpression, parentTable, null);
}
public ExpressionSummary getExpressionSummary()
{
return _expressionSummary;
}
public void setExpressionSummary(ExpressionSummary expressionSummary)
{
_expressionSummary = expressionSummary;
}
public List<String> getSyntaxErrors()
{
return _syntaxErrors;
}
public List<String> getSyntaxWarnings()
{
return _syntaxWarnings;
}
public String getPreviewName()
{
return _previewName;
}
public void setPreviewName(String previewName)
{
_previewName = previewName;
}
public static NameExpressionValidationResult getValidationMessages(@Nullable TableInfo tableInfo, @Nullable String currentDataTypeName, @NotNull String nameExpression, @Nullable List<? extends GWTPropertyDescriptor> properties, @Nullable Map<String, String> importAliases, @NotNull Container container)
{
List<String> errorMessages = getMismatchedTagErrors(nameExpression);
Pair<List<String>, List<String>> reservedFieldResults = getReservedFieldValidationResults(nameExpression);
errorMessages.addAll(reservedFieldResults.first);
List<String> warningMessages = new ArrayList<>(reservedFieldResults.second);
if (!errorMessages.isEmpty())
return new NameExpressionValidationResult(errorMessages, warningMessages, null);
warningMessages.addAll(getFieldMissingBracesWarnings(nameExpression, properties, importAliases));
NameExpressionValidationResult fieldMessages = getSubstitutionPartValidationResults(nameExpression, tableInfo, properties, importAliases, container, currentDataTypeName);
errorMessages.addAll(fieldMessages.errors());
warningMessages.addAll(fieldMessages.warnings());
return new NameExpressionValidationResult(errorMessages, warningMessages, fieldMessages.previews());
}
static NameExpressionValidationResult getSubstitutionPartValidationResults(@NotNull String nameExpression, @Nullable TableInfo tableInfo, @Nullable List<? extends GWTPropertyDescriptor> properties, @Nullable Map<String, String> importAliases, @NotNull Container container, @Nullable String currentDataTypeName)
{
NameGenerator generator = new NameGenerator(nameExpression, tableInfo,true, importAliases, container, null, null, true, properties, currentDataTypeName);
return new NameExpressionValidationResult(generator.getSyntaxErrors(), generator.getSyntaxWarnings(), generator.getPreviewName() != null ? Collections.singletonList(generator.getPreviewName()) : null);
}
static List<String> getFieldMissingBracesWarnings(@NotNull String nameExpression, @Nullable List<? extends GWTPropertyDescriptor> properties, @Nullable Map<String, String> importAliases)
{
Set<String> substitutionFields = new CaseInsensitiveHashSet();
if (importAliases != null)
substitutionFields.addAll(importAliases.keySet());
if (properties != null)
properties.forEach(field -> substitutionFields.add(field.getName()));
substitutionFields.remove(null);
if (substitutionFields.isEmpty())
return Collections.emptyList();
List<String> warningMessages = new ArrayList<>();
String lcExpression = nameExpression.toLowerCase();
String allFieldsLc = StringUtils.join(substitutionFields, "\n").toLowerCase();
for (String subField : substitutionFields)
{
String lcSub = subField.toLowerCase();
int lcIndex = lcExpression.indexOf(lcSub);
if (lcIndex != -1)
{
if (lcIndex > 0)
{
char preChar = lcExpression.charAt(lcIndex - 1);
if (Character.isLetter(preChar))
continue;
else
{
// Check if expression is substring of another expression, which is enclosed by ${}.
// If both 'Exp Name' and 'Name' fields are present, ${Exp Name} should by pass check on 'Name' field.
if (StringUtils.countMatches(allFieldsLc, lcSub) >= 2)
{
String prevStr = nameExpression.substring(0, lcIndex);
int prevOpenCount = StringUtils.countMatches(prevStr, "${");
int prevCloseCount = StringUtils.countMatches(prevStr, "}");
if ((prevOpenCount - prevCloseCount) == 1)
continue;
}
}
}
if (lcExpression.length() > (lcIndex + lcSub.length()))
{
char postChar = lcExpression.charAt(lcIndex + lcSub.length());
if (Character.isLetter(postChar))
continue;
}
warningMessages.addAll(SubstitutionFormat.validateNonFunctionalSyntax(subField, nameExpression, lcIndex, "field", true));
}
}
return warningMessages;
}
public static String validateFieldKeyConflict(String fieldKey)
{
String fieldKeyLc = fieldKey.toLowerCase();
Set<String> formatNames = new HashSet<>(SubstitutionFormat.getFormatNames());
formatNames.add(SubstitutionValue.withCounter.name());
for (String formatName : formatNames)
{
String lcFormatName = ":" + formatName.toLowerCase();
int matchInd = fieldKeyLc.indexOf(lcFormatName);
if (matchInd > -1)
return "'" + fieldKey.substring(matchInd, matchInd + lcFormatName.length()) + "' is a reserved pattern.";
}
for (SubstitutionValue subValue : SubstitutionValue.values())
{
if (subValue.getKey().equalsIgnoreCase(fieldKey))
return "'" + fieldKey + "' is a reserved name.";
}
return null;
}
static Pair<List<String>, List<String>> getReservedFieldValidationResults(String nameExpression)
{
// For each substitution format, find its location in the string
// validate punctuation and arguments.
List<String> warningMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
String lcExpression = nameExpression.toLowerCase();
SubstitutionFormat.getFormatNames().forEach(formatName -> {
String lcFormatName = formatName.toLowerCase();
int lcIndex = lcExpression.indexOf(":" + lcFormatName);
if (lcIndex > -1)
errorMessages.addAll(SubstitutionFormat.validateSyntax(formatName, nameExpression, lcIndex));
});
for (SubstitutionValue subValue : SubstitutionValue.values())
{
String lcSub = subValue.getKey().toLowerCase();
int lcIndex = lcExpression.indexOf(lcSub);
if (lcIndex != -1)
{
/*
* also check that the part is not preceded by an alphabetic letter
* - "unknown" contains "now", but should bypass reserved key word check
* - "DataInputs" contains "Input", but should bypass "Input" check
*/
if (lcIndex > 0)
{
char preChar = lcExpression.charAt(lcIndex - 1);
if (Character.isLetter(preChar))
continue;
}
if (lcExpression.length() > (lcIndex + lcSub.length()))
{
char postChar = lcExpression.charAt(lcIndex + lcSub.length());
if (Character.isLetter(postChar))
continue;
}
if (subValue.equals(SubstitutionValue.withCounter))
{
Pair<List<String>, List<String>> withCounterResults = validateWithCounterSyntax(nameExpression, lcIndex);
errorMessages.addAll(withCounterResults.first);
warningMessages.addAll(withCounterResults.second);
}
else
{
warningMessages.addAll(SubstitutionFormat.validateNonFunctionalSyntax(subValue.getKey(), nameExpression, lcIndex));
}
}
}
return new Pair<>(errorMessages, warningMessages);
}
static Pair<List<String>, List<String>> validateWithCounterSyntax(String nameExpression, int index)
{
List<String> warningMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
int start = index;
// check withCount is inside ${}
String prevStr = nameExpression.substring(0, index);
int prevOpenCount = StringUtils.countMatches(prevStr, "${") - StringUtils.countMatches(prevStr, "\\${");
int prevCloseCount = StringUtils.countMatches(prevStr, "}") - StringUtils.countMatches(prevStr, "\\}");
String postStr = nameExpression.substring(index);
int postOpenCount = StringUtils.countMatches(postStr, "${") - StringUtils.countMatches(postStr, "\\${");
int postCloseCount = StringUtils.countMatches(postStr, "}") - StringUtils.countMatches(postStr, "\\}");
if ((prevOpenCount - prevCloseCount) != 1 || (postCloseCount - postOpenCount) != 1)
warningMessages.add(String.format("The '%s' substitution pattern starting at position %d should be enclosed in ${}.", SubstitutionValue.withCounter.name(), start));
if (nameExpression.charAt(index-1) != ':')
warningMessages.add(String.format("The '%s' substitution pattern starting at position %d should be preceded by a colon.", SubstitutionValue.withCounter.name(), start));
else
start = start-1;
int startParen = index + SubstitutionValue.withCounter.name().length();
if (startParen >= nameExpression.length() || nameExpression.charAt(startParen) != '(')
return new Pair<>(errorMessages, warningMessages);
int endParen = nameExpression.indexOf(")", start);
if (endParen == -1)
errorMessages.add(String.format("No ending parentheses found for the '%s' substitution pattern starting at index %d.", SubstitutionValue.withCounter.name(), start));
else
{
int commaIndex = nameExpression.indexOf(",", start);
int firstQuoteIndex = nameExpression.indexOf("'", commaIndex + 1);
int secondQuoteIndex = firstQuoteIndex == -1 ? -1 : nameExpression.indexOf("'", firstQuoteIndex + 1);
int secondCommaIndex = -1;
if (secondQuoteIndex > -1)
secondCommaIndex = nameExpression.indexOf(",", secondQuoteIndex + 1);
else if (commaIndex > -1)
secondCommaIndex = nameExpression.indexOf(",", commaIndex + 1);
String startVal = null;
String format = null;
String thirdParam = null;
try
{
if (secondCommaIndex > -1 && secondCommaIndex < endParen)
{
// 3 arguments
startVal = nameExpression.substring(startParen + 1, commaIndex).trim();
if (firstQuoteIndex > -1 && secondQuoteIndex > firstQuoteIndex)
format = nameExpression.substring(firstQuoteIndex, secondQuoteIndex + 1).trim();
thirdParam = nameExpression.substring(secondCommaIndex + 1, endParen).trim();
}
else if (commaIndex > startParen && commaIndex < endParen)
{
// two arguments
startVal = nameExpression.substring(startParen + 1, commaIndex).trim();
format = nameExpression.substring(commaIndex + 1, endParen).trim();
}
else
{
startVal = nameExpression.substring(startParen + 1, endParen).trim();
}
}
catch (StringIndexOutOfBoundsException e)
{
errorMessages.add(String.format("Invalid 'withCounter' expression starting at position %d", index));
}
// find the value of the first argument, if any, and validate it is an integer
if (!StringUtils.isEmpty(startVal))
{
try
{
Integer.parseInt(startVal);
}
catch (NumberFormatException e)
{
errorMessages.add(String.format("Invalid starting value %s for 'withCounter' starting at position %d.", startVal, index));
}
}
if (!StringUtils.isEmpty(format))
{
if (format.charAt(0) != '\'' || format.charAt(format.length()-1) != '\'')
errorMessages.add(String.format("Format string starting at position %d for 'withCounter' substitution pattern should be enclosed in single quotes.", commaIndex + 1));
}
if (!StringUtils.isEmpty(thirdParam))
{
if (!(WITH_COUNTER_NO_GAP_PARAM.equalsIgnoreCase(thirdParam)))
errorMessages.add(String.format("Param at position %d for 'withCounter' substitution pattern is invalid. Supported params include: " + WITH_COUNTER_NO_GAP_PARAM + ".", commaIndex + 1));
}
}
return new Pair<>(errorMessages, warningMessages);
}
static List<String> getMismatchedTagErrors(String nameExpression)
{
int start = 0;
int openIndex;
final String openTag = "${";
final String closeTag = "}";
List<String> errors = new ArrayList<>();
List<Integer> unmatchedOpen = new ArrayList<>();
List<Integer> unmatchedClosed = new ArrayList<>();
LinkedList<Integer> openIndexes = new LinkedList<>();
while (start < nameExpression.length() && (openIndex = findFirstOpenOrCloseTag(nameExpression, openTag, start)) >= 0)
{
openIndexes.clear();
openIndexes.push(openIndex);
int subInd = openIndex + 2;
while (subInd < nameExpression.length())
{
int nextOpen = findFirstOpenOrCloseTag(nameExpression, openTag, subInd);
int nextClose = findFirstOpenOrCloseTag(nameExpression, closeTag, subInd);
// no more opens or closes
if (nextOpen == -1 && nextClose == -1)
break;
// more opens but no more closes, continue in order to pick up all the open indexes
if (nextOpen > 0 && nextClose == -1)
{
openIndexes.add(nextOpen);
subInd = nextOpen + 2;
}
else if (nextOpen == -1 || nextClose < nextOpen)
{
if (openIndexes.isEmpty()) // Can this actually happen?
unmatchedClosed.add(nextClose);
else
{
openIndexes.pop();
subInd = nextClose + 1;
}
}
else if (nextClose > nextOpen)
{
openIndexes.push(nextOpen);
subInd = nextOpen + 2;
}
if (openIndexes.isEmpty())
break;
}
if (!openIndexes.isEmpty())
unmatchedOpen.addAll(openIndexes.stream().map(index -> index+1).toList());
start = subInd;
}
if (!unmatchedOpen.isEmpty())
{
if (unmatchedOpen.size() == 1)
errors.add("No closing brace found for the substitution pattern starting at position " + unmatchedOpen.get(0) + ".");
else
errors.add("No closing braces found for the substitution patterns starting at positions " + StringUtils.join(unmatchedOpen, ", ") + ".");
}
if (!unmatchedClosed.isEmpty())
{
errors.add("Unmatched closing brace found at position" + (unmatchedClosed.size() == 1 ? " " : "s ") + StringUtils.join(unmatchedClosed, ", ") + ".");
}
return errors;
}
public static @Nullable Stream<String> parentNames(Object value, String parentColName)
{
TSVWriter tsvWriter = new TSVWriter() // Used to quote values with newline/tabs/quotes
{
@Override
protected int write()
{
throw new UnsupportedOperationException();
}
};
Stream<String> values = parentNames(value, parentColName, tsvWriter, null);
if (values == null)
return values;
return values.map(String::trim)
.filter(s -> !s.isEmpty());
}
public static @Nullable Stream<String> parentNames(Object value, String parentColName, TSVWriter tsvWriter, @Nullable BatchValidationException errors)
{
if (value == null)
return Stream.empty();
Stream<String> values = null;
if (value instanceof String || value instanceof Number)
{
String valueStr = value instanceof String ? (String) value : value.toString();
if (StringUtils.isEmpty((valueStr).trim()))
return Stream.empty();
// GitHub Issue 827: Cannot aliquot samples where parent sample has a comma in the name AND the aliquot naming pattern references ancestor lineage
if (ALIQUOTED_FROM_INPUT.equalsIgnoreCase(parentColName) || ALIQUOTED_FROM_INPUT_LABEL.equalsIgnoreCase(parentColName))
{
// quotes might have already stripped at this point due to fix for issue 45563
boolean isQuoted = (valueStr.contains(",") || valueStr.contains("\n") || valueStr.contains("\r")) && (valueStr.startsWith("\"") && valueStr.endsWith("\""));
if (isQuoted)
valueStr = StringUtilsLabKey.unquoteString(valueStr).trim();
return Stream.of(valueStr);
}
// Issue 44841: The names of the parents may include commas, so we parse the set of parent names
// using TabLoader instead of just splitting on the comma.
boolean likelyAlreadyQuoted = valueStr.contains(",") || valueStr.contains("\n") || valueStr.contains("\r") || (valueStr.startsWith("\"") && valueStr.endsWith("\""));
String quotedStr = likelyAlreadyQuoted ? valueStr : tsvWriter.quoteValue(valueStr); // if value contains comma, no need to quote again
try
{
values = Arrays.stream(ExperimentService.getParentValues(quotedStr));
}
catch (IOException e)
{
if (errors != null)
errors.addRowError(new ValidationException("Unable to parse parent names from " + value, parentColName));
else
throw new IllegalStateException("Unable to parse parent names from " + valueStr, e);
}
}
else if (value instanceof Collection<?> coll)
{
values = coll.stream().map(String::valueOf);
}
else if (value instanceof JSONArray jsonArray)
{
values = jsonArray.toList().stream().map(String::valueOf);
}
else
{
if (errors != null)
errors.addRowError(new ValidationException("Expected comma separated list or a JSONArray of parent names: " + value, parentColName));
else
throw new IllegalStateException("For parent values in naming pattern, expected string or collection for '" + parentColName + "': " + value);
}
if (values != null)
{
List<String> valueList = values.toList();
Set<String> valueSet = new HashSet<>();
Set<String> duplicates = valueList.stream().filter(s -> !valueSet.add(s)).collect(Collectors.toSet());
if (!duplicates.isEmpty())
{
if (errors != null)
errors.addRowError(new ValidationException("Duplicate parent names found: " + StringUtils.join(duplicates, ", "), parentColName));
else
throw new IllegalStateException("Duplicate parent names found: " + StringUtils.join(duplicates, ", "));
}
return valueList.stream();
}
return values;
}
public static boolean isParentInput(Object token, @NotNull CaseInsensitiveHashMap<String> importAliases, @Nullable String currentDataTypeName, Container container, User user)
{
return isParentInputToken(token, importAliases, false) || isParentInputWithDataType(token.toString().split("/", 2), currentDataTypeName, false, container, user);
}
public static boolean isParentLookup(List<String> fieldParts, @NotNull CaseInsensitiveHashMap<String> importAliases, @Nullable String currentDataTypeName, Container container, User user)
{
if (!isParentInputToken(fieldParts.get(0), importAliases, false))
return false;
return fieldParts.size() != 2 || !isParentInputWithDataType(fieldParts.toArray(String[]::new), currentDataTypeName, false, container, user);
}
public static boolean isAncestorSearch(List<String> fieldParts, @NotNull CaseInsensitiveHashMap<String> importAliases, Container container, User user)
{
if (!fieldParts.get(0).startsWith("~"))
return false;
if (fieldParts.size() == 1)
return importAliases.containsKey(fieldParts.get(0).substring(1));
if (!isParentInputToken(fieldParts.get(0), null, true))
return false;
return fieldParts.size() <= 3 && isParentInputWithDataType(fieldParts.subList(0, 2).toArray(String[]::new), null,true, container, user);
}
public static boolean isProjectSampleCountToken(FieldKey token)
{
return SubstitutionFormat.sampleCount.name().equalsIgnoreCase(token.toString());
}
public static boolean isProjectRootSampleCountToken(FieldKey token)
{
return SubstitutionFormat.rootSampleCount.name().equalsIgnoreCase(token.toString());
}
public static boolean isParentInputToken(Object token, @Nullable Map<String, String> importAliases, boolean isAncestorSearch)
{
String sTok = token.toString();
if (isAncestorSearch)
{
if (!sTok.startsWith("~"))
return false;
sTok = sTok.substring(1); // remove leading ~
}
return INPUT_PARENT.equalsIgnoreCase(sTok)
|| ExpData.DATA_INPUT_PARENT.equalsIgnoreCase(sTok)
|| ExpMaterial.MATERIAL_INPUT_PARENT.equalsIgnoreCase(sTok)
|| (importAliases != null && importAliases.containsKey(sTok));
}
public static boolean isParentInputWithDataType(String[] parts, @Nullable String currentDataTypeName, boolean isAncestorSearch, Container container, User user)
{
if (parts.length != 2)
return false;
String inputToken = parts[0];
if (isAncestorSearch)
{
if (!inputToken.startsWith("~"))
return false;
inputToken = inputToken.substring(1); // remove leading ~
}
String dataType = QueryKey.decodePart(parts[1]); // If data type contains special characters
boolean isInput = INPUT_PARENT.equalsIgnoreCase(inputToken);
boolean isData = ExpData.DATA_INPUT_PARENT.equalsIgnoreCase(inputToken);
boolean isMaterial = ExpMaterial.MATERIAL_INPUT_PARENT.equalsIgnoreCase(inputToken);
if (!(isInput || isData || isMaterial))
return false;
if (dataType.equalsIgnoreCase(currentDataTypeName) && !isAncestorSearch)
return true;
if (isMaterial || isInput)
{
if (SampleTypeService.get().getSampleType(container, dataType, true) != null)
return true;
if (isMaterial)
return false;
}
return ExperimentService.get().getDataClass(container, dataType, true) != null;
}
private Object getParentLookupTokenPreview(String currentDataType, FieldKey fkTok, String inputPrefix, @Nullable String inputDataType, @Nullable NameExpressionAncestorPartOption ancestorPartOption, String lookupField, User user, Map<String, String> dataClassNames, Map<String, String> sampleTypeNames)
{
String inputPrefixLc = inputPrefix.toLowerCase();
boolean isMaterial = inputPrefixLc.startsWith("materialinputs") || inputPrefixLc.startsWith("inputs");
boolean isData = inputPrefixLc.startsWith("datainputs") || inputPrefixLc.startsWith("inputs");
boolean isAncestor = false;
if (ancestorPartOption != null)
{
List<Pair<ExpLineageOptions.LineageExpType, String>> ancestorPaths = ancestorPartOption.ancestorPaths();
Pair<ExpLineageOptions.LineageExpType, String> ancestorSearchType = ancestorPartOption.ancestorSearchType();
if (ancestorSearchType != null)
{
isAncestor = true;
isMaterial = ancestorSearchType.first == ExpLineageOptions.LineageExpType.Material;
isData = !isMaterial;
String dataTypeLsid = ancestorSearchType.second;
inputDataType = isMaterial ? sampleTypeNames.get(dataTypeLsid) : dataClassNames.get(dataTypeLsid);
}
else if (ancestorPaths != null && !ancestorPaths.isEmpty())
{
isAncestor = true;
Pair<ExpLineageOptions.LineageExpType, String> ancestorType = ancestorPaths.get(ancestorPaths.size() - 1);
isMaterial = ExpLineageOptions.LineageExpType.Material == ancestorType.first;
isData = ExpLineageOptions.LineageExpType.Data == ancestorType.first;
if (!StringUtils.isEmpty(ancestorType.second))
inputDataType = isMaterial ? sampleTypeNames.get(ancestorType.second) : dataClassNames.get(ancestorType.second);
else
inputDataType = null;
}
}
switch (lookupField.toLowerCase())
{
case "rowid":
case "createdby":
case "modifiedby":
return 1005;
case "name":
case "lsid":
case "description":
return (isAncestor ? "ancestor" : "parent") + lookupField;
case "created":
return PREVIEW_DATETIME_VALUE;
case "modified":
return PREVIEW_MODIFIED_DATE_VALUE;
}
List<ExpObject> dataTypes = new ArrayList<>();
if (isMaterial)
{
if (!StringUtils.isEmpty(inputDataType))
{
ExpSampleType sampleType = SampleTypeService.get().getSampleType(_container, inputDataType, true);
if (sampleType != null)
dataTypes.add(sampleType);
}
else
dataTypes.addAll(SampleTypeService.get().getSampleTypes(_container, true));
}
if (isData)
{
if (!StringUtils.isEmpty(inputDataType))
{
ExpDataClass dataClass = ExperimentService.get().getDataClass(_container, inputDataType, true);
if (dataClass != null)
dataTypes.add(dataClass);
}
else
dataTypes.addAll(ExperimentService.get().getDataClasses(_container, true));
}
boolean isCurrentDataType = inputDataType != null && inputDataType.equals(currentDataType);
String fieldKeyDisplay = QueryKey.decodePart(fkTok.toString());
if (inputDataType != null && dataTypes.isEmpty())
{
if (!isCurrentDataType)
{
_syntaxErrors.add("Invalid lineage lookup: " + fieldKeyDisplay + ".");
return null;
}
}
for (ExpObject dataType : dataTypes)
{
Domain domain = null;
if (dataType instanceof ExpSampleType sampleType)
{
domain = sampleType.getDomain();
}
else if (dataType instanceof ExpDataClass dataClass)
{
domain = dataClass.getDomain();
}
if (domain != null)
{
List<? extends DomainProperty> domainProperties = domain.getProperties();
for (DomainProperty domainProperty : domainProperties)
{
if (domainProperty.getName().equalsIgnoreCase(lookupField))
{
Object result = getNamePartPreviewValue(domainProperty.getPropertyType(), lookupField);
if (result instanceof String)
return (isAncestor ? "ancestor" : "parent") + result;
return result;
}
}
}