-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathOntologyManager.java
More file actions
3921 lines (3349 loc) · 169 KB
/
OntologyManager.java
File metadata and controls
3921 lines (3349 loc) · 169 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) 2005-2018 Fred Hutchinson Cancer Research Center
*
* 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.exp;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.cache.BlockingCache;
import org.labkey.api.cache.Cache;
import org.labkey.api.cache.CacheLoader;
import org.labkey.api.cache.CacheManager;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.collections.CaseInsensitiveMapWrapper;
import org.labkey.api.collections.IntHashMap;
import org.labkey.api.data.*;
import org.labkey.api.data.DbScope.Transaction;
import org.labkey.api.data.dialect.SqlDialect;
import org.labkey.api.dataiterator.DataIterator;
import org.labkey.api.dataiterator.DataIteratorContext;
import org.labkey.api.dataiterator.DataIteratorUtil;
import org.labkey.api.dataiterator.MapDataIterator;
import org.labkey.api.defaults.DefaultValueService;
import org.labkey.api.exceptions.OptimisticConflictException;
import org.labkey.api.exp.api.ExperimentService;
import org.labkey.api.exp.api.StorageProvisioner;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainProperty;
import org.labkey.api.exp.property.IPropertyValidator;
import org.labkey.api.exp.property.Lookup;
import org.labkey.api.exp.property.PropertyService;
import org.labkey.api.exp.property.SystemProperty;
import org.labkey.api.exp.property.ValidatorContext;
import org.labkey.api.gwt.client.ui.domain.CancellationException;
import org.labkey.api.query.BatchValidationException;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.PropertyValidationError;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.SchemaKey;
import org.labkey.api.query.ValidationError;
import org.labkey.api.query.ValidationException;
import org.labkey.api.security.User;
import org.labkey.api.security.permissions.ReadPermission;
import org.labkey.api.test.TestTimeout;
import org.labkey.api.test.TestWhen;
import org.labkey.api.util.CPUTimer;
import org.labkey.api.util.GUID;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.HtmlStringBuilder;
import org.labkey.api.util.Pair;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.ResultSetUtil;
import org.labkey.api.util.TestContext;
import org.labkey.api.view.HttpView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableCollection;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Collectors.joining;
import static org.labkey.api.util.IntegerUtils.asLong;
/**
* Lots of static methods for dealing with domains and property descriptors. Tends to operate primarily on the bean-style
* classes like {@link PropertyDescriptor} and {@link DomainDescriptor}. When possible, it's usually preferable to use
* {@link PropertyService}, {@link Domain}, and {@link DomainProperty} instead as they tend to provide higher-level
* abstractions.
*/
public class OntologyManager
{
private static final Logger _log = LogManager.getLogger(OntologyManager.class);
private static final Cache<Pair<Container, String>, Map<String, ObjectProperty>> PROPERTY_MAP_CACHE = DatabaseCache.get(getExpSchema().getScope(), 100000, "Property maps", new PropertyMapCacheLoader());
private static final BlockingCache<String, Long> OBJECT_ID_CACHE = DatabaseCache.get(getExpSchema().getScope(), 2000, "ObjectIds", new ObjectIdCacheLoader());
private static final Cache<Pair<String, GUID>, PropertyDescriptor> PROP_DESCRIPTOR_CACHE = DatabaseCache.get(getExpSchema().getScope(), 40000, "Property descriptors", new CacheLoader<>()
{
@Override
public PropertyDescriptor load(@NotNull Pair<String, GUID> key, @Nullable Object argument)
{
PropertyDescriptor ret = null;
String propertyURI = key.first;
Container c = ContainerManager.getForId(key.second);
if (null != c)
{
Container proj = c.getProject();
if (null == proj)
proj = c;
_log.debug("Loading a property descriptor for key " + key + " using project " + proj);
String sql = " SELECT * FROM " + getTinfoPropertyDescriptor() + " WHERE PropertyURI = ? AND Project IN (?,?)";
List<PropertyDescriptor> pdArray = new SqlSelector(getExpSchema(), sql, propertyURI, proj, _sharedContainer.getId()).getArrayList(PropertyDescriptor.class);
if (!pdArray.isEmpty())
{
PropertyDescriptor pd = pdArray.get(0);
// if someone has explicitly inserted a descriptor with the same URI as an existing one,
// and one of the two is in the shared project, use the project-level descriptor.
if (pdArray.size() > 1)
{
_log.debug("Multiple PropertyDescriptors found for " + propertyURI);
if (pd.getProject().equals(_sharedContainer))
pd = pdArray.get(1);
}
_log.debug("Loaded property descriptor " + pd);
ret = pd;
}
}
return ret;
}
});
/** DomainURI, ContainerEntityId -> DomainDescriptor */
private static final Cache<Pair<String, GUID>, DomainDescriptor> DOMAIN_DESCRIPTORS_BY_URI_CACHE = DatabaseCache.get(getExpSchema().getScope(), 2000, CacheManager.UNLIMITED, "Domain descriptors by URI", (key, argument) -> {
String domainURI = key.first;
Container c = ContainerManager.getForId(key.second);
if (c == null)
{
return null;
}
return fetchDomainDescriptorFromDB(domainURI, c);
});
@Nullable
private static DomainDescriptor fetchDomainDescriptorFromDB(String domainURI, Container c)
{
return fetchDomainDescriptorFromDB(domainURI, c, false);
}
/** Goes against the DB, bypassing the cache */
@Nullable
public static DomainDescriptor fetchDomainDescriptorFromDB(String uriOrName, Container c, boolean isName)
{
Container proj = c.getProject();
if (null == proj)
proj = c;
String sql = " SELECT * FROM " + getTinfoDomainDescriptor() + " WHERE " + (isName ? "Name" : "DomainURI") + " = ? AND Project IN (?,?) ";
List<DomainDescriptor> ddArray = new SqlSelector(getExpSchema(), sql, uriOrName,
proj,
ContainerManager.getSharedContainer().getId()).getArrayList(DomainDescriptor.class);
DomainDescriptor dd = null;
if (!ddArray.isEmpty())
{
dd = ddArray.get(0);
// if someone has explicitly inserted a descriptor with the same URI as an existing one ,
// and one of the two is in the shared project, use the project-level descriptor.
if (ddArray.size() > 1)
{
_log.debug("Multiple DomainDescriptors found for " + uriOrName);
if (dd.getProject().equals(ContainerManager.getSharedContainer()))
dd = ddArray.get(0);
}
}
return dd;
}
private static final BlockingCache<Integer, DomainDescriptor> DOMAIN_DESC_BY_ID_CACHE = DatabaseCache.get(getExpSchema().getScope(),2000, CacheManager.UNLIMITED,"Domain descriptors by ID", new DomainDescriptorLoader());
private static final BlockingCache<Pair<String, GUID>, List<Pair<String, Boolean>>> DOMAIN_PROPERTIES_CACHE = DatabaseCache.get(getExpSchema().getScope(), 5000, CacheManager.UNLIMITED, "Domain properties", new CacheLoader<>()
{
@Override
public List<Pair<String, Boolean>> load(@NotNull Pair<String, GUID> key, @Nullable Object argument)
{
String typeURI = key.first;
Container c = ContainerManager.getForId(key.second);
if (null == c)
return Collections.emptyList();
SQLFragment sql = new SQLFragment("SELECT PropertyURI, Required " +
"FROM " + getTinfoPropertyDescriptor() + " PD\n" +
" INNER JOIN " + getTinfoPropertyDomain() + " PDM ON (PD.PropertyId = PDM.PropertyId)\n" +
" INNER JOIN " + getTinfoDomainDescriptor() + " DD ON (DD.DomainId = PDM.DomainId)\n" +
"WHERE DD.DomainURI = ? AND DD.Project IN (?, ?) ORDER BY PDM.SortOrder, PD.PropertyId");
sql.addAll(
typeURI,
// protect against null project, just double-up shared project
c.isRoot() ? c.getId() : (c.getProject() == null ? _sharedContainer.getProject().getId() : c.getProject().getId()),
_sharedContainer.getProject().getId()
);
return new SqlSelector(getExpSchema(), sql).mapStream()
.map(map -> Pair.of((String)map.get("PropertyURI"), (Boolean)map.get("Required")))
.toList();
}
});
private static final Cache<Container, Map<String, DomainDescriptor>> DOMAIN_DESCRIPTORS_BY_CONTAINER_CACHE = DatabaseCache.get(getExpSchema().getScope(), 2000, "Domain descriptors by container", (c, argument) -> {
String sql = "SELECT * FROM " + getTinfoDomainDescriptor() + " WHERE Container = ?";
Map<String, DomainDescriptor> dds = new LinkedHashMap<>();
for (DomainDescriptor dd : new SqlSelector(getExpSchema(), sql, c).getArrayList(DomainDescriptor.class))
{
dds.putIfAbsent(dd.getDomainURI(), dd);
}
return unmodifiableMap(dds);
});
private static final Container _sharedContainer = ContainerManager.getSharedContainer();
public static final String MV_INDICATOR_SUFFIX = "mvindicator";
static public String PropertyOrderURI = "urn:exp.labkey.org/#PropertyOrder";
/**
* A comma-separated list of propertyID that indicates the sort order of the properties attached to an object.
*/
static public SystemProperty PropertyOrder = new SystemProperty(PropertyOrderURI, PropertyType.STRING);
static
{
BeanObjectFactory.Registry.register(ObjectProperty.class, new ObjectProperty.ObjectPropertyObjectFactory());
}
private OntologyManager()
{
}
/**
* @return map from PropertyURI to value
*/
public static @NotNull Map<String, Object> getProperties(Container container, String parentLSID)
{
Map<String, Object> m = new LinkedHashMap<>();
Map<String, ObjectProperty> propVals = getPropertyObjects(container, parentLSID);
if (null != propVals)
{
for (Map.Entry<String, ObjectProperty> entry : propVals.entrySet())
{
m.put(entry.getKey(), entry.getValue().value());
}
}
return m;
}
public static final int MAX_PROPS_IN_BATCH = 1000; // Keep this reasonably small so progress indicator is updated regularly
public static final int UPDATE_STATS_BATCH_COUNT = 1000;
public static void insertTabDelimited(Container c,
User user,
@Nullable Long ownerObjectId,
ImportHelper helper,
Domain domain,
DataIterator rows,
boolean ensureObjects,
@Nullable RowCallback rowCallback)
throws SQLException, BatchValidationException
{
List<PropertyDescriptor> properties = new ArrayList<>(domain.getProperties().size());
for (DomainProperty prop : domain.getProperties())
{
properties.add(prop.getPropertyDescriptor());
}
insertTabDelimited(c, user, ownerObjectId, helper, properties, rows, ensureObjects, rowCallback);
}
public interface RowCallback
{
void rowProcessed(Map<String, Object> row, String lsid) throws BatchValidationException;
default void complete() throws BatchValidationException
{}
default RowCallback chain(RowCallback other)
{
if (other == NO_OP_ROW_CALLBACK)
{
return this;
}
if (this == NO_OP_ROW_CALLBACK)
{
return other;
}
RowCallback original = this;
return new RowCallback()
{
@Override
public void rowProcessed(Map<String, Object> row, String lsid) throws BatchValidationException
{
original.rowProcessed(row, lsid);
other.rowProcessed(row, lsid);
}
@Override
public void complete() throws BatchValidationException
{
original.complete();
other.complete();
}
};
}
}
public static final RowCallback NO_OP_ROW_CALLBACK = (row, lsid) -> {};
public static void insertTabDelimited(Container c,
User user,
@Nullable Long ownerObjectId,
ImportHelper helper,
List<PropertyDescriptor> descriptors,
DataIterator rawRows,
boolean ensureObjects,
@Nullable RowCallback rowCallback)
throws SQLException, BatchValidationException
{
MapDataIterator rows = DataIteratorUtil.wrapMap(rawRows, false);
rowCallback = rowCallback == null ? NO_OP_ROW_CALLBACK : rowCallback;
CPUTimer total = new CPUTimer("insertTabDelimited");
CPUTimer before = new CPUTimer("beforeImport");
CPUTimer ensure = new CPUTimer("ensureObject");
CPUTimer insert = new CPUTimer("insertProperties");
assert total.start();
assert getExpSchema().getScope().isTransactionActive();
// Make sure we have enough rows to handle the overflow of the current row so we don't have to resize the list
List<PropertyRow> propsToInsert = new ArrayList<>(MAX_PROPS_IN_BATCH + descriptors.size());
ValidatorContext validatorCache = new ValidatorContext(c, user);
try
{
OntologyObject objInsert = new OntologyObject();
objInsert.setContainer(c);
if (ownerObjectId != null && ownerObjectId > 0)
objInsert.setOwnerObjectId(ownerObjectId);
List<ValidationError> errors = new ArrayList<>();
Map<Integer, List<? extends IPropertyValidator>> validatorMap = new IntHashMap<>();
// cache all the property validators for this upload
for (PropertyDescriptor pd : descriptors)
{
List<? extends IPropertyValidator> validators = PropertyService.get().getPropertyValidators(pd);
if (!validators.isEmpty())
validatorMap.put(pd.getPropertyId(), validators);
}
int rowCount = 0;
int batchCount = 0;
while (rows.next())
{
Map<String, Object> map = rows.getMap();
// TODO: hack -- should exit and return cancellation status instead of throwing
if (Thread.currentThread().isInterrupted())
throw new CancellationException();
assert before.start();
Map<String, Object> modifiableMap = new HashMap<>(map);
String lsid = helper.beforeImportObject(modifiableMap);
map = Collections.unmodifiableMap(modifiableMap);
if (lsid == null)
{
throw new IllegalStateException("No LSID available");
}
assert before.stop();
assert ensure.start();
long objectId;
if (ensureObjects)
objectId = ensureObject(c, lsid, ownerObjectId);
else
{
objInsert.setObjectURI(lsid);
Table.insert(null, getTinfoObject(), objInsert);
objectId = objInsert.getObjectId();
}
for (PropertyDescriptor pd : descriptors)
{
Object value = map.get(pd.getPropertyURI());
if (null == value)
{
if (pd.isRequired())
throw new BatchValidationException(new ValidationException("Missing value for required property " + pd.getName()));
else
{
continue;
}
}
else
{
if (validatorMap.containsKey(pd.getPropertyId()))
validateProperty(validatorMap.get(pd.getPropertyId()), pd, new ObjectProperty(lsid, c, pd, value), errors, validatorCache);
}
try
{
PropertyRow row = new PropertyRow(objectId, pd, value, pd.getPropertyType());
propsToInsert.add(row);
}
catch (ConversionException e)
{
throw new BatchValidationException(new ValidationException(ConvertHelper.getStandardConversionErrorMessage(value, pd.getName(), pd.getPropertyType().getJavaType())));
}
}
assert ensure.stop();
rowCount++;
if (propsToInsert.size() > MAX_PROPS_IN_BATCH)
{
assert insert.start();
insertPropertiesBulk(c, propsToInsert, false);
helper.afterBatchInsert(rowCount);
assert insert.stop();
propsToInsert = new ArrayList<>(MAX_PROPS_IN_BATCH + descriptors.size());
if (++batchCount % UPDATE_STATS_BATCH_COUNT == 0)
{
getExpSchema().getSqlDialect().updateStatistics(getTinfoObject());
getExpSchema().getSqlDialect().updateStatistics(getTinfoObjectProperty());
helper.updateStatistics(rowCount);
}
}
rowCallback.rowProcessed(map, lsid);
}
if (!errors.isEmpty())
throw new BatchValidationException(new ValidationException(errors));
assert insert.start();
insertPropertiesBulk(c, propsToInsert, false);
helper.afterBatchInsert(rowCount);
rowCallback.complete();
assert insert.stop();
}
catch (SQLException x)
{
SQLException next = x.getNextException();
if (x instanceof java.sql.BatchUpdateException && null != next)
x = next;
_log.debug("Exception uploading: ", x);
throw x;
}
assert total.stop();
_log.debug("\t" + total);
_log.debug("\t" + before);
_log.debug("\t" + ensure);
_log.debug("\t" + insert);
}
/**
* As an incremental step of QueryUpdateService cleanup, this is a version of insertTabDelimited that works on a
* tableInfo that implements UpdateableTableInfo. Does not support ownerObjectid.
* <p>
* This code is made complicated by the fact that while we are trying to move toward a TableInfo/ColumnInfo view
* of the world, validators are attached to PropertyDescriptors. Also, missing value handling is attached
* to PropertyDescriptors.
* <p>
* The original version of this method expects a data to be a map PropertyURI->value. This version will also
* accept Name->value.
* <p>
* Name->Value is preferred, we are using TableInfo after all.
*/
@Deprecated // switch to StandardDataIteratorBuilder and TableInsertDataIteratorBuilder
public static void insertTabDelimited(TableInfo tableInsert,
Container c,
User user,
UpdateableTableImportHelper helper,
DataIterator rows,
boolean autoFillDefaultColumns,
Logger logger,
RowCallback rowCallback)
throws SQLException, BatchValidationException
{
saveTabDelimited(tableInsert, c, user, helper, rows, logger, true, autoFillDefaultColumns, rowCallback);
}
@Deprecated // switch to StandardDataIteratorBuilder and TableInsertDataIteratorBuilder
public static void updateTabDelimited(TableInfo tableInsert,
Container c,
User user,
UpdateableTableImportHelper helper,
DataIterator rows,
boolean autoFillDefaultColumns,
Logger logger)
throws SQLException, BatchValidationException
{
saveTabDelimited(tableInsert, c, user, helper, rows, logger, false, autoFillDefaultColumns, NO_OP_ROW_CALLBACK);
}
private static void saveTabDelimited(TableInfo table,
Container c,
User user,
UpdateableTableImportHelper helper,
DataIterator in,
Logger logger,
boolean insert,
boolean autoFillDefaultColumns,
@Nullable RowCallback rowCallback)
throws SQLException, BatchValidationException
{
if (!(table instanceof UpdateableTableInfo))
throw new IllegalArgumentException();
if (rowCallback == null)
{
rowCallback = NO_OP_ROW_CALLBACK;
}
DbScope scope = table.getSchema().getScope();
assert scope.isTransactionActive();
Domain d = table.getDomain();
List<? extends DomainProperty> properties = null == d ? Collections.emptyList() : d.getProperties();
ValidatorContext validatorCache = new ValidatorContext(c, user);
Connection conn = null;
ParameterMapStatement parameterMap = null;
Map<String, Object> currentRow = null;
MapDataIterator rows = DataIteratorUtil.wrapMap(in, false);
try
{
conn = scope.getConnection();
if (insert)
{
parameterMap = StatementUtils.insertStatement(conn, table, c, user, true, autoFillDefaultColumns);
}
else
{
parameterMap = StatementUtils.updateStatement(conn, table, c, user, false, autoFillDefaultColumns);
}
List<ValidationError> errors = new ArrayList<>();
Map<String, List<? extends IPropertyValidator>> validatorMap = new HashMap<>();
Map<String, DomainProperty> propertiesMap = new HashMap<>();
// cache all the property validators for this upload
for (DomainProperty dp : properties)
{
propertiesMap.put(dp.getPropertyURI(), dp);
List<? extends IPropertyValidator> validators = dp.getValidators();
if (!validators.isEmpty())
validatorMap.put(dp.getPropertyURI(), validators);
}
List<ColumnInfo> columns = table.getColumns();
PropertyType[] propertyTypes = new PropertyType[columns.size()];
for (int i = 0; i < columns.size(); i++)
{
String propertyURI = columns.get(i).getPropertyURI();
DomainProperty dp = null == propertyURI ? null : propertiesMap.get(propertyURI);
PropertyDescriptor pd = null == dp ? null : dp.getPropertyDescriptor();
if (null != pd)
propertyTypes[i] = pd.getPropertyType();
}
int rowCount = 0;
while (rows.next())
{
currentRow = new CaseInsensitiveHashMap<>(rows.getMap());
// TODO: hack -- should exit and return cancellation status instead of throwing
if (Thread.currentThread().isInterrupted())
throw new CancellationException();
parameterMap.clearParameters();
String lsid = helper.beforeImportObject(currentRow);
currentRow.put("lsid", lsid);
//
// NOTE we validate based on columninfo/propertydescriptor
// However, we bind by name, and there may be parameters that do not correspond to columninfo
//
for (int i = 0; i < columns.size(); i++)
{
ColumnInfo col = columns.get(i);
if (col.isMvIndicatorColumn() || col.isRawValueColumn()) //TODO col.isNotUpdatableForSomeReasonSoContinue()
continue;
String propertyURI = col.getPropertyURI();
DomainProperty dp = null == propertyURI ? null : propertiesMap.get(propertyURI);
PropertyDescriptor pd = null == dp ? null : dp.getPropertyDescriptor();
Object value = currentRow.get(col.getName());
if (null == value)
value = currentRow.get(propertyURI);
if (null == value)
{
// TODO col.isNullable() doesn't seem to work here
if (null != pd && pd.isRequired())
throw new BatchValidationException(new ValidationException("Missing value for required property " + col.getName()));
}
else
{
if (null != pd)
{
try
{
// Use an ObjectProperty to unwrap MvFieldWrapper, do type conversion, etc
ObjectProperty objectProperty = new ObjectProperty(lsid, c, pd, value);
if (!validateProperty(validatorMap.get(propertyURI), pd, objectProperty, errors, validatorCache))
{
throw new BatchValidationException(new ValidationException(errors));
}
}
catch (ConversionException e)
{
throw new BatchValidationException(new ValidationException(ConvertHelper.getStandardConversionErrorMessage(value, pd.getName(), pd.getJavaClass())));
}
}
}
// issue 19391: data from R uses "Inf" to represent infinity
if (JdbcType.DOUBLE.equals(col.getJdbcType()))
{
value = "Inf".equals(value) ? "Infinity" : value;
value = "-Inf".equals(value) ? "-Infinity" : value;
}
try
{
String key = col.getName();
if (!parameterMap.containsKey(key))
key = propertyURI;
if (null == propertyTypes[i])
{
// some built-in columns won't have parameters (createdby, etc)
if (parameterMap.containsKey(key))
{
assert !(value instanceof MvFieldWrapper);
// Handle type coercion for these built-in columns as well, though we don't need to
// worry about missing values
value = PropertyType.getFromClass(col.getJavaObjectClass()).convert(value);
parameterMap.put(key, value);
}
}
else
{
Pair<Object, String> p = new Pair<>(value, null);
convertValuePair(pd, propertyTypes[i], p);
parameterMap.put(key, p.first);
if (null != p.second)
{
FieldKey mvName = col.getMvColumnName();
if (mvName != null)
{
String storageName = table.getColumn(mvName).getMetaDataIdentifier().getId();
parameterMap.put(storageName, p.second);
}
}
}
}
catch (ConversionException e)
{
throw new ValidationException(ConvertHelper.getStandardConversionErrorMessage(value, pd.getName(), propertyTypes[i].getJavaType()));
}
}
helper.bindAdditionalParameters(currentRow, parameterMap);
parameterMap.execute();
if (insert)
{
long rowId = parameterMap.getRowId();
currentRow.put("rowId", rowId);
}
lsid = helper.afterImportObject(currentRow);
if (lsid == null)
{
throw new IllegalStateException("No LSID available");
}
rowCallback.rowProcessed(currentRow, lsid);
rowCount++;
}
if (!errors.isEmpty())
throw new BatchValidationException(new ValidationException(errors));
rowCallback.complete();
helper.afterBatchInsert(rowCount);
if (logger != null)
logger.debug("inserted row " + rowCount + ".");
}
catch (ValidationException e)
{
throw new BatchValidationException(e);
}
catch (SQLException x)
{
SQLException next = x.getNextException();
if (x instanceof java.sql.BatchUpdateException && null != next)
x = next;
_log.debug("Exception uploading: ", x);
if (null != currentRow)
_log.debug(currentRow.toString());
throw x;
}
finally
{
if (null != parameterMap)
parameterMap.close();
if (null != conn)
scope.releaseConnection(conn);
}
}
// TODO: Consolidate with ColumnValidator
public static boolean validateProperty(List<? extends IPropertyValidator> validators, PropertyDescriptor prop, ObjectProperty objectProperty,
List<ValidationError> errors, ValidatorContext validatorCache)
{
boolean ret = true;
Object value = objectProperty.getObjectValue();
if (prop.isRequired() && value == null && objectProperty.getMvIndicator() == null)
{
errors.add(new PropertyValidationError("Field '" + prop.getName() + "' is required", prop.getName()));
ret = false;
}
// Check if the string is too long. Use either the PropertyDescriptor's scale or VARCHAR(4000) for ontology managed values
int stringLengthLimit = prop.getScale() > 0 ? prop.getScale() : getTinfoObjectProperty().getColumn("StringValue").getScale();
int stringLength = value == null ? 0 : value.toString().length();
if (value != null && prop.isStringType() && stringLength > stringLengthLimit)
{
String s = stringLength <= 100 ? value.toString() : StringUtilsLabKey.leftSurrogatePairFriendly(value.toString(), 100);
errors.add(new PropertyValidationError("Field '" + prop.getName() + "' is limited to " + stringLengthLimit + " characters, but the value is " + stringLength + " characters. (The value starts with '" + s + "...')", prop.getName()));
ret = false;
}
// TODO: check date is within postgres date range
// Don't validate null values, #15683
if (null != value && validators != null)
{
for (IPropertyValidator validator : validators)
if (!validator.validate(prop, value, errors, validatorCache)) ret = false;
}
return ret;
}
public interface ImportHelper
{
/**
* may modify map
*
* @return LSID for new or existing Object. Null indicates LSID is still unknown.
*/
String beforeImportObject(Map<String, Object> map) throws SQLException;
void afterBatchInsert(int currentRow) throws SQLException;
void updateStatistics(int currentRow) throws SQLException;
}
public interface UpdateableTableImportHelper extends ImportHelper
{
/**
* may be used to process attachments, for auditing, etc
* @return the LSID of the inserted row
*/
String afterImportObject(Map<String, Object> map) throws SQLException;
/**
* may set parameters directly for columns that are not exposed by tableinfo
* e.g. "_key"
* <p>
* TODO maybe this can be handled declaratively? see UpdateableTableInfo
*/
void bindAdditionalParameters(Map<String, Object> map, ParameterMapStatement target) throws ValidationException;
}
@NotNull
private static Pair<Container, String> getPropertyMapCacheKey(@Nullable Container container, @NotNull String objectLSID)
{
return Pair.of(container, objectLSID);
}
/**
* Get ordered map of property values for an object. The order of the properties in the
* Map corresponds to the <code>PropertyOrder</code> property, if present.
*
* @return map from PropertyURI to ObjectProperty
*/
public static Map<String, ObjectProperty> getPropertyObjects(@Nullable Container container, @NotNull String objectLSID)
{
Pair<Container, String> cacheKey = getPropertyMapCacheKey(container, objectLSID);
return PROPERTY_MAP_CACHE.get(cacheKey);
}
public static class PropertyMapCacheLoader implements CacheLoader<Pair<Container, String>, Map<String, ObjectProperty>>
{
@Override
public Map<String, ObjectProperty> load(@NotNull Pair<Container, String> key, @Nullable Object argument)
{
Container container = key.first;
String objectLSID = key.second;
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("ObjectURI"), objectLSID);
if (container != null)
{
filter.addCondition(FieldKey.fromParts("Container"), container);
}
if (_log.isDebugEnabled())
{
try (ResultSet rs = new TableSelector(getTinfoObjectPropertiesView(), filter, null).getResultSet())
{
ResultSetUtil.logData(rs);
}
catch (SQLException x)
{
throw new RuntimeException(x);
}
}
List<ObjectProperty> props = new TableSelector(getTinfoObjectPropertiesView(), filter, null).getArrayList(ObjectProperty.class);
// check for a "PropertyOrder" value
ObjectProperty propertyOrder = props.stream().filter(op -> PropertyOrderURI.equals(op.getPropertyURI())).findFirst().orElse(null);
if (propertyOrder != null)
{
String order = propertyOrder.getStringValue();
if (order != null)
{
// CONSIDER: Store as a JSONArray of propertyURI instead of propertyId
String[] parts = order.split(",");
try
{
List<Integer> propertyIds = Arrays.stream(parts).map(s -> ConvertHelper.convert(s, Integer.class)).toList();
// Don't include the "PropertyOrder" property
props = new ArrayList<>(props);
props.remove(propertyOrder);
// Order by the index found in the PropertyOrder list, otherwise just stick it at the end
Comparator<ObjectProperty> comparator = (op1, op2) -> {
int i1 = propertyIds.indexOf(op1.getPropertyId());
if (i1 == -1)
i1 = propertyIds.size();
int i2 = propertyIds.indexOf(op2.getPropertyId());
if (i2 == -1)
i2 = propertyIds.size();
return i1 - i2;
};
props.sort(comparator);
}
catch (ConversionException e)
{
_log.warn("Failed to parse PropertyOrder integer list: " + order);
}
}
}
Map<String, ObjectProperty> m = new LinkedHashMap<>();
for (ObjectProperty value : props)
{
m.put(value.getPropertyURI(), value);
}
return unmodifiableMap(m);
}
}
public static void updateObjectPropertyOrder(User user, Container container, String objectLSID, List<PropertyDescriptor> properties)
throws ValidationException
{
String ids = null;
if (properties != null && !properties.isEmpty())
ids = properties.stream().map(pd -> Integer.toString(pd.getPropertyId())).collect(joining(","));
updateObjectProperty(user, container, PropertyOrder.getPropertyDescriptor(), objectLSID, ids, null, false);
}
/**
* Moves the properties of an object from one container to another (used when the object is moving)
* @param targetContainer the container to move the properties to
* @param user the user doing the move
* @param objectLSID the LSID of the object to which the properties are attached
* @return number of properties moved
*/
public static int updateContainer(Container targetContainer, User user, @NotNull String objectLSID)
{
return updateContainer(targetContainer, user, List.of(objectLSID));
}
public static int updateContainer(Container targetContainer, User user, @NotNull List<String> objectLSIDs)
{
return Table.updateContainer(getTinfoObject(), "objectURI", objectLSIDs, targetContainer, user, false);
}
/**
* Get ordered list of the PropertyURI in {@link #PropertyOrder}, if present.
*/
public static List<String> getObjectPropertyOrder(Container c, String objectLSID)
{
Map<String, ObjectProperty> props = getPropertyObjects(c, objectLSID);
return new ArrayList<>(props.keySet());
}
public static long ensureObject(Container container, String objectURI)
{
return ensureObject(container, objectURI, (Long) null);
}
public static long ensureObject(Container container, String objectURI, String ownerURI)
{
Long ownerId = null;
if (null != ownerURI)
ownerId = ensureObject(container, ownerURI, (Long) null);
return ensureObject(container, objectURI, ownerId);
}
public static long ensureObject(Container container, String objectURI, Long ownerId)
{
//TODO: (marki) Transact?
Long objId = OBJECT_ID_CACHE.get(objectURI, container);
if (null == objId)
{
OntologyObject obj = new OntologyObject();
obj.setContainer(container);
obj.setObjectURI(objectURI);
if (ownerId != null && ownerId > 0)
obj.setOwnerObjectId(ownerId);
obj = Table.insert(null, getTinfoObject(), obj);
objId = obj.getObjectId();
OBJECT_ID_CACHE.remove(objectURI);
}
return objId;
}
private static class ObjectIdCacheLoader implements CacheLoader<String, Long>
{
@Override
public Long load(@NotNull String objectURI, @Nullable Object argument)
{
Container container = (Container)argument;
OntologyObject obj = getOntologyObject(container, objectURI);
return obj == null ? null : obj.getObjectId();
}
}
public static @Nullable OntologyObject getOntologyObject(Container container, String uri)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("ObjectURI"), uri);
if (container != null)
{
filter.addCondition(FieldKey.fromParts("Container"), container.getId());
}
return new TableSelector(getTinfoObject(), filter, null).getObject(OntologyObject.class);