-
Notifications
You must be signed in to change notification settings - Fork 188
/
ResourceObjectConverter.java
2556 lines (2190 loc) · 124 KB
/
ResourceObjectConverter.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
/*
* Copyright (c) 2010-2017 Evolveum
*
* 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 com.evolveum.midpoint.provisioning.impl;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.refinery.*;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.util.JavaTypeConverter;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.provisioning.api.GenericConnectorException;
import com.evolveum.midpoint.provisioning.ucf.api.*;
import com.evolveum.midpoint.provisioning.util.ProvisioningUtil;
import com.evolveum.midpoint.repo.cache.RepositoryCache;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.processor.*;
import com.evolveum.midpoint.schema.result.*;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.Holder;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.*;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.util.*;
import java.util.Map.Entry;
/**
*
* Responsibilities:
* protected objects
* simulated activation
* script execution
* avoid duplicate values
* attributes returned by default/not returned by default
*
* Limitations:
* must NOT access repository
* does not know about OIDs
*
* @author Katarina Valalikova
* @author Radovan Semancik
*
*/
@Component
public class ResourceObjectConverter {
private static final String DOT_CLASS = ResourceObjectConverter.class.getName() + ".";
public static final String OPERATION_MODIFY_ENTITLEMENT = DOT_CLASS + "modifyEntitlement";
private static final String OPERATION_ADD_RESOURCE_OBJECT = DOT_CLASS + "addResourceObject";
private static final String OPERATION_MODIFY_RESOURCE_OBJECT = DOT_CLASS + "modifyResourceObject";
private static final String OPERATION_DELETE_RESOURCE_OBJECT = DOT_CLASS + "deleteResourceObject";
private static final String OPERATION_REFRESH_OPERATION_STATUS = DOT_CLASS + "refreshOperationStatus";
@Autowired private EntitlementConverter entitlementConverter;
@Autowired private MatchingRuleRegistry matchingRuleRegistry;
@Autowired private ResourceObjectReferenceResolver resourceObjectReferenceResolver;
@Autowired private ShadowCaretaker shadowCaretaker;
@Autowired private Clock clock;
@Autowired private PrismContext prismContext;
@Autowired private RelationRegistry relationRegistry;
@Autowired private AsyncUpdateListeningRegistry listeningRegistry;
private static final Trace LOGGER = TraceManager.getTrace(ResourceObjectConverter.class);
static final String FULL_SHADOW_KEY = ResourceObjectConverter.class.getName()+".fullShadow";
public PrismObject<ShadowType> getResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, boolean fetchAssociations, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException,
SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Getting resource object {}", identifiers);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
PrismObject<ShadowType> resourceShadow = fetchResourceObject(ctx, identifiers,
attributesToReturn, fetchAssociations, parentResult); // todo consider whether it is always necessary to fetch the entitlements
LOGGER.trace("Got resource object\n{}", resourceShadow.debugDumpLazily());
return resourceShadow;
}
/**
* Tries to get the object directly if primary identifiers are present. Tries to search for the object if they are not.
*/
public PrismObject<ShadowType> locateResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Locating resource object {}", identifiers);
ConnectorInstance connector = ctx.getConnector(ReadCapabilityType.class, parentResult);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
if (hasAllIdentifiers(identifiers, ctx.getObjectClassDefinition())) {
return fetchResourceObject(ctx, identifiers,
attributesToReturn, true, parentResult); // todo consider whether it is always necessary to fetch the entitlements
} else {
// Search
Collection<? extends RefinedAttributeDefinition> secondaryIdentifierDefs = ctx.getObjectClassDefinition().getSecondaryIdentifiers();
// Assume single secondary identifier for simplicity
if (secondaryIdentifierDefs.size() > 1) {
throw new UnsupportedOperationException("Composite secondary identifier is not supported yet");
} else if (secondaryIdentifierDefs.isEmpty()) {
throw new SchemaException("No secondary identifier defined, cannot search");
}
RefinedAttributeDefinition<String> secondaryIdentifierDef = secondaryIdentifierDefs.iterator().next();
ResourceAttribute<?> secondaryIdentifier = null;
for (ResourceAttribute<?> identifier: identifiers) {
if (identifier.getElementName().equals(secondaryIdentifierDef.getName())) {
secondaryIdentifier = identifier;
}
}
if (secondaryIdentifier == null) {
throw new SchemaException("No secondary identifier present, cannot search. Identifiers: "+identifiers);
}
final ResourceAttribute<?> finalSecondaryIdentifier = secondaryIdentifier;
List<PrismPropertyValue<String>> secondaryIdentifierValues = (List) secondaryIdentifier.getValues();
PrismPropertyValue<String> secondaryIdentifierValue;
if (secondaryIdentifierValues.size() > 1) {
throw new IllegalStateException("Secondary identifier has more than one value: " + secondaryIdentifier.getValues());
} else if (secondaryIdentifierValues.size() == 1) {
secondaryIdentifierValue = secondaryIdentifierValues.get(0).clone();
} else {
secondaryIdentifierValue = null;
}
ObjectQuery query = prismContext.queryFor(ShadowType.class)
.itemWithDef(secondaryIdentifierDef, ShadowType.F_ATTRIBUTES, secondaryIdentifierDef.getName()).eq(secondaryIdentifierValue)
.build();
final Holder<PrismObject<ShadowType>> shadowHolder = new Holder<>();
ShadowResultHandler handler = new ShadowResultHandler() {
@Override
public boolean handle(PrismObject<ShadowType> shadow) {
if (!shadowHolder.isEmpty()) {
throw new IllegalStateException("More than one value found for secondary identifier "+finalSecondaryIdentifier);
}
shadowHolder.setValue(shadow);
return true;
}
};
try {
connector.search(ctx.getObjectClassDefinition(), query, handler, attributesToReturn, null, null, ctx, parentResult);
if (shadowHolder.isEmpty()) {
throw new ObjectNotFoundException("No object found for secondary identifier "+secondaryIdentifier);
}
PrismObject<ShadowType> shadow = shadowHolder.getValue();
PrismObject<ShadowType> finalShadow = postProcessResourceObjectRead(ctx, shadow, true, parentResult);
LOGGER.trace("Located resource object {}", finalShadow);
return finalShadow;
} catch (GenericFrameworkException e) {
throw new GenericConnectorException(e.getMessage(), e);
}
}
}
private boolean hasAllIdentifiers(Collection<? extends ResourceAttribute<?>> attributes,
RefinedObjectClassDefinition objectClassDefinition) {
Collection<? extends RefinedAttributeDefinition> identifierDefs = objectClassDefinition.getPrimaryIdentifiers();
for (RefinedAttributeDefinition identifierDef: identifierDefs) {
boolean found = false;
for(ResourceAttribute<?> attribute: attributes) {
if (attribute.getElementName().equals(identifierDef.getName()) && !attribute.isEmpty()) {
found = true;
}
}
if (!found) {
return false;
}
}
return true;
}
public AsynchronousOperationReturnValue<PrismObject<ShadowType>> addResourceObject(ProvisioningContext ctx,
PrismObject<ShadowType> shadow, OperationProvisioningScriptsType scripts, ConnectorOperationOptions connOptions,
boolean skipExplicitUniquenessCheck, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException,
ObjectAlreadyExistsException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.createSubresult(OPERATION_ADD_RESOURCE_OBJECT);
ResourceType resource = ctx.getResource();
LOGGER.trace("Adding resource object {}", shadow);
// We might be modifying the shadow (e.g. for simulated capabilities). But we do not want the changes
// to propagate back to the calling code. Hence the clone.
PrismObject<ShadowType> shadowClone = shadow.clone();
ShadowType shadowType = shadowClone.asObjectable();
Collection<ResourceAttribute<?>> resourceAttributesAfterAdd = null;
if (ProvisioningUtil.isProtectedShadow(ctx.getObjectClassDefinition(), shadowClone, matchingRuleRegistry,
relationRegistry)) {
LOGGER.error("Attempt to add protected shadow " + shadowType + "; ignoring the request");
SecurityViolationException e = new SecurityViolationException("Cannot get protected shadow " + shadowType);
result.recordFatalError(e);
throw e;
}
if (!skipExplicitUniquenessCheck) {
checkForAddConflicts(ctx, shadow, result);
}
checkForCapability(ctx, CreateCapabilityType.class, result);
Collection<Operation> additionalOperations = new ArrayList<>();
addExecuteScriptOperation(additionalOperations, ProvisioningOperationTypeType.ADD, scripts, resource,
result);
entitlementConverter.processEntitlementsAdd(ctx, shadowClone);
ConnectorInstance connector = ctx.getConnector(CreateCapabilityType.class, result);
AsynchronousOperationReturnValue<Collection<ResourceAttribute<?>>> connectorAsyncOpRet = null;
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("PROVISIONING ADD operation on resource {}\n ADD object:\n{}\n additional operations:\n{}",
resource.asPrismObject(), shadowType.asPrismObject().debugDump(),
SchemaDebugUtil.debugDump(additionalOperations,2));
}
transformActivationAttributesAdd(ctx, shadowType, result);
connectorAsyncOpRet = connector.addObject(shadowClone, additionalOperations, ctx, result);
resourceAttributesAfterAdd = connectorAsyncOpRet.getReturnValue();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("PROVISIONING ADD successful, returned attributes:\n{}",
SchemaDebugUtil.prettyPrint(resourceAttributesAfterAdd));
}
// Be careful not to apply this to the cloned shadow. This needs to be propagated
// outside this method.
applyAfterOperationAttributes(shadow, resourceAttributesAfterAdd);
} catch (CommunicationException ex) {
result.recordFatalError(
"Could not create object on the resource. Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
result.recordFatalError("Could not create object on the resource. Generic error in connector: " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector: " + ex.getMessage(), ex);
} catch (ObjectAlreadyExistsException ex){
result.recordFatalError("Could not create object on the resource. Object already exists on the resource: " + ex.getMessage(), ex);
throw new ObjectAlreadyExistsException("Object already exists on the resource: " + ex.getMessage(), ex);
} catch (ConfigurationException | SchemaException | SecurityViolationException | PolicyViolationException | RuntimeException | Error e){
result.recordFatalError(e);
throw e;
}
// Execute entitlement modification on other objects (if needed)
executeEntitlementChangesAdd(ctx, shadowClone, scripts, connOptions, result);
LOGGER.trace("Added resource object {}", shadow);
computeResultStatus(result);
AsynchronousOperationReturnValue<PrismObject<ShadowType>> asyncOpRet = AsynchronousOperationReturnValue.wrap(shadow, result);
if (connectorAsyncOpRet != null) {
asyncOpRet.setOperationType(connectorAsyncOpRet.getOperationType());
}
return asyncOpRet;
}
/**
* Special case for multi-connectors (e.g. semi-manual connectors). There is a possibility that the object
* which we want to add is already present in the backing store. In case of manual provisioning the resource
* itself will not indicate "already exist" error. We have to explicitly check for that.
*/
private void checkForAddConflicts(ProvisioningContext ctx, PrismObject<ShadowType> shadow, OperationResult result) throws ObjectAlreadyExistsException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, ObjectNotFoundException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Checking for add conflicts for {}", ShadowUtil.shortDumpShadow(shadow));
}
PrismObject<ShadowType> existingObject = null;
ConnectorInstance readConnector = null;
try {
ConnectorInstance createConnector = ctx.getConnector(CreateCapabilityType.class, result);
readConnector = ctx.getConnector(ReadCapabilityType.class, result);
if (readConnector == createConnector) {
// Same connector for reading and creating. We assume that the connector can check uniqueness itself.
// No need to check explicitly. We will gladly skip the check, as the check may be additional overhead
// that we normally do not need or want.
return;
}
ResourceObjectIdentification identification = ResourceObjectIdentification.createFromShadow(ctx.getObjectClassDefinition(), shadow.asObjectable());
existingObject = readConnector.fetchObject(identification, null, ctx, result);
} catch (ObjectNotFoundException e) {
// This is OK
result.muteLastSubresultError();
return;
} catch (CommunicationException ex) {
result.recordFatalError(
"Could not create object on the resource. Error communicating with the connector " + readConnector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + readConnector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
result.recordFatalError("Could not create object on the resource. Generic error in connector: " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector: " + ex.getMessage(), ex);
} catch (Throwable e){
result.recordFatalError(e);
throw e;
}
if (existingObject == null) {
LOGGER.trace("No add conflicts for {}", shadow);
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Detected add conflict for {}, conflicting shadow: {}", ShadowUtil.shortDumpShadow(shadow), ShadowUtil.shortDumpShadow(existingObject));
}
LOGGER.trace("Conflicting shadow:\n{}", existingObject.debugDumpLazily(1));
ObjectAlreadyExistsException e = new ObjectAlreadyExistsException("Object " + ShadowUtil.shortDumpShadow(shadow) +
" already exists in the snapshot of " + ctx.getResource() + " as " + ShadowUtil.shortDumpShadow(existingObject));
result.recordFatalError(e);
throw e;
}
}
public AsynchronousOperationResult deleteResourceObject(ProvisioningContext ctx, PrismObject<ShadowType> shadow,
OperationProvisioningScriptsType scripts, ConnectorOperationOptions connOptions, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.createSubresult(OPERATION_DELETE_RESOURCE_OBJECT);
LOGGER.trace("Deleting resource object {}", shadow);
checkForCapability(ctx, DeleteCapabilityType.class, result);
Collection<? extends ResourceAttribute<?>> identifiers = ShadowUtil
.getAllIdentifiers(shadow);
if (ProvisioningUtil.isProtectedShadow(ctx.getObjectClassDefinition(), shadow, matchingRuleRegistry, relationRegistry)) {
LOGGER.error("Attempt to delete protected resource object " + ctx.getObjectClassDefinition() + ": "
+ identifiers + "; ignoring the request");
SecurityViolationException e = new SecurityViolationException("Cannot delete protected resource object "
+ ctx.getObjectClassDefinition() + ": " + identifiers);
result.recordFatalError(e);
throw e;
}
//check idetifier if it is not null
if (identifiers.isEmpty() && shadow.asObjectable().getFailedOperationType()!= null){
throw new GenericConnectorException(
"Unable to delete object from the resource. Probably it has not been created yet because of previous unavailability of the resource.");
}
// Execute entitlement modification on other objects (if needed)
executeEntitlementChangesDelete(ctx, shadow, scripts, connOptions, result);
Collection<Operation> additionalOperations = new ArrayList<>();
addExecuteScriptOperation(additionalOperations, ProvisioningOperationTypeType.DELETE, scripts, ctx.getResource(),
result);
ConnectorInstance connector = ctx.getConnector(DeleteCapabilityType.class, result);
AsynchronousOperationResult connectorAsyncOpRet = null;
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"PROVISIONING DELETE operation on {}\n DELETE object, object class {}, identified by:\n{}\n additional operations:\n{}",
ctx.getResource(), shadow.asObjectable().getObjectClass(),
SchemaDebugUtil.debugDump(identifiers),
SchemaDebugUtil.debugDump(additionalOperations));
}
if (!ResourceTypeUtil.isDeleteCapabilityEnabled(ctx.getResource())){
UnsupportedOperationException e = new UnsupportedOperationException("Resource does not support 'delete' operation");
result.recordFatalError(e);
throw e;
}
connectorAsyncOpRet = connector.deleteObject(ctx.getObjectClassDefinition(), additionalOperations, shadow, identifiers, ctx, result);
computeResultStatus(result);
LOGGER.debug("PROVISIONING DELETE: {}", result.getStatus());
} catch (ObjectNotFoundException ex) {
result.recordFatalError("Can't delete object " + shadow
+ ". Reason: " + ex.getMessage(), ex);
throw new ObjectNotFoundException("An error occured while deleting resource object " + shadow
+ "whith identifiers " + identifiers + ": " + ex.getMessage(), ex);
} catch (CommunicationException ex) {
result.recordFatalError(
"Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with the connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (ConfigurationException ex) {
result.recordFatalError(
"Configuration error in connector " + connector + ": " + ex.getMessage(), ex);
throw new ConfigurationException("Configuration error in connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (ExpressionEvaluationException ex) {
result.recordFatalError(
"Expression error while setting up the resource: " + ex.getMessage(), ex);
throw new ExpressionEvaluationException("Expression error while setting up the resource: "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
result.recordFatalError("Generic error in connector: " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector: " + ex.getMessage(), ex);
} catch (SecurityViolationException | PolicyViolationException | RuntimeException | Error ex) {
result.recordFatalError(ex);
throw ex;
}
LOGGER.trace("Deleted resource object {}", shadow);
AsynchronousOperationResult aResult = AsynchronousOperationResult.wrap(result);
updateQuantum(ctx, connector, aResult, parentResult);
if (connectorAsyncOpRet != null) {
aResult.setOperationType(connectorAsyncOpRet.getOperationType());
}
return aResult;
}
private void updateQuantum(ProvisioningContext ctx, ConnectorInstance connectorUsedForOperation, AsynchronousOperationResult aResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
ConnectorInstance readConnector = ctx.getConnector(ReadCapabilityType.class, parentResult);
if (readConnector != connectorUsedForOperation) {
// Writing by different connector that we are going to use for reading: danger of quantum effects
aResult.setQuantumOperation(true);
}
}
public AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>> modifyResourceObject(
ProvisioningContext ctx,
PrismObject<ShadowType> repoShadow,
OperationProvisioningScriptsType scripts,
ConnectorOperationOptions connOptions,
Collection<? extends ItemDelta> itemDeltas,
XMLGregorianCalendar now,
OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException {
OperationResult result = parentResult.createSubresult(OPERATION_MODIFY_RESOURCE_OBJECT);
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Modifying resource object {}, deltas:\n{}", repoShadow, DebugUtil.debugDump(itemDeltas, 1));
}
RefinedObjectClassDefinition objectClassDefinition = ctx.getObjectClassDefinition();
Collection<Operation> operations = new ArrayList<>();
Collection<? extends ResourceAttribute<?>> identifiers = ShadowUtil.getAllIdentifiers(repoShadow);
Collection<? extends ResourceAttribute<?>> primaryIdentifiers = ShadowUtil.getPrimaryIdentifiers(repoShadow);
if (ProvisioningUtil.isProtectedShadow(ctx.getObjectClassDefinition(), repoShadow, matchingRuleRegistry,
relationRegistry)) {
if (hasChangesOnResource(itemDeltas)) {
LOGGER.error("Attempt to modify protected resource object " + objectClassDefinition + ": "
+ identifiers);
SecurityViolationException e = new SecurityViolationException("Cannot modify protected resource object "
+ objectClassDefinition + ": " + identifiers);
result.recordFatalError(e);
throw e;
} else {
// Return immediately. This structure of the code makes sure that we do not execute any
// resource operation for protected account even if there is a bug in the code below.
LOGGER.trace("No resource modifications for protected resource object {}: {}; skipping",
objectClassDefinition, identifiers);
result.recordNotApplicableIfUnknown();
return AsynchronousOperationReturnValue.wrap(null, result);
}
}
boolean hasVolatilityTriggerModification = false;
boolean hasResourceModification = false;
for (ItemDelta modification: itemDeltas) {
ItemPath path = modification.getPath();
QName firstPathName = path.firstName();
if (ProvisioningUtil.isAttributeModification(firstPathName)) {
hasResourceModification = true;
QName attrName = path.rest().firstNameOrFail();
RefinedAttributeDefinition<Object> attrDef = ctx.getObjectClassDefinition().findAttributeDefinition(attrName);
if (attrDef.isVolatilityTrigger()) {
LOGGER.trace("Will pre-read and re-read object because volatility trigger attribute {} has changed", attrName);
hasVolatilityTriggerModification = true;
break;
}
} else if (ProvisioningUtil.isNonAttributeResourceModification(firstPathName)) {
hasResourceModification = true;
}
}
if (!hasResourceModification) {
// Quit early, so we avoid potential pre-read and other processing when there is no point of doing so.
// Also the read may fail which may invoke consistency mechanism which will complicate the situation.
LOGGER.trace("No resource modification found for {}, skipping", identifiers);
result.recordNotApplicableIfUnknown();
return AsynchronousOperationReturnValue.wrap(null, result);
}
/*
* State of the shadow before execution of the deltas - e.g. with original attributes, as it may be recorded in such a way in
* groups of which this account is a member of. (In case of object->subject associations.)
*
* This is used when the resource does NOT provide referential integrity by itself. This is e.g. the case of OpenDJ with default
* settings.
*
* On the contrary, AD and OpenDJ with referential integrity plugin do provide automatic referential integrity, so this feature is
* not needed.
*
* We decide based on setting of explicitReferentialIntegrity in association definition.
*/
collectAttributeAndEntitlementChanges(ctx, itemDeltas, operations, repoShadow, result);
PrismObject<ShadowType> preReadShadow = null;
Collection<PropertyModificationOperation> sideEffectOperations = null;
AsynchronousOperationReturnValue<Collection<PropertyModificationOperation>> modifyAsyncRet = null;
//check identifier if it is not null
if ((primaryIdentifiers == null || primaryIdentifiers.isEmpty()) && repoShadow.asObjectable().getFailedOperationType() != null){
GenericConnectorException e = new GenericConnectorException(
"Unable to modify object in the resource. Probably it has not been created yet because of previous unavailability of the resource.");
result.recordFatalError(e);
throw e;
}
if (hasVolatilityTriggerModification || ResourceTypeUtil.isAvoidDuplicateValues(ctx.getResource()) || isRename(ctx, operations)) {
// We need to filter out the deltas that add duplicate values or remove values that are not there
LOGGER.trace("Pre-reading resource shadow");
preReadShadow = preReadShadow(ctx, identifiers, operations, true, repoShadow, result); // yes, we need associations here
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Pre-read object (straight from the resource):\n{}", preReadShadow==null?null:preReadShadow.debugDump(1));
}
// If there are pending changes in the shadow then we have to apply to pre-read object.
// The pre-read object may be out of date (e.g. in case of semi-manual connectors).
// In that case we may falsely remove some of the modifications. E.g. in case that
// account is enabled, then disable and then enabled again. If backing store still
// has the account as enabled, then the last enable operation would be ignored.
// No case is created to re-enable the account. And the account stays disabled at the end.
preReadShadow = shadowCaretaker.applyPendingOperations(ctx, repoShadow, preReadShadow, true, now);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Pre-read object (applied pending operations):\n{}", preReadShadow==null?null:preReadShadow.debugDump(1));
}
}
if (!operations.isEmpty()) {
// This must go after the skip check above. Otherwise the scripts would be executed even if there is no need to.
addExecuteScriptOperation(operations, ProvisioningOperationTypeType.MODIFY, scripts, ctx.getResource(), result);
if (InternalsConfig.isSanityChecks()) {
// MID-3964
if (MiscUtil.hasDuplicates(operations)) {
throw new SchemaException("Duplicated changes: "+operations);
}
}
// Execute primary ICF operation on this shadow
modifyAsyncRet = executeModify(ctx, (preReadShadow == null ? repoShadow.clone() : preReadShadow), identifiers, operations, connOptions, result);
if (modifyAsyncRet != null) {
sideEffectOperations = modifyAsyncRet.getReturnValue();
}
} else {
// We have to check BEFORE we add script operations, otherwise the check would be pointless
LOGGER.trace("No modifications for connector object specified. Skipping processing of subject executeModify.");
}
Collection<PropertyDelta<PrismPropertyValue>> sideEffectDeltas = convertToPropertyDelta(sideEffectOperations);
/*
* State of the shadow after execution of the deltas - e.g. with new DN (if it was part of the delta), because this one should be recorded
* in groups of which this account is a member of. (In case of object->subject associations.)
*/
PrismObject<ShadowType> shadowAfter = preReadShadow == null ? repoShadow.clone() : preReadShadow.clone();
for (ItemDelta itemDelta : itemDeltas) {
itemDelta.applyTo(shadowAfter);
}
PrismObject<ShadowType> postReadShadow = null;
if (hasVolatilityTriggerModification) {
// There may be other changes that were not detected by the connector. Re-read the object and compare.
LOGGER.trace("Post-reading resource shadow");
postReadShadow = preReadShadow(ctx, identifiers, operations, true, repoShadow, result);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Post-read object:\n{}", postReadShadow.debugDump());
}
ObjectDelta<ShadowType> resourceShadowDelta = preReadShadow.diff(postReadShadow);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Determined side-effect changes by old-new diff:\n{}", resourceShadowDelta.debugDump());
}
for (ItemDelta modification: resourceShadowDelta.getModifications()) {
if (modification.getParentPath().startsWithName(ShadowType.F_ATTRIBUTES) && !ItemDeltaCollectionsUtil
.hasEquivalent(itemDeltas, modification)) {
ItemDeltaCollectionsUtil.merge(sideEffectDeltas, modification);
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Side-effect changes after merging with old-new diff:\n{}", DebugUtil.debugDump(sideEffectDeltas));
}
}
Collection<? extends ItemDelta> allDeltas = new ArrayList<>();
((Collection)allDeltas).addAll(itemDeltas);
((Collection)allDeltas).addAll(sideEffectDeltas);
// Execute entitlement modification on other objects (if needed)
shadowAfter = executeEntitlementChangesModify(ctx,
preReadShadow == null ? repoShadow : preReadShadow,
postReadShadow == null ? shadowAfter : postReadShadow,
scripts, connOptions, allDeltas, result);
if (!sideEffectDeltas.isEmpty()) {
if (preReadShadow != null) {
PrismUtil.setDeltaOldValue(preReadShadow, sideEffectDeltas);
} else {
PrismUtil.setDeltaOldValue(repoShadow, sideEffectDeltas);
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Modificaiton side-effect changes:\n{}", DebugUtil.debugDump(sideEffectDeltas));
}
LOGGER.trace("Modified resource object {}", repoShadow);
computeResultStatus(result);
AsynchronousOperationReturnValue<Collection<PropertyDelta<PrismPropertyValue>>> aResult = AsynchronousOperationReturnValue.wrap(sideEffectDeltas, result);
if (modifyAsyncRet != null) {
aResult.setOperationType(modifyAsyncRet.getOperationType());
}
return aResult;
} catch (Throwable e) {
result.recordFatalError(e);
throw e;
}
}
private Collection<PropertyDelta<PrismPropertyValue>> convertToPropertyDelta(
Collection<PropertyModificationOperation> sideEffectOperations) {
Collection<PropertyDelta<PrismPropertyValue>> sideEffectDeltas = new ArrayList<>();
if (sideEffectOperations != null) {
for (PropertyModificationOperation mod : sideEffectOperations){
sideEffectDeltas.add(mod.getPropertyDelta());
}
}
return sideEffectDeltas;
}
@SuppressWarnings("rawtypes")
private AsynchronousOperationReturnValue<Collection<PropertyModificationOperation>> executeModify(ProvisioningContext ctx,
PrismObject<ShadowType> currentShadow, Collection<? extends ResourceAttribute<?>> identifiers,
Collection<Operation> operations, ConnectorOperationOptions connOptions, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, SecurityViolationException, PolicyViolationException, ConfigurationException, ObjectAlreadyExistsException, ExpressionEvaluationException {
Collection<PropertyModificationOperation> sideEffectChanges = new HashSet<>();
RefinedObjectClassDefinition objectClassDefinition = ctx.getObjectClassDefinition();
if (operations.isEmpty()){
LOGGER.trace("No modifications for resource object. Skipping modification.");
return null;
} else {
LOGGER.trace("Resource object modification operations: {}", operations);
}
checkForCapability(ctx, UpdateCapabilityType.class, parentResult);
if (!ShadowUtil.hasPrimaryIdentifier(identifiers, objectClassDefinition)) {
Collection<? extends ResourceAttribute<?>> primaryIdentifiers = resourceObjectReferenceResolver.resolvePrimaryIdentifier(ctx, identifiers, "modification of resource object "+identifiers, parentResult);
if (primaryIdentifiers == null || primaryIdentifiers.isEmpty()) {
throw new ObjectNotFoundException("Cannot find repository shadow for identifiers "+identifiers);
}
identifiers = primaryIdentifiers;
}
// Invoke ICF
ConnectorInstance connector = ctx.getConnector(UpdateCapabilityType.class, parentResult);
AsynchronousOperationReturnValue<Collection<PropertyModificationOperation>> connectorAsyncOpRet = null;
try {
if (ResourceTypeUtil.isAvoidDuplicateValues(ctx.getResource())) {
if (currentShadow == null) {
LOGGER.trace("Fetching shadow for duplicate filtering");
currentShadow = preReadShadow(ctx, identifiers, operations, false, currentShadow, parentResult);
}
if (currentShadow == null) {
LOGGER.debug("We do not have pre-read shadow, skipping duplicate filtering");
} else {
LOGGER.trace("Filtering out duplicate values");
Collection<Operation> filteredOperations = new ArrayList<>(operations.size());
for (Operation origOperation: operations) {
if (origOperation instanceof PropertyModificationOperation) {
PropertyModificationOperation modificationOperation = (PropertyModificationOperation)origOperation;
PropertyDelta<?> propertyDelta = modificationOperation.getPropertyDelta();
PropertyDelta<?> filteredDelta = ProvisioningUtil.narrowPropertyDelta(propertyDelta, currentShadow,
modificationOperation.getMatchingRuleQName(), matchingRuleRegistry);
if (filteredDelta != null && !filteredDelta.isEmpty()) {
if (propertyDelta == filteredDelta) {
filteredOperations.add(origOperation);
} else {
PropertyModificationOperation newOp = new PropertyModificationOperation<>(filteredDelta);
newOp.setMatchingRuleQName(modificationOperation.getMatchingRuleQName());
filteredOperations.add(newOp);
}
} else {
LOGGER.trace("Filtering out modification {} because it has empty delta after narrow", propertyDelta);
}
} else if (origOperation instanceof ExecuteProvisioningScriptOperation) {
filteredOperations.add(origOperation);
}
}
if (filteredOperations.isEmpty()) {
LOGGER.debug("No modifications for connector object specified (after filtering). Skipping processing.");
parentResult.recordSuccess();
return null;
}
operations = filteredOperations;
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"PROVISIONING MODIFY operation on {}\n MODIFY object, object class {}, identified by:\n{}\n changes:\n{}",
ctx.getResource(), objectClassDefinition.getHumanReadableName(),
SchemaDebugUtil.debugDump(identifiers, 1), SchemaDebugUtil.debugDump(operations, 1));
}
if (!ResourceTypeUtil.isUpdateCapabilityEnabled(ctx.getResource())){
if (operations == null || operations.isEmpty()){
LOGGER.debug("No modifications for connector object specified (after filtering). Skipping processing.");
parentResult.recordSuccess();
return null;
}
UnsupportedOperationException e = new UnsupportedOperationException("Resource does not support 'update' operation");
parentResult.recordFatalError(e);
throw e;
}
Collection<ResourceAttribute<?>> identifiersWorkingCopy = cloneIdentifiers(identifiers); // because identifiers can be modified e.g. on rename operation
List<Collection<Operation>> operationsWaves = sortOperationsIntoWaves(operations, objectClassDefinition);
LOGGER.trace("Operation waves: {}", operationsWaves.size());
boolean inProgress = false;
String asynchronousOperationReference = null;
for (Collection<Operation> operationsWave : operationsWaves) {
Collection<RefinedAttributeDefinition> readReplaceAttributes = determineReadReplace(ctx, operationsWave, objectClassDefinition);
LOGGER.trace("Read+Replace attributes: {}", readReplaceAttributes);
if (!readReplaceAttributes.isEmpty()) {
AttributesToReturn attributesToReturn = new AttributesToReturn();
attributesToReturn.setReturnDefaultAttributes(false);
attributesToReturn.setAttributesToReturn(readReplaceAttributes);
// TODO eliminate this fetch if this is first wave and there are no explicitly requested attributes
// but make sure currentShadow contains all required attributes
LOGGER.trace("Fetching object because of READ+REPLACE mode");
currentShadow = fetchResourceObject(ctx,
identifiersWorkingCopy, attributesToReturn, false, parentResult);
operationsWave = convertToReplace(ctx, operationsWave, currentShadow);
}
if (!operationsWave.isEmpty()) {
ResourceObjectIdentification identification = ResourceObjectIdentification.create(objectClassDefinition, identifiersWorkingCopy);
connectorAsyncOpRet = connector.modifyObject(identification, currentShadow, operationsWave, connOptions, ctx, parentResult);
Collection<PropertyModificationOperation> sideEffects = connectorAsyncOpRet.getReturnValue();
if (sideEffects != null) {
sideEffectChanges.addAll(sideEffects);
// we accept that one attribute can be changed multiple times in sideEffectChanges; TODO: normalize
}
if (connectorAsyncOpRet.isInProgress()) {
inProgress = true;
asynchronousOperationReference = connectorAsyncOpRet.getOperationResult().getAsynchronousOperationReference();
}
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("PROVISIONING MODIFY successful, inProgress={}, side-effect changes {}", inProgress, DebugUtil.debugDump(sideEffectChanges));
}
if (inProgress) {
parentResult.recordInProgress();
parentResult.setAsynchronousOperationReference(asynchronousOperationReference);
}
} catch (ObjectNotFoundException ex) {
parentResult.recordFatalError("Object to modify not found: " + ex.getMessage(), ex);
throw new ObjectNotFoundException("Object to modify not found: " + ex.getMessage(), ex);
} catch (CommunicationException ex) {
parentResult.recordFatalError(
"Error communicating with the connector " + connector + ": " + ex.getMessage(), ex);
throw new CommunicationException("Error communicating with connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (GenericFrameworkException ex) {
parentResult.recordFatalError(
"Generic error in the connector " + connector + ": " + ex.getMessage(), ex);
throw new GenericConnectorException("Generic error in connector connector " + connector + ": "
+ ex.getMessage(), ex);
} catch (ObjectAlreadyExistsException ex) {
parentResult.recordFatalError("Conflict during modify: " + ex.getMessage(), ex);
throw new ObjectAlreadyExistsException("Conflict during modify: " + ex.getMessage(), ex);
} catch (SchemaException | ConfigurationException | ExpressionEvaluationException | SecurityViolationException | PolicyViolationException | RuntimeException | Error ex) {
parentResult.recordFatalError(ex.getMessage(), ex);
throw ex;
}
AsynchronousOperationReturnValue<Collection<PropertyModificationOperation>> asyncOpRet = AsynchronousOperationReturnValue.wrap(sideEffectChanges, parentResult);
if (connectorAsyncOpRet != null) {
asyncOpRet.setOperationType(connectorAsyncOpRet.getOperationType());
}
return asyncOpRet;
}
@SuppressWarnings("rawtypes")
private PrismObject<ShadowType> preReadShadow(
ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers,
Collection<Operation> operations,
boolean fetchEntitlements,
PrismObject<ShadowType> repoShadow,
OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException {
PrismObject<ShadowType> currentShadow;
List<RefinedAttributeDefinition> neededExtraAttributes = new ArrayList<>();
for (Operation operation : operations) {
RefinedAttributeDefinition rad = getRefinedAttributeDefinitionIfApplicable(operation, ctx.getObjectClassDefinition());
if (rad != null && (!rad.isReturnedByDefault() || rad.getFetchStrategy() == AttributeFetchStrategyType.EXPLICIT)) {
neededExtraAttributes.add(rad);
}
}
AttributesToReturn attributesToReturn = new AttributesToReturn();
attributesToReturn.setAttributesToReturn(neededExtraAttributes);
try {
currentShadow = fetchResourceObject(ctx, identifiers,
attributesToReturn, fetchEntitlements, parentResult);
} catch (ObjectNotFoundException e) {
// This may happen for semi-manual connectors that are not yet up to date.
// No big deal. We will have to work without it.
LOGGER.warn("Cannot pre-read shadow {}, it is probably not present in the {}. Skipping pre-read.", identifiers, ctx.getResource());
return null;
}
if (repoShadow != null) {
currentShadow.setOid(repoShadow.getOid());
}
currentShadow.asObjectable().setName(new PolyStringType(ShadowUtil.determineShadowName(currentShadow)));
return currentShadow;
}
private Collection<RefinedAttributeDefinition> determineReadReplace(ProvisioningContext ctx, Collection<Operation> operations, RefinedObjectClassDefinition objectClassDefinition) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
Collection<RefinedAttributeDefinition> retval = new ArrayList<>();
for (Operation operation : operations) {
RefinedAttributeDefinition rad = getRefinedAttributeDefinitionIfApplicable(operation, objectClassDefinition);
if (rad != null && isReadReplaceMode(ctx, rad, objectClassDefinition) && operation instanceof PropertyModificationOperation) { // third condition is just to be sure
PropertyDelta propertyDelta = ((PropertyModificationOperation) operation).getPropertyDelta();
if (propertyDelta.isAdd() || propertyDelta.isDelete()) {
retval.add(rad); // REPLACE operations are not needed to be converted to READ+REPLACE
}
}
}
return retval;
}
private boolean isReadReplaceMode(ProvisioningContext ctx, RefinedAttributeDefinition rad, RefinedObjectClassDefinition objectClassDefinition) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
if (rad.getReadReplaceMode() != null) {
return rad.getReadReplaceMode();
}
// READ+REPLACE mode is if addRemoveAttributeCapability is NOT present
return objectClassDefinition.getEffectiveCapability(AddRemoveAttributeValuesCapabilityType.class, ctx.getResource()) == null;
}
private RefinedAttributeDefinition getRefinedAttributeDefinitionIfApplicable(Operation operation, RefinedObjectClassDefinition objectClassDefinition) {
if (operation instanceof PropertyModificationOperation) {
PropertyDelta propertyDelta = ((PropertyModificationOperation) operation).getPropertyDelta();
if (isAttributeDelta(propertyDelta)) {
QName attributeName = propertyDelta.getElementName();
return objectClassDefinition.findAttributeDefinition(attributeName);
}
}
return null;
}
/**
* Converts ADD/DELETE VALUE operations into REPLACE VALUE, if needed
*/
private Collection<Operation> convertToReplace(ProvisioningContext ctx, Collection<Operation> operations, PrismObject<ShadowType> currentShadow) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException {
List<Operation> retval = new ArrayList<>(operations.size());
for (Operation operation : operations) {
if (operation instanceof PropertyModificationOperation) {
PropertyDelta propertyDelta = ((PropertyModificationOperation) operation).getPropertyDelta();
if (isAttributeDelta(propertyDelta)) {
QName attributeName = propertyDelta.getElementName();
RefinedAttributeDefinition rad = ctx.getObjectClassDefinition().findAttributeDefinition(attributeName);
if (isReadReplaceMode(ctx, rad, ctx.getObjectClassDefinition()) && (propertyDelta.isAdd() || propertyDelta.isDelete())) {
PropertyModificationOperation newOp = convertToReplace(propertyDelta, currentShadow, rad.getMatchingRuleQName());
newOp.setMatchingRuleQName(((PropertyModificationOperation) operation).getMatchingRuleQName());
retval.add(newOp);
continue;
}
}
}
retval.add(operation); // for yet-unprocessed operations
}
return retval;
}
private PropertyModificationOperation convertToReplace(PropertyDelta<?> propertyDelta, PrismObject<ShadowType> currentShadow, QName matchingRuleQName) throws SchemaException {
if (propertyDelta.isReplace()) {
// this was probably checked before
throw new IllegalStateException("PropertyDelta is both ADD/DELETE and REPLACE");
}
Collection<PrismPropertyValue> currentValues = new ArrayList<>();
if (currentShadow != null) {
// let's extract (parent-less) current values
PrismProperty<?> currentProperty = currentShadow.findProperty(propertyDelta.getPath());
if (currentProperty != null) {
for (PrismPropertyValue currentValue : currentProperty.getValues()) {
currentValues.add(currentValue.clone());
}
}
}
final MatchingRule matchingRule;
if (matchingRuleQName != null) {
ItemDefinition def = propertyDelta.getDefinition();
QName typeName;
if (def != null) {
typeName = def.getTypeName();
} else {
typeName = null; // we'll skip testing rule fitness w.r.t type
}
matchingRule = matchingRuleRegistry.getMatchingRule(matchingRuleQName, typeName);
} else {
matchingRule = null;
}
Comparator comparator = (Comparator<PrismPropertyValue<?>>) (o1, o2) -> {
//noinspection unchecked
if (o1.equals(o2, EquivalenceStrategy.IGNORE_METADATA, matchingRule)) {
return 0;
} else {
return 1;
}
};
// add values that have to be added
if (propertyDelta.isAdd()) {
for (PrismPropertyValue valueToAdd : propertyDelta.getValuesToAdd()) {
if (!PrismValueCollectionsUtil.containsValue(currentValues, valueToAdd, comparator)) {
currentValues.add(valueToAdd.clone());
} else {
LOGGER.warn("Attempting to add a value of {} that is already present in {}: {}",
valueToAdd, propertyDelta.getElementName(), currentValues);
}
}
}