/
ObjectClassHandler.java
1152 lines (900 loc) · 40.9 KB
/
ObjectClassHandler.java
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
package com.evolveum.polygon.connector.csv;
import com.evolveum.polygon.connector.csv.util.Column;
import com.evolveum.polygon.connector.csv.util.StringAccessor;
import com.evolveum.polygon.connector.csv.util.Util;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.identityconnectors.common.StringUtil;
import org.identityconnectors.common.logging.Log;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.framework.common.exceptions.*;
import org.identityconnectors.framework.common.objects.*;
import org.identityconnectors.framework.common.objects.filter.FilterTranslator;
import org.identityconnectors.framework.spi.SyncTokenResultsHandler;
import org.identityconnectors.framework.spi.operations.*;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
import static com.evolveum.polygon.connector.csv.util.Util.createSyncFileName;
import static com.evolveum.polygon.connector.csv.util.Util.handleGenericException;
/**
* todo check new FileSystem().newWatchService() to create exclusive tmp file https://docs.oracle.com/javase/tutorial/essential/io/notification.html
* <p>
* Created by lazyman on 27/01/2017.
*/
public class ObjectClassHandler implements CreateOp, DeleteOp, TestOp, SearchOp<String>,
UpdateAttributeValuesOp, AuthenticateOp, ResolveUsernameOp, SyncOp {
private enum Operation {
DELETE, UPDATE, ADD_ATTR_VALUE, REMOVE_ATTR_VALUE;
}
private static final Log LOG = Log.getLog(ObjectClassHandler.class);
private ObjectClassHandlerConfiguration configuration;
private Map<String, Column> header;
public ObjectClassHandler(ObjectClassHandlerConfiguration configuration) {
this.configuration = configuration;
header = initHeader(configuration.getFilePath());
}
private Map<String, Column> initHeader(File csvFile) {
CSVFormat csv = Util.createCsvFormat(configuration);
try (Reader reader = Util.createReader(csvFile, configuration)) {
CSVParser parser = csv.parse(reader);
Iterator<CSVRecord> iterator = parser.iterator();
CSVRecord record = null;
while (iterator.hasNext()) {
record = iterator.next();
if (!isRecordEmpty(record)) {
break;
}
}
if (record == null) {
throw new ConfigurationException("Couldn't initialize headers, nothing in csv file for object class "
+ configuration.getObjectClass());
}
return createHeader(record);
} catch (IOException ex) {
throw new ConnectorIOException("Couldn't initialize connector for object class "
+ configuration.getObjectClass(), ex);
}
}
private String getAvailableAttributeName(Map<String, Column> header, String realName) {
String availableName = realName;
for (int i = 1; i <= header.size(); i++) {
if (!header.containsKey(availableName)) {
break;
}
availableName = realName + i;
}
return availableName;
}
private Map<String, Column> createHeader(CSVRecord record) {
Map<String, Column> header = new HashMap<>();
if (configuration.isHeaderExists()) {
for (int i = 0; i < record.size(); i++) {
String name = record.get(i);
if (StringUtil.isEmpty(name)) {
name = Util.DEFAULT_COLUMN_NAME + 0;
}
String availableName = getAvailableAttributeName(header, name);
header.put(availableName, new Column(name, i));
}
} else {
// header doesn't exist, we just create col0...colN
for (int i = 0; i < record.size(); i++) {
header.put(Util.DEFAULT_COLUMN_NAME + i, new Column(null, i));
}
}
LOG.ok("Created header {0}", header);
testHeader(header);
return header;
}
private void testHeader(Map<String, Column> headers) {
boolean uniqueFound = false;
boolean passwordFound = false;
for (String header : headers.keySet()) {
if (header.equals(configuration.getUniqueAttribute())) {
uniqueFound = true;
continue;
}
if (header.equals(configuration.getPasswordAttribute())) {
passwordFound = true;
continue;
}
if (uniqueFound && passwordFound) {
break;
}
}
if (!uniqueFound) {
throw new ConfigurationException("Header in csv file doesn't contain "
+ "unique attribute name as defined in configuration.");
}
if (StringUtil.isNotEmpty(configuration.getPasswordAttribute()) && !passwordFound) {
throw new ConfigurationException("Header in csv file doesn't contain "
+ "password attribute name as defined in configuration.");
}
}
public ObjectClass getObjectClass() {
return configuration.getObjectClass();
}
public void schema(SchemaBuilder schema) {
try {
ObjectClassInfoBuilder objClassBuilder = new ObjectClassInfoBuilder();
objClassBuilder.setType(getObjectClass().getObjectClassValue());
objClassBuilder.setAuxiliary(configuration.isAuxiliary());
objClassBuilder.setContainer(configuration.isContainer());
objClassBuilder.addAllAttributeInfo(createAttributeInfo(header));
schema.defineObjectClass(objClassBuilder.build());
} catch (Exception ex) {
handleGenericException(ex, "Couldn't initialize connector");
}
}
private Set<AttributeInfo.Flags> createFlags(AttributeInfo.Flags... flags) {
Set<AttributeInfo.Flags> set = new HashSet<>();
set.addAll(Arrays.asList(flags));
return set;
}
private List<AttributeInfo> createAttributeInfo(Map<String, Column> columns) {
List<String> multivalueAttributes = new ArrayList<>();
if (StringUtil.isNotEmpty(configuration.getMultivalueAttributes())) {
String[] array = configuration.getMultivalueAttributes().split(configuration.getMultivalueDelimiter());
multivalueAttributes = Arrays.asList(array);
}
List<AttributeInfo> infos = new ArrayList<>();
for (String name : columns.keySet()) {
if (name == null || name.isEmpty()) {
continue;
}
if (name.equals(configuration.getUniqueAttribute())) {
// unique column
AttributeInfoBuilder builder = new AttributeInfoBuilder(Uid.NAME);
builder.setType(String.class);
builder.setNativeName(name);
infos.add(builder.build());
if (!isUniqueAndNameAttributeEqual()) {
builder = new AttributeInfoBuilder(name);
builder.setType(String.class);
builder.setNativeName(name);
builder.setRequired(true);
infos.add(builder.build());
continue;
}
}
if (name.equals(configuration.getNameAttribute())) {
AttributeInfoBuilder builder = new AttributeInfoBuilder(Name.NAME);
builder.setType(String.class);
builder.setNativeName(name);
if (isUniqueAndNameAttributeEqual()) {
builder.setRequired(true);
}
infos.add(builder.build());
continue;
}
if (name.equals(configuration.getPasswordAttribute())) {
AttributeInfoBuilder builder = new AttributeInfoBuilder(OperationalAttributes.PASSWORD_NAME);
builder.setType(GuardedString.class);
builder.setNativeName(name);
infos.add(builder.build());
continue;
}
AttributeInfoBuilder builder = new AttributeInfoBuilder(name);
if (name.equals(configuration.getPasswordAttribute())) {
builder.setType(GuardedString.class);
} else {
builder.setType(String.class);
}
builder.setNativeName(name);
if (multivalueAttributes.contains(name)) {
builder.setMultiValued(true);
}
infos.add(builder.build());
}
return infos;
}
@Override
public Uid authenticate(ObjectClass oc, String username, GuardedString password, OperationOptions oo) {
return resolveUsername(username, password, oo, true);
}
@Override
public Uid create(ObjectClass oc, Set<Attribute> set, OperationOptions oo) {
if (configuration.isReadOnly()) {
throw new ConnectorException("Can't add attribute values. Readonly set to true.");
}
Set<Attribute> attributes = normalize(set);
String uidValue = findUidValue(attributes);
Uid uid = new Uid(uidValue);
FileLock lock = Util.obtainTmpFileLock(configuration);
Reader reader = null;
Writer writer = null;
try {
reader = Util.createReader(configuration);
writer = new BufferedWriter(Channels.newWriter(lock.channel(), configuration.getEncoding()));
CSVFormat csv = Util.createCsvFormat(configuration);
CSVParser parser = csv.parse(reader);
csv = Util.createCsvFormat(configuration);
CSVPrinter printer = csv.print(writer);
Iterator<CSVRecord> iterator = parser.iterator();
// we don't want to skip header in any case, but if it's there just
// write it to tmp file as "standard" record. We can't handle first row
// as header in case there are more columns with the same name.
if (configuration.isHeaderExists() && iterator.hasNext()) {
CSVRecord record = iterator.next();
printer.printRecord(record);
}
// handling real records
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
ConnectorObject obj = createConnectorObject(record);
if (uid.equals(obj.getUid())) {
throw new AlreadyExistsException("Account already exists '" + uid.getUidValue() + "'.");
}
printer.printRecord(record);
}
printer.printRecord(createNewRecord(attributes));
writer.close();
reader.close();
moveTmpToOrig();
} catch (Exception ex) {
handleGenericException(ex, "Error during account '" + uid + "' create");
} finally {
Util.cleanupResources(writer, reader, lock, configuration);
}
return uid;
}
private void moveTmpToOrig() throws IOException {
// moving existing file
String path = configuration.getFilePath().getPath();
File orig = new File(path);
File tmp = Util.createTmpPath(configuration);
Files.move(tmp.toPath(), orig.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
private boolean isPassword(String column) {
return StringUtil.isNotEmpty(configuration.getPasswordAttribute())
&& configuration.getPasswordAttribute().equals(column);
}
private boolean isUid(String column) {
return configuration.getUniqueAttribute().equals(column);
}
private List<Object> createNewRecord(Set<Attribute> attributes) {
final Object[] record = new Object[header.size()];
Attribute nameAttr = AttributeUtil.getNameFromAttributes(attributes);
Object name = nameAttr != null ? AttributeUtil.getSingleValue(nameAttr) : null;
Attribute uniqueAttr = AttributeUtil.find(configuration.getUniqueAttribute(), attributes);
Object uid = uniqueAttr != null ? AttributeUtil.getSingleValue(uniqueAttr) : null;
for (String column : header.keySet()) {
Object value;
if (isPassword(column)) {
Attribute attr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
if (attr == null) {
continue;
}
value = Util.createRawValue(attr, configuration);
} else if (isName(column)) {
value = name;
} else if (isUid(column)) {
value = uid;
} else {
Attribute attr = AttributeUtil.find(column, attributes);
if (attr == null) {
continue;
}
value = Util.createRawValue(attr, configuration);
}
record[header.get(column).getIndex()] = value;
}
return Arrays.asList(record);
}
private String findUidValue(Set<Attribute> attributes) {
Attribute uniqueAttr = AttributeUtil.find(configuration.getUniqueAttribute(), attributes);
Object uid = uniqueAttr != null ? AttributeUtil.getSingleValue(uniqueAttr) : null;
if (uid == null) {
throw new InvalidAttributeValueException("Unique attribute value not defined");
}
return uid.toString();
}
@Override
public void delete(ObjectClass oc, Uid uid, OperationOptions oo) {
if (configuration.isReadOnly()) {
throw new ConnectorException("Can't add attribute values. Readonly set to true.");
}
update(Operation.DELETE, oc, uid, null, oo);
}
@Override
public Uid resolveUsername(ObjectClass oc, String username, OperationOptions oo) {
return resolveUsername(username, null, oo, false);
}
@Override
public FilterTranslator<String> createFilterTranslator(ObjectClass oc, OperationOptions oo) {
return new CsvFilterTranslator();
}
private boolean skipRecord(CSVRecord record) {
if (configuration.isHeaderExists() && record.getRecordNumber() == 1) {
return true;
}
if (isRecordEmpty(record)) {
return true;
}
return false;
}
@Override
public void executeQuery(ObjectClass oc, String uid, ResultsHandler handler, OperationOptions oo) {
CSVFormat csv = Util.createCsvFormatReader(configuration);
try (Reader reader = Util.createReader(configuration)) {
CSVParser parser = csv.parse(reader);
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
if (skipRecord(record)) {
continue;
}
ConnectorObject obj = createConnectorObject(record);
if (uid == null) {
if (!handler.handle(obj)) {
break;
} else {
continue;
}
}
if (!uidMatches(uid, obj.getUid().getUidValue(), configuration.isIgnoreIdentifierCase())) {
continue;
}
if (!handler.handle(obj)) {
break;
}
}
} catch (Exception ex) {
handleGenericException(ex, "Error during query execution");
}
}
private boolean uidMatches(String uid1, String uid2, boolean ignoreCase) {
return uid1.equals(uid2) || ignoreCase && uid1.equalsIgnoreCase(uid2);
}
private void validateAuthenticationInputs(String username, GuardedString password, boolean authenticate) {
if (StringUtil.isEmpty(username)) {
throw new InvalidCredentialException("Username must not be empty");
}
if (authenticate && StringUtil.isEmpty(configuration.getPasswordAttribute())) {
throw new ConfigurationException("Password attribute not defined in configuration");
}
if (authenticate && password == null) {
throw new InvalidPasswordException("Password is not defined");
}
}
private Uid resolveUsername(String username, GuardedString password, OperationOptions oo, boolean authenticate) {
validateAuthenticationInputs(username, password, authenticate);
CSVFormat csv = Util.createCsvFormatReader(configuration);
try (Reader reader = Util.createReader(configuration)) {
ConnectorObject object = null;
CSVParser parser = csv.parse(reader);
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
if (skipRecord(record)) {
continue;
}
ConnectorObject obj = createConnectorObject(record);
Name name = obj.getName();
if (name != null && username.equals(AttributeUtil.getStringValue(name))) {
object = obj;
break;
}
}
if (object == null) {
String message = authenticate ? "Invalid username and/or password" : "Invalid username";
throw new InvalidCredentialException(message);
}
if (authenticate) {
authenticate(username, password, object);
}
Uid uid = object.getUid();
if (uid == null) {
throw new UnknownUidException("Unique attribute doesn't have value for account '" + username + "'");
}
return uid;
} catch (Exception ex) {
handleGenericException(ex, "Error during authentication");
}
return null;
}
private void authenticate(String username, GuardedString password, ConnectorObject foundObject) {
GuardedString objPassword = AttributeUtil.getPasswordValue(foundObject.getAttributes());
if (objPassword == null) {
throw new InvalidPasswordException("Password not defined for username '" + username + "'");
}
// we don't want to authenticate against empty password
StringAccessor acc = new StringAccessor();
objPassword.access(acc);
if (StringUtil.isEmpty(acc.getValue())) {
throw new InvalidPasswordException("Password not defined for username '" + username + "'");
}
if (!objPassword.equals(password)) {
throw new InvalidPasswordException("Invalid username and/or password");
}
}
private void handleJustNewToken(SyncToken token, SyncResultsHandler handler) {
if (!(handler instanceof SyncTokenResultsHandler)) {
return;
}
SyncTokenResultsHandler tokenHandler = (SyncTokenResultsHandler) handler;
tokenHandler.handleResult(token);
}
@Override
public void sync(ObjectClass oc, SyncToken token, SyncResultsHandler handler, OperationOptions oo) {
File syncLockFile = Util.createSyncLockFile(configuration);
FileLock lock = Util.obtainTmpFileLock(syncLockFile);
try {
long tokenLongValue = getTokenValue(token);
LOG.info("Token {0}", tokenLongValue);
if (tokenLongValue == -1) {
//token doesn't exist, we only create new sync file - we're synchronizing from now on
String newToken = createNewSyncFile();
handleJustNewToken(new SyncToken(newToken), handler);
LOG.info("Token value was not defined {0}, only creating new sync file, synchronizing from now on.", token);
return;
}
doSync(tokenLongValue, handler);
} finally {
Util.closeQuietly(lock);
syncLockFile.delete();
}
}
private File findOldCsv(long token, String newToken, SyncResultsHandler handler) {
File oldCsv = Util.createSyncFileName(token, configuration);
if (!oldCsv.exists()) {
// we'll try to find first sync file which is newer than token (there's a possibility
// that we loose some changes this way - same as for example ldap)
oldCsv = Util.findOldestSyncFile(token, configuration);
if (oldCsv == null || oldCsv.equals(createSyncFileName(Long.parseLong(newToken), configuration))) {
// we didn't found any newer file, we should stop and handle this situation as if this
// is first time we're doing sync operation (like getLatestSyncToken())
handleJustNewToken(new SyncToken(newToken), handler);
LOG.info("File for token wasn't found, sync will stop, new token {0} will be returned.", token);
return null;
}
}
return oldCsv;
}
private void doSync(long token, SyncResultsHandler handler) {
String newToken = createNewSyncFile();
SyncToken newSyncToken = new SyncToken(newToken);
File newCsv = Util.createSyncFileName(Long.parseLong(newToken), configuration);
Integer uidIndex = header.get(configuration.getUniqueAttribute()).getIndex();
File oldCsv = findOldCsv(token, newToken, handler);
if (oldCsv == null) {
LOG.error("Couldn't find old csv file to create diff, finishing synchronization.");
return;
}
LOG.ok("Comparing files. Old {0} (exists: {1}, size: {2}) with new {3} (exists: {4}, size: {5})",
oldCsv.getName(), oldCsv.exists(), oldCsv.length(), newCsv.getName(), newCsv.exists(), newCsv.length());
try (Reader reader = Util.createReader(newCsv, configuration)) {
Map<String, CSVRecord> oldData = loadOldSyncFile(oldCsv);
Set<String> oldUsedOids = new HashSet<>();
CSVFormat csv = Util.createCsvFormatReader(configuration);
CSVParser parser = csv.parse(reader);
Iterator<CSVRecord> iterator = parser.iterator();
int changesCount = 0;
boolean shouldContinue = true;
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
if (skipRecord(record)) {
continue;
}
String uid = record.get(uidIndex);
if (StringUtil.isEmpty(uid)) {
throw new ConnectorException("Unique attribute not defined for record number "
+ record.getRecordNumber() + " in " + newCsv.getName());
}
SyncDelta delta = doSyncCreateOrUpdate(record, uid, oldData, oldUsedOids, newSyncToken, handler);
if (delta == null) {
continue;
}
changesCount++;
shouldContinue = handler.handle(delta);
if (!shouldContinue) {
break;
}
}
if (shouldContinue) {
changesCount += doSyncDeleted(oldData, oldUsedOids, newSyncToken, handler);
}
if (changesCount == 0) {
handleJustNewToken(new SyncToken(newToken), handler);
}
} catch (Exception ex) {
handleGenericException(ex, "Error during synchronization");
} finally {
cleanupOldSyncFiles();
}
}
private Map<String, CSVRecord> loadOldSyncFile(File oldCsv) {
Map<String, Column> header = initHeader(oldCsv);
if (!this.header.equals(header)) {
throw new ConnectorException("Headers of sync file '" + oldCsv + "' and current csv don't match");
}
Integer uidIndex = header.get(configuration.getUniqueAttribute()).getIndex();
Map<String, CSVRecord> oldData = new HashMap<>();
CSVFormat csv = Util.createCsvFormatReader(configuration);
try (Reader reader = Util.createReader(oldCsv, configuration)) {
CSVParser parser = csv.parse(reader);
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
if (skipRecord(record)) {
continue;
}
String uid = record.get(uidIndex);
if (StringUtil.isEmpty(uid)) {
throw new ConnectorException("Unique attribute not defined for record number "
+ record.getRecordNumber() + " in " + oldCsv.getName());
}
if (oldData.containsKey(uid)) {
throw new ConnectorException("Unique attribute value '" + uid + "' is not unique in "
+ oldCsv.getName());
}
oldData.put(uid, record);
}
} catch (Exception ex) {
handleGenericException(ex, "Error during query execution");
}
return oldData;
}
private void cleanupOldSyncFiles() {
String[] tokenFiles = Util.listTokenFiles(configuration);
Arrays.sort(tokenFiles);
int preserve = configuration.getPreserveOldSyncFiles();
if (preserve <= 1) {
LOG.info("Not removing old token files. Preserve last tokens: {0}.", preserve);
return;
}
File parentFolder = configuration.getTmpFolder();
for (int i = 0; i + preserve < tokenFiles.length; i++) {
File tokenSyncFile = new File(parentFolder, tokenFiles[i]);
if (!tokenSyncFile.exists()) {
continue;
}
LOG.info("Deleting file {0}.", tokenSyncFile.getName());
tokenSyncFile.delete();
}
}
private SyncDelta doSyncCreateOrUpdate(CSVRecord newRecord, String newRecordUid, Map<String, CSVRecord> oldData,
Set<String> oldUsedOids, SyncToken newSyncToken, SyncResultsHandler handler) {
SyncDelta delta;
CSVRecord oldRecord = oldData.get(newRecordUid);
if (oldRecord == null) {
// newRecord is new account
delta = buildSyncDelta(SyncDeltaType.CREATE, newSyncToken, newRecord);
} else {
oldUsedOids.add(newRecordUid);
// this will be an update if records aren't equal
List old = Util.copyOf(oldRecord.iterator());
List _new = Util.copyOf(newRecord.iterator());
if (old.equals(_new)) {
// record are equal, no update
return null;
}
delta = buildSyncDelta(SyncDeltaType.UPDATE, newSyncToken, newRecord);
}
LOG.ok("Created delta {0}", delta);
return delta;
}
private int doSyncDeleted(Map<String, CSVRecord> oldData, Set<String> oldUsedOids, SyncToken newSyncToken,
SyncResultsHandler handler) {
int changesCount = 0;
for (String oldUid : oldData.keySet()) {
if (oldUsedOids.contains(oldUid)) {
continue;
}
// deleted record
CSVRecord deleted = oldData.get(oldUid);
SyncDelta delta = buildSyncDelta(SyncDeltaType.DELETE, newSyncToken, deleted);
LOG.ok("Created delta {0}", delta);
changesCount++;
if (!handler.handle(delta)) {
break;
}
}
return changesCount;
}
private SyncDelta buildSyncDelta(SyncDeltaType type, SyncToken token, CSVRecord record) {
SyncDeltaBuilder builder = new SyncDeltaBuilder();
builder.setDeltaType(type);
builder.setObjectClass(ObjectClass.ACCOUNT);
builder.setToken(token);
ConnectorObject object = createConnectorObject(record);
builder.setObject(object);
return builder.build();
}
private long getTokenValue(SyncToken token) {
if (token == null || token.getValue() == null) {
return -1;
}
String object = token.getValue().toString();
if (!object.matches("[0-9]{13}")) {
return -1;
}
return Long.parseLong(object);
}
private String createNewSyncFile() {
long timestamp = System.currentTimeMillis();
String token = null;
try {
File real = configuration.getFilePath();
File last = Util.createSyncFileName(timestamp, configuration);
LOG.info("Creating new sync file {0} file {1}", timestamp, last.getName());
Files.copy(real.toPath(), last.toPath(), StandardCopyOption.REPLACE_EXISTING);
LOG.ok("New sync file created, name {0}, size {1}", last.getName(), last.length());
token = Long.toString(timestamp);
} catch (IOException ex) {
handleGenericException(ex, "Error occurred while creating new sync file " + timestamp);
}
return token;
}
@Override
public SyncToken getLatestSyncToken(ObjectClass oc) {
String csvFileName = configuration.getFilePath().getName();
String[] oldCsvFiles = Util.listTokenFiles(configuration);
String token;
if (oldCsvFiles.length != 0) {
Arrays.sort(oldCsvFiles);
String latestCsvFile = oldCsvFiles[oldCsvFiles.length - 1];
token = latestCsvFile.replaceFirst(csvFileName + "\\.sync\\.", "");
LOG.ok("Last file found, token is {0}", token);
return new SyncToken(token);
}
LOG.info("Old csv files were not found, creating token, synchronizing from \"now\".");
token = createNewSyncFile();
return new SyncToken(token);
}
@Override
public void test() {
configuration.validate();
initHeader(configuration.getFilePath());
}
@Override
public Uid addAttributeValues(ObjectClass oc, Uid uid, Set<Attribute> set, OperationOptions oo) {
if (configuration.isReadOnly()) {
throw new ConnectorException("Can't add attribute values. Readonly set to true.");
}
return update(Operation.ADD_ATTR_VALUE, oc, uid, set, oo);
}
@Override
public Uid removeAttributeValues(ObjectClass oc, Uid uid, Set<Attribute> set, OperationOptions oo) {
if (configuration.isReadOnly()) {
throw new ConnectorException("Can't add attribute values. Readonly set to true.");
}
return update(Operation.REMOVE_ATTR_VALUE, oc, uid, set, oo);
}
@Override
public Uid update(ObjectClass oc, Uid uid, Set<Attribute> set, OperationOptions oo) {
if (configuration.isReadOnly()) {
throw new ConnectorException("Can't add attribute values. Readonly set to true.");
}
return update(Operation.UPDATE, oc, uid, set, oo);
}
private boolean isRecordEmpty(CSVRecord record) {
if (!configuration.isIgnoreEmptyLines()) {
return false;
}
for (int i = 0; i < record.size(); i++) {
String value = record.get(i);
if (StringUtil.isNotBlank(value)) {
return false;
}
}
return true;
}
private Map<Integer, String> reverseHeaderMap() {
Map<Integer, String> reversed = new HashMap<>();
this.header.forEach((key, value) -> {
reversed.put(value.getIndex(), key);
});
return reversed;
}
private ConnectorObject createConnectorObject(CSVRecord record) {
ConnectorObjectBuilder builder = new ConnectorObjectBuilder();
Map<Integer, String> header = reverseHeaderMap();
for (int i = 0; i < record.size(); i++) {
String name = header.get(i);
String value = record.get(i);
if (StringUtil.isEmpty(value)) {
continue;
}
if (name.equals(configuration.getUniqueAttribute())) {
builder.setUid(value);
if (!isUniqueAndNameAttributeEqual()) {
continue;
}
}
if (name.equals(configuration.getNameAttribute())) {
builder.setName(new Name(value));
continue;
}
if (name.equals(configuration.getPasswordAttribute())) {
builder.addAttribute(OperationalAttributes.PASSWORD_NAME, new GuardedString(value.toCharArray()));
continue;
}
builder.addAttribute(name, createAttributeValues(value));
}
return builder.build();
}
private boolean isUniqueAndNameAttributeEqual() {
String uniqueAttribute = configuration.getUniqueAttribute();
String nameAttribute = configuration.getNameAttribute();
return uniqueAttribute == null ? nameAttribute == null : uniqueAttribute.equals(nameAttribute);
}
private List<String> createAttributeValues(String attributeValue) {
List<String> values = new ArrayList<>();
if (StringUtil.isEmpty(configuration.getMultivalueDelimiter())) {
values.add(attributeValue);
} else {
String[] array = attributeValue.split(configuration.getMultivalueDelimiter());
for (String item : array) {
if (StringUtil.isEmpty(item)) {
continue;
}
values.add(item);
}
}
return values;
}
private Uid update(Operation operation, ObjectClass objectClass, Uid uid, Set<Attribute> attributes,
OperationOptions oo) {
Util.notNull(uid, "Uid must not be null");
if ((Operation.ADD_ATTR_VALUE.equals(operation) || Operation.REMOVE_ATTR_VALUE.equals(operation))
&& attributes.isEmpty()) {
return uid;
}
Map<Integer, String> header = reverseHeaderMap();
attributes = normalize(attributes);
FileLock lock = Util.obtainTmpFileLock(configuration);
Reader reader = null;
Writer writer = null;
try {
reader = Util.createReader(configuration);
writer = new BufferedWriter(Channels.newWriter(lock.channel(), configuration.getEncoding()));
boolean found = false;
CSVFormat csv = Util.createCsvFormat(configuration);
CSVParser parser = csv.parse(reader);
csv = Util.createCsvFormat(configuration);
CSVPrinter printer = csv.print(writer);
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
Map<String, String> data = new HashMap<>();
for (int i = 0; i < record.size(); i++) {
data.put(header.get(i), record.get(i));
}
String recordUidValue = data.get(configuration.getUniqueAttribute());
if (StringUtil.isEmpty(recordUidValue)) {
continue;
}
if (!uidMatches(uid.getUidValue(), recordUidValue, configuration.isIgnoreIdentifierCase())) {
printer.printRecord(record);
continue;