-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathEntityCsv.java
More file actions
2051 lines (1837 loc) · 76.6 KB
/
EntityCsv.java
File metadata and controls
2051 lines (1837 loc) · 76.6 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 2021 Collate
* 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.openmetadata.csv;
import static org.openmetadata.common.utils.CommonUtil.listOf;
import static org.openmetadata.common.utils.CommonUtil.listOrEmpty;
import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;
import static org.openmetadata.csv.CsvUtil.ENTITY_TYPE_SEPARATOR;
import static org.openmetadata.csv.CsvUtil.FIELD_SEPARATOR;
import static org.openmetadata.csv.CsvUtil.fieldToColumns;
import static org.openmetadata.csv.CsvUtil.fieldToEntities;
import static org.openmetadata.csv.CsvUtil.fieldToExtensionStrings;
import static org.openmetadata.csv.CsvUtil.fieldToInternalArray;
import static org.openmetadata.csv.CsvUtil.recordToString;
import static org.openmetadata.service.Entity.DATABASE;
import static org.openmetadata.service.Entity.DATABASE_SCHEMA;
import static org.openmetadata.service.Entity.STORED_PROCEDURE;
import static org.openmetadata.service.Entity.TABLE;
import static org.openmetadata.service.events.ChangeEventHandler.copyChangeEvent;
import static org.openmetadata.service.util.EntityUtil.findColumnWithChildren;
import static org.openmetadata.service.util.EntityUtil.getLocalColumnName;
import com.fasterxml.jackson.databind.JsonNode;
import com.networknt.schema.Error;
import com.networknt.schema.Schema;
import jakarta.json.JsonPatch;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVFormat.Builder;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.tuple.Pair;
import org.jdbi.v3.sqlobject.transaction.Transaction;
import org.openmetadata.common.utils.CommonUtil;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.schema.api.data.StoredProcedureCode;
import org.openmetadata.schema.entity.data.Database;
import org.openmetadata.schema.entity.data.DatabaseSchema;
import org.openmetadata.schema.entity.data.StoredProcedure;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.entity.teams.User;
import org.openmetadata.schema.type.ApiStatus;
import org.openmetadata.schema.type.AssetCertification;
import org.openmetadata.schema.type.ChangeEvent;
import org.openmetadata.schema.type.Column;
import org.openmetadata.schema.type.ColumnDataType;
import org.openmetadata.schema.type.EntityReference;
import org.openmetadata.schema.type.EventType;
import org.openmetadata.schema.type.Include;
import org.openmetadata.schema.type.StoredProcedureLanguage;
import org.openmetadata.schema.type.TagLabel;
import org.openmetadata.schema.type.TagLabel.TagSource;
import org.openmetadata.schema.type.csv.CsvDocumentation;
import org.openmetadata.schema.type.csv.CsvErrorType;
import org.openmetadata.schema.type.csv.CsvFile;
import org.openmetadata.schema.type.csv.CsvHeader;
import org.openmetadata.schema.type.csv.CsvImportResult;
import org.openmetadata.schema.type.customProperties.TableConfig;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.Entity;
import org.openmetadata.service.TypeRegistry;
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.formatter.util.FormatterUtil;
import org.openmetadata.service.jdbi3.DatabaseSchemaRepository;
import org.openmetadata.service.jdbi3.EntityRepository;
import org.openmetadata.service.jdbi3.TableRepository;
import org.openmetadata.service.util.AsyncService;
import org.openmetadata.service.util.EntityUtil;
import org.openmetadata.service.util.FullyQualifiedName;
import org.openmetadata.service.util.RestUtil.PutResponse;
import org.openmetadata.service.util.ValidatorUtil;
/**
* EntityCsv provides export and import capabilities for an entity. Each entity must implement the
* abstract methods to provide entity specific processing functionality to export an entity to a CSV
* record, and import an entity from a CSV record.
*/
@Slf4j
public abstract class EntityCsv<T extends EntityInterface> {
public static final String FIELD_ERROR_MSG = "#%s: Field %d error - %s";
public static final String IMPORT_STATUS_HEADER = "status";
public static final String IMPORT_STATUS_DETAILS = "details";
public static final String IMPORT_SUCCESS = "success";
public static final String IMPORT_FAILED = "failure";
public static final String IMPORT_SKIPPED = "skipped";
public static final String ENTITY_CREATED = "Entity created";
public static final String ENTITY_UPDATED = "Entity updated";
// Additional fields for export/import with multiple entity types
public static final String FIELD_ENTITY_TYPE = "entityType";
public static final String FIELD_FULLY_QUALIFIED_NAME = "fullyQualifiedName";
public static final int DEFAULT_BATCH_SIZE = 100;
private final String entityType;
private final List<CsvHeader> csvHeaders;
private final List<String> expectedHeaders;
protected final CsvImportResult importResult = new CsvImportResult();
protected boolean processRecord; // When set to false record processing is discontinued
protected final Map<String, T> dryRunCreatedEntities = new HashMap<>();
protected final String importedBy;
protected int recordIndex = 0;
// Queue for batching entity creates/updates - processed after each batch of CSV records
protected final List<PendingEntityOperation> pendingEntityOperations = new ArrayList<>();
/** Holder for pending entity create/update operations */
protected static class PendingEntityOperation {
EntityInterface entity;
EntityInterface originalEntity;
CSVRecord csvRecord;
String entityType;
boolean isCreate;
PendingEntityOperation(
EntityInterface entity,
EntityInterface originalEntity,
CSVRecord csvRecord,
String entityType,
boolean isCreate) {
this.entity = entity;
this.originalEntity = originalEntity;
this.csvRecord = csvRecord;
this.entityType = entityType;
this.isCreate = isCreate;
}
}
// Queue for batching OpenSearch updates - processed after each batch of CSV records
protected final List<EntityInterface> pendingSearchIndexUpdates = new ArrayList<>();
/** Cache for tables being modified during column imports - enables batching column updates */
protected final Map<String, TableUpdateContext> pendingTableUpdates = new HashMap<>();
/** Context for batched table column updates */
protected static class TableUpdateContext {
Table originalTable;
Table updatedTable;
List<CSVRecord> csvRecords = new ArrayList<>();
TableUpdateContext(Table original, Table updated) {
this.originalTable = original;
this.updatedTable = updated;
}
}
protected EntityCsv(String entityType, List<CsvHeader> csvHeaders, String importedBy) {
this.entityType = entityType;
this.csvHeaders = csvHeaders;
this.expectedHeaders = CsvUtil.getHeaders(csvHeaders);
this.importedBy = importedBy;
}
/** Import entities from a CSV file */
public final CsvImportResult importCsv(String csv, boolean dryRun) throws IOException {
return importCsv(csv, dryRun, null);
}
/** Import entities from a CSV file with progress callback */
public final CsvImportResult importCsv(
String csv, boolean dryRun, CsvImportProgressCallback callback) throws IOException {
importResult.withDryRun(dryRun);
StringWriter writer = new StringWriter();
CSVPrinter resultsPrinter = getResultsCsv(csvHeaders, writer);
if (resultsPrinter == null) {
return importResult;
}
// Parse CSV
List<CSVRecord> records = parse(csv);
if (records == null) {
return importResult; // Error during parsing
}
// First record is CSV header - Validate headers
if (!validateHeaders(records.get(recordIndex++))) {
return importResult;
}
importResult.withNumberOfRowsPassed(importResult.getNumberOfRowsPassed() + 1);
int totalRows = records.size() - 1; // Exclude header row
int batchNumber = 0;
int rowsInBatch = 0;
// Validate and load each record with batch progress tracking
while (recordIndex < records.size()) {
processRecord(resultsPrinter, records);
rowsInBatch++;
// Send progress notification after each batch
if (rowsInBatch >= DEFAULT_BATCH_SIZE || recordIndex >= records.size()) {
// Flush pending entity operations using batch DB operations
flushPendingEntityOperations();
// Flush any pending batched updates (e.g., column updates for tables)
flushPendingTableUpdates(resultsPrinter);
// Flush pending search index updates using bulk API
flushPendingSearchIndexUpdates();
batchNumber++;
int rowsProcessed = recordIndex - 1; // Exclude header row from count
if (callback != null) {
String message =
String.format(
"Processed %d of %d rows (batch %d)", rowsProcessed, totalRows, batchNumber);
callback.onProgress(rowsProcessed, totalRows, batchNumber, message);
}
rowsInBatch = 0;
}
}
// Flush any remaining pending updates
flushPendingEntityOperations();
flushPendingTableUpdates(resultsPrinter);
flushPendingSearchIndexUpdates();
// Finally, create the entities parsed from the record
setFinalStatus();
importResult.withImportResultsCsv(writer.toString());
return importResult;
}
/** Implement this method to a CSV record and turn it into an entity */
protected abstract void createEntity(CSVPrinter resultsPrinter, List<CSVRecord> csvRecords)
throws IOException;
public final String exportCsv(T entity) throws IOException {
CsvFile csvFile = new CsvFile().withHeaders(csvHeaders);
addRecord(csvFile, entity);
return CsvUtil.formatCsv(csvFile);
}
public final String exportCsv(List<T> entities) throws IOException {
return exportCsv(entities, null);
}
public final String exportCsv(List<T> entities, CsvExportProgressCallback callback)
throws IOException {
CsvFile csvFile = new CsvFile().withHeaders(csvHeaders);
int total = entities.size();
int exported = 0;
int batchNumber = 0;
for (T entity : entities) {
addRecord(csvFile, entity);
exported++;
// Send progress notification after each batch
if (exported % DEFAULT_BATCH_SIZE == 0 || exported == total) {
batchNumber++;
if (callback != null) {
String message =
String.format("Exported %d of %d entities (batch %d)", exported, total, batchNumber);
callback.onProgress(exported, total, message);
}
}
}
return CsvUtil.formatCsv(csvFile);
}
public static CsvDocumentation getCsvDocumentation(String entityType, boolean recursive) {
String effectiveEntityType = (recursive) ? "entity" : entityType;
LOG.info("Initializing CSV documentation for entity {}", effectiveEntityType);
String path =
String.format(
".*json/data/%s/%sCsvDocumentation.json$", effectiveEntityType, effectiveEntityType);
try {
List<String> jsonDataFiles = EntityUtil.getJsonDataResources(path);
String json =
CommonUtil.getResourceAsStream(
EntityRepository.class.getClassLoader(), jsonDataFiles.get(0));
return JsonUtils.readValue(json, CsvDocumentation.class);
} catch (IOException e) {
LOG.error(
"FATAL - Failed to load CSV documentation for entity {} from the path {}",
effectiveEntityType,
path);
}
return null;
}
/** Implement this method to export an entity into a list of fields to create a CSV record */
protected abstract void addRecord(CsvFile csvFile, T entity);
/** Implement this method to export an entity into a list of fields to create a CSV record */
public void addRecord(CsvFile csvFile, List<String> recordList) {
List<List<String>> list = csvFile.getRecords();
list.add(recordList);
csvFile.withRecords(list);
}
/** Owner field is in entityType:entityName format */
public List<EntityReference> getOwners(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
Function<Integer, String> invalidMessageCreator)
throws IOException {
if (!processRecord) {
return null;
}
String ownersRecord = csvRecord.get(fieldNumber);
if (nullOrEmpty(ownersRecord)) {
return null;
}
List<String> owners = listOrEmpty(CsvUtil.fieldToStrings(ownersRecord));
List<EntityReference> refs = new ArrayList<>();
for (String owner : owners) {
List<String> ownerTypes = listOrEmpty(fieldToEntities(owner));
if (ownerTypes.size() != 2) {
importFailure(printer, invalidMessageCreator.apply(fieldNumber), csvRecord);
return Collections.emptyList();
}
EntityReference ownerRef =
getEntityReference(printer, csvRecord, fieldNumber, ownerTypes.get(0), ownerTypes.get(1));
if (ownerRef != null) {
refs.add(ownerRef);
}
}
return refs.isEmpty() ? null : refs;
}
public List<EntityReference> getOwners(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber)
throws IOException {
return getOwners(printer, csvRecord, fieldNumber, EntityCsv::invalidOwner);
}
public List<EntityReference> getReviewers(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber) throws IOException {
return getOwners(printer, csvRecord, fieldNumber, EntityCsv::invalidReviewer);
}
public List<EntityReference> getDomains(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber)
throws IOException {
if (!processRecord) {
return null;
}
String domainsRecord = csvRecord.get(fieldNumber);
if (nullOrEmpty(domainsRecord)) {
return null;
}
List<String> domains = listOrEmpty(CsvUtil.fieldToStrings(domainsRecord));
List<EntityReference> refs = new ArrayList<>();
for (String domain : domains) {
EntityReference domainRef =
getEntityReference(printer, csvRecord, fieldNumber, Entity.DOMAIN, domain);
if (domainRef != null) {
refs.add(domainRef);
}
}
return refs;
}
/** Owner field is in entityName format */
public EntityReference getOwnerAsUser(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber)
throws IOException {
if (!processRecord) {
return null;
}
String owner = csvRecord.get(fieldNumber);
if (nullOrEmpty(owner)) {
return null;
}
return getEntityReference(printer, csvRecord, fieldNumber, Entity.USER, owner);
}
protected final Boolean getBoolean(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber)
throws IOException {
String field = csvRecord.get(fieldNumber);
if (nullOrEmpty(field)) {
return null;
}
if (field.equals(Boolean.TRUE.toString())) {
return true;
}
if (field.equals(Boolean.FALSE.toString())) {
return false;
}
importFailure(printer, invalidBoolean(fieldNumber, field), csvRecord);
processRecord = false;
return false;
}
protected final EntityReference getEntityReference(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber, String entityType)
throws IOException {
if (!processRecord) {
return null;
}
String fqn = csvRecord.get(fieldNumber);
return getEntityReference(printer, csvRecord, fieldNumber, entityType, fqn);
}
protected EntityInterface getEntityByName(String entityType, String fqn) {
EntityInterface entity =
entityType.equals(this.entityType) ? dryRunCreatedEntities.get(fqn) : null;
if (entity == null) {
EntityRepository<?> entityRepository = Entity.getEntityRepository(entityType);
entity = entityRepository.findByNameOrNull(fqn, Include.NON_DELETED);
}
return entity;
}
protected final EntityReference getEntityReference(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber, String entityType, String fqn)
throws IOException {
if (nullOrEmpty(fqn)) {
return null;
}
EntityInterface entity = getEntityByName(entityType, fqn);
if (entity == null) {
importFailure(printer, entityNotFound(fieldNumber, entityType, fqn), csvRecord);
processRecord = false;
return null;
}
return entity.getEntityReference();
}
protected final List<EntityReference> getEntityReferences(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber, String entityType)
throws IOException {
if (!processRecord) {
return null;
}
String fqns = csvRecord.get(fieldNumber);
if (nullOrEmpty(fqns)) {
return null;
}
List<String> fqnList = listOrEmpty(CsvUtil.fieldToStrings(fqns));
List<EntityReference> refs = new ArrayList<>();
for (String fqn : fqnList) {
EntityReference ref = getEntityReference(printer, csvRecord, fieldNumber, entityType, fqn);
if (!processRecord) {
return null;
}
if (ref != null) {
refs.add(ref);
}
}
refs.sort(Comparator.comparing(EntityReference::getName));
return refs.isEmpty() ? null : refs;
}
protected final List<EntityReference> getEntityReferencesForGlossaryTerms(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber) throws IOException {
if (!processRecord) {
return null;
}
String fqns = csvRecord.get(fieldNumber);
if (nullOrEmpty(fqns)) {
return null;
}
List<String> fqnList = listOrEmpty(CsvUtil.fieldToStrings(fqns));
List<EntityReference> refs = new ArrayList<>();
for (String fqn : fqnList) {
EntityInterface entity = getEntityByName(Entity.GLOSSARY_TERM, fqn);
if (entity == null) {
importFailure(printer, entityNotFound(fieldNumber, Entity.GLOSSARY_TERM, fqn), csvRecord);
processRecord = false;
return null;
}
// Validate that the glossary term has APPROVED status
org.openmetadata.schema.entity.data.GlossaryTerm term =
(org.openmetadata.schema.entity.data.GlossaryTerm) entity;
if (term.getEntityStatus() != org.openmetadata.schema.type.EntityStatus.APPROVED) {
LOG.error(
"[VALIDATION] VALIDATION FAILED! Term '{}' status is {} not APPROVED",
fqn,
term.getEntityStatus());
importFailure(
printer,
invalidField(
fieldNumber,
String.format(
"Glossary term '%s' must have APPROVED status to be linked. Current status: %s",
fqn, term.getEntityStatus())),
csvRecord);
processRecord = false;
return null;
}
refs.add(entity.getEntityReference());
}
refs.sort(Comparator.comparing(EntityReference::getName));
return refs.isEmpty() ? null : refs;
}
protected final List<TagLabel> getTagLabels(
CSVPrinter printer,
CSVRecord csvRecord,
List<Pair<Integer, TagSource>> fieldNumbersWithSource)
throws IOException {
if (!processRecord) {
return null;
}
List<TagLabel> tagLabels = new ArrayList<>();
for (Pair<Integer, TagSource> pair : fieldNumbersWithSource) {
int fieldNumbers = pair.getLeft();
TagSource source = pair.getRight();
List<EntityReference> refs =
source == TagSource.CLASSIFICATION
? getEntityReferences(printer, csvRecord, fieldNumbers, Entity.TAG)
: getEntityReferencesForGlossaryTerms(printer, csvRecord, fieldNumbers);
if (processRecord && !nullOrEmpty(refs)) {
for (EntityReference ref : refs) {
tagLabels.add(new TagLabel().withSource(source).withTagFQN(ref.getFullyQualifiedName()));
}
}
}
return tagLabels;
}
protected AssetCertification getCertificationLabels(String certificationTag) {
if (nullOrEmpty(certificationTag)) {
return null;
}
TagLabel certificationLabel =
new TagLabel().withTagFQN(certificationTag).withSource(TagLabel.TagSource.CLASSIFICATION);
return new AssetCertification()
.withTagLabel(certificationLabel)
.withAppliedDate(System.currentTimeMillis())
.withExpiryDate(System.currentTimeMillis());
}
public Map<String, Object> getExtension(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber)
throws IOException {
String extensionString = csvRecord.get(fieldNumber);
if (nullOrEmpty(extensionString)) {
return null;
}
Map<String, Object> extensionMap = new HashMap<>();
for (String extensions : fieldToExtensionStrings(extensionString)) {
// Split on the first occurrence of ENTITY_TYPE_SEPARATOR to get key-value pair
int separatorIndex = extensions.indexOf(ENTITY_TYPE_SEPARATOR);
if (separatorIndex == -1) {
importFailure(printer, invalidExtension(fieldNumber, extensions, "null"), csvRecord);
continue;
}
String key = extensions.substring(0, separatorIndex);
String value = extensions.substring(separatorIndex + 1);
if (key.isEmpty() || value.isEmpty()) {
importFailure(printer, invalidExtension(fieldNumber, key, value), csvRecord);
} else {
extensionMap.put(key, value);
}
}
validateExtension(printer, fieldNumber, csvRecord, extensionMap);
return extensionMap;
}
private void validateExtension(
CSVPrinter printer, int fieldNumber, CSVRecord csvRecord, Map<String, Object> extensionMap)
throws IOException {
for (Map.Entry<String, Object> entry : extensionMap.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
Schema jsonSchema = TypeRegistry.instance().getSchema(entityType, fieldName);
if (jsonSchema == null) {
importFailure(printer, invalidCustomPropertyKey(fieldNumber, fieldName), csvRecord);
return;
}
String customPropertyType = TypeRegistry.getCustomPropertyType(entityType, fieldName);
String propertyConfig = TypeRegistry.getCustomPropertyConfig(entityType, fieldName);
switch (customPropertyType) {
case "entityReference", "entityReferenceList" -> {
boolean isList = "entityReferenceList".equals(customPropertyType);
fieldValue =
parseEntityReferences(printer, csvRecord, fieldNumber, fieldValue.toString(), isList);
}
case "date-cp", "dateTime-cp", "time-cp" -> fieldValue =
parseFormattedDateTimeField(
printer,
csvRecord,
fieldNumber,
fieldName,
fieldValue.toString(),
customPropertyType,
propertyConfig);
case "enum" -> fieldValue =
parseEnumType(
printer,
csvRecord,
fieldNumber,
fieldName,
customPropertyType,
fieldValue,
propertyConfig);
case "timeInterval" -> fieldValue =
parseTimeInterval(printer, csvRecord, fieldNumber, fieldName, fieldValue);
case "number", "integer", "timestamp" -> fieldValue =
parseLongField(
printer, csvRecord, fieldNumber, fieldName, customPropertyType, fieldValue);
case "table-cp" -> fieldValue =
parseTableType(printer, csvRecord, fieldNumber, fieldName, fieldValue, propertyConfig);
default -> {}
}
// Validate the field against the JSON schema
validateAndUpdateExtension(
printer,
csvRecord,
fieldNumber,
fieldName,
fieldValue,
customPropertyType,
extensionMap,
jsonSchema);
}
}
private Object parseEntityReferences(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber, String fieldValue, boolean isList)
throws IOException {
List<EntityReference> entityReferences = new ArrayList<>();
List<String> entityRefStrings =
isList
? listOrEmpty(fieldToInternalArray(fieldValue))
: Collections.singletonList(fieldValue);
for (String entityRefStr : entityRefStrings) {
List<String> entityRefTypeAndValue = listOrEmpty(fieldToEntities(entityRefStr));
if (entityRefTypeAndValue.size() == 2) {
EntityReference entityRef =
getEntityReference(
printer,
csvRecord,
fieldNumber,
entityRefTypeAndValue.get(0),
entityRefTypeAndValue.get(1));
Optional.ofNullable(entityRef).ifPresent(entityReferences::add);
}
}
return isList ? entityReferences : entityReferences.isEmpty() ? null : entityReferences.get(0);
}
protected String parseFormattedDateTimeField(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
String fieldName,
String fieldValue,
String fieldType,
String propertyConfig)
throws IOException {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(propertyConfig, Locale.ENGLISH);
return switch (fieldType) {
case "date-cp" -> {
TemporalAccessor date = formatter.parse(fieldValue);
yield formatter.format(date);
}
case "dateTime-cp" -> {
LocalDateTime dateTime = LocalDateTime.parse(fieldValue, formatter);
yield dateTime.format(formatter);
}
case "time-cp" -> {
LocalTime time = LocalTime.parse(fieldValue, formatter);
yield time.format(formatter);
}
default -> throw new IllegalStateException("Unexpected value: " + fieldType);
};
} catch (DateTimeParseException e) {
importFailure(
printer,
invalidCustomPropertyFieldFormat(fieldNumber, fieldName, fieldType, propertyConfig),
csvRecord);
return null;
}
}
private Map<String, Long> parseTimeInterval(
CSVPrinter printer, CSVRecord csvRecord, int fieldNumber, String fieldName, Object fieldValue)
throws IOException {
List<String> timestampValues = fieldToEntities(fieldValue.toString());
Map<String, Long> timestampMap = new HashMap<>();
if (timestampValues.size() == 2) {
try {
timestampMap.put("start", Long.parseLong(timestampValues.get(0)));
timestampMap.put("end", Long.parseLong(timestampValues.get(1)));
} catch (NumberFormatException e) {
importFailure(
printer,
invalidCustomPropertyValue(
fieldNumber, fieldName, "timeInterval", fieldValue.toString()),
csvRecord);
return null;
}
} else {
importFailure(
printer,
invalidCustomPropertyFieldFormat(fieldNumber, fieldName, "timeInterval", "start:end"),
csvRecord);
return null;
}
return timestampMap;
}
private Object parseLongField(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
String fieldName,
String customPropertyType,
Object fieldValue)
throws IOException {
try {
return Long.parseLong(fieldValue.toString());
} catch (NumberFormatException e) {
importFailure(
printer,
invalidCustomPropertyValue(
fieldNumber, fieldName, customPropertyType, fieldValue.toString()),
csvRecord);
return null;
}
}
private Object parseTableType(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
String fieldName,
Object fieldValue,
String propertyConfig)
throws IOException {
List<String> tableValues = listOrEmpty(fieldToInternalArray(fieldValue.toString()));
List<Map<String, String>> rows = new ArrayList<>();
TableConfig tableConfig =
JsonUtils.treeToValue(JsonUtils.readTree(propertyConfig), TableConfig.class);
for (String row : tableValues) {
List<String> columns = listOrEmpty(fieldToColumns(row));
Map<String, String> rowMap = new LinkedHashMap<>();
Iterator<String> columnIterator = tableConfig.getColumns().iterator();
Iterator<String> valueIterator = columns.iterator();
if (columns.size() > tableConfig.getColumns().size()) {
importFailure(
printer,
invalidCustomPropertyValue(
fieldNumber,
fieldName,
"table",
"Column count should be less than or equal to " + tableConfig.getColumns().size()),
csvRecord);
return null;
}
while (columnIterator.hasNext() && valueIterator.hasNext()) {
rowMap.put(columnIterator.next(), valueIterator.next());
}
rows.add(rowMap);
}
Map<String, Object> tableJson = new LinkedHashMap<>();
tableJson.put("rows", rows);
tableJson.put("columns", tableConfig.getColumns());
return tableJson;
}
private Object parseEnumType(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
String fieldName,
String customPropertyType,
Object fieldValue,
String propertyConfig)
throws IOException {
List<String> enumKeys = listOrEmpty(fieldToInternalArray(fieldValue.toString()));
try {
EntityRepository.validateEnumKeys(fieldName, JsonUtils.valueToTree(enumKeys), propertyConfig);
} catch (Exception e) {
importFailure(
printer,
invalidCustomPropertyValue(fieldNumber, fieldName, customPropertyType, e.getMessage()),
csvRecord);
}
return enumKeys.isEmpty() ? null : enumKeys;
}
private void validateAndUpdateExtension(
CSVPrinter printer,
CSVRecord csvRecord,
int fieldNumber,
String fieldName,
Object fieldValue,
String customPropertyType,
Map<String, Object> extensionMap,
Schema jsonSchema)
throws IOException {
if (fieldValue != null) {
JsonNode jsonNodeValue = JsonUtils.convertValue(fieldValue, JsonNode.class);
List<Error> validationMessages = jsonSchema.validate(jsonNodeValue);
if (!validationMessages.isEmpty()) {
importFailure(
printer,
invalidCustomPropertyValue(
fieldNumber, fieldName, customPropertyType, validationMessages.toString()),
csvRecord);
} else {
extensionMap.put(fieldName, fieldValue);
}
}
}
public static String[] getResultHeaders(List<CsvHeader> csvHeaders) {
List<String> importResultsCsvHeader = listOf(IMPORT_STATUS_HEADER, IMPORT_STATUS_DETAILS);
importResultsCsvHeader.addAll(CsvUtil.getHeaders(csvHeaders));
return importResultsCsvHeader.toArray(new String[0]);
}
// Create a CSVPrinter to capture the import results
private CSVPrinter getResultsCsv(List<CsvHeader> csvHeaders, StringWriter writer) {
CSVFormat format =
Builder.create(CSVFormat.DEFAULT).setHeader(getResultHeaders(csvHeaders)).build();
try {
return new CSVPrinter(writer, format);
} catch (IOException e) {
documentFailure(failed(e.getMessage(), CsvErrorType.UNKNOWN));
}
return null;
}
public List<CSVRecord> parse(String csv) {
Reader in = new StringReader(csv);
try {
return CSVFormat.DEFAULT.parse(in).stream().toList();
} catch (IOException e) {
documentFailure(failed(e.getMessage(), CsvErrorType.PARSER_FAILURE));
}
return null;
}
public List<CSVRecord> parse(String csv, boolean recursive) {
List<CSVRecord> records = new ArrayList<>();
Reader in = new StringReader(csv);
try {
CSVParser parser =
CSVFormat.DEFAULT
.withFirstRecordAsHeader()
.withQuote('"')
.withIgnoreEmptyLines()
.parse(in);
List<List<String>> fixedRows = new ArrayList<>();
List<String> headers = new ArrayList<>(parser.getHeaderMap().keySet()); // Extract headers
// Add headers explicitly at the top if they are missing
if (fixedRows.isEmpty()) {
fixedRows.add(headers);
}
// Process each record
for (CSVRecord record : parser) {
List<String> fixedRow = new ArrayList<>();
for (String value : record) {
// Preserve the raw value without additional processing
fixedRow.add(value);
}
// Pad or trim the row to match the number of columns in headers
fixedRow = padOrTrimColumns(fixedRow);
fixedRows.add(fixedRow);
}
// Convert fixedRows back to CSVRecords
records = convertToCSVRecords(fixedRows, headers);
} catch (IOException e) {
documentFailure(failed(e.getMessage(), CsvErrorType.PARSER_FAILURE));
}
return records;
}
private List<CSVRecord> convertToCSVRecords(List<List<String>> fixedRows, List<String> headers)
throws IOException {
List<CSVRecord> finalRecords = new ArrayList<>();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter =
new CSVPrinter(stringWriter, CSVFormat.DEFAULT.withHeader(headers.toArray(new String[0])));
// Write updated records
for (List<String> row : fixedRows) {
csvPrinter.printRecord(row);
}
csvPrinter.flush();
// Parse CSV again with headers
Reader in = new StringReader(stringWriter.toString());
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
finalRecords.addAll(parser.getRecords());
return finalRecords;
}
private List<String> padOrTrimColumns(List<String> row) {
List<String> fixedRow = new ArrayList<>(row);
// If row has fewer columns than expected, add empty columns
while (fixedRow.size() < csvHeaders.size()) {
fixedRow.add("");
}
// If row has more columns than expected, trim extra ones
while (fixedRow.size() > csvHeaders.size()) {
fixedRow.remove(fixedRow.size() - 1);
}
return fixedRow;
}
private boolean validateHeaders(CSVRecord csvRecord) {
importResult.withNumberOfRowsProcessed((int) csvRecord.getRecordNumber());
if (expectedHeaders.equals(csvRecord.toList())) {
return true;
}
importResult.withNumberOfRowsFailed(1);
documentFailure(invalidHeader(recordToString(expectedHeaders), recordToString(csvRecord)));
return false;
}
private void processRecord(CSVPrinter resultsPrinter, List<CSVRecord> csvRecords)
throws IOException {
processRecord = true;
createEntity(resultsPrinter, csvRecords); // Convert record into entity for
}
public final CSVRecord getNextRecord(
CSVPrinter resultsPrinter, List<CsvHeader> csvHeaders, List<CSVRecord> csvRecords)
throws IOException {
CSVRecord csvRecord = csvRecords.get(recordIndex++);
// Every row must have total fields corresponding to the number of headers
if (csvHeaders.size() != csvRecord.size()) {
importFailure(
resultsPrinter, invalidFieldCount(expectedHeaders.size(), csvRecord.size()), csvRecord);
return null;
}
// Check if required values are present
List<String> errors = new ArrayList<>();
for (int i = 0; i < csvHeaders.size(); i++) {
String field = csvRecord.get(i);
boolean fieldRequired = Boolean.TRUE.equals(csvHeaders.get(i).getRequired());
if (fieldRequired && nullOrEmpty(field)) {
errors.add(fieldRequired(i));
}
}