-
Notifications
You must be signed in to change notification settings - Fork 188
/
ContextLoader.java
1830 lines (1662 loc) · 97.3 KB
/
ContextLoader.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-2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.model.impl.lens.projector;
import static com.evolveum.midpoint.model.impl.lens.LensUtil.getExportType;
import static com.evolveum.midpoint.schema.internals.InternalsConfig.consistencyChecks;
import static com.evolveum.midpoint.schema.result.OperationResult.DEFAULT;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.evolveum.midpoint.model.impl.lens.projector.util.ProcessorExecution;
import com.evolveum.midpoint.model.impl.lens.projector.util.ProcessorMethod;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
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.util.*;
import com.evolveum.midpoint.util.annotation.Experimental;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_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.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.model.api.context.SynchronizationPolicyDecision;
import com.evolveum.midpoint.model.common.ArchetypeManager;
import com.evolveum.midpoint.model.common.SystemObjectCache;
import com.evolveum.midpoint.model.impl.lens.ClockworkMedic;
import com.evolveum.midpoint.model.impl.lens.LensContext;
import com.evolveum.midpoint.model.impl.lens.LensElementContext;
import com.evolveum.midpoint.model.impl.lens.LensFocusContext;
import com.evolveum.midpoint.model.impl.lens.LensObjectDeltaOperation;
import com.evolveum.midpoint.model.impl.lens.LensProjectionContext;
import com.evolveum.midpoint.model.impl.lens.LensUtil;
import com.evolveum.midpoint.model.api.context.SynchronizationIntent;
import com.evolveum.midpoint.model.impl.security.SecurityHelper;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.PolicyViolationException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* Context loader loads the missing parts of the context. The context enters the projector with just the minimum information.
* Context loader gets missing data such as accounts. It gets them from the repository or provisioning as necessary. It follows
* the account links in focus (linkRef) and focus deltas.
*
* @author Radovan Semancik
*
*/
@Component
@ProcessorExecution()
public class ContextLoader implements ProjectorProcessor {
@Autowired
@Qualifier("cacheRepositoryService")
private RepositoryService cacheRepositoryService;
@Autowired private SystemObjectCache systemObjectCache;
@Autowired private ArchetypeManager archetypeManager;
@Autowired private ProvisioningService provisioningService;
@Autowired private PrismContext prismContext;
@Autowired private SecurityHelper securityHelper;
@Autowired private ClockworkMedic medic;
@Autowired private RelationRegistry relationRegistry;
@Autowired private SchemaService schemaService;
private static final Trace LOGGER = TraceManager.getTrace(ContextLoader.class);
public static final String CLASS_DOT = ContextLoader.class.getName() + ".";
private static final String OPERATION_LOAD = CLASS_DOT + "load";
private static final String OPERATION_LOAD_PROJECTION = CLASS_DOT + "loadProjection";
@ProcessorMethod
<F extends ObjectType> void load(LensContext<F> context, String activityDescription,
@SuppressWarnings("unused") XMLGregorianCalendar now, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
context.recompute();
OperationResult result = parentResult.createMinorSubresult(OPERATION_LOAD);
ProjectorComponentTraceType trace;
if (result.isTracingAny(ProjectorComponentTraceType.class)) {
trace = new ProjectorComponentTraceType(prismContext);
if (result.isTracingNormal(ProjectorComponentTraceType.class)) {
trace.setInputLensContextText(context.debugDump());
}
trace.setInputLensContext(context.toLensContextType(getExportType(trace, result)));
result.addTrace(trace);
} else {
trace = null;
}
try {
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
preprocessProjectionContext(context, projectionContext, task, result);
}
context.checkConsistenceIfNeeded();
determineFocusContext(context, task, result);
LensFocusContext<F> focusContext = context.getFocusContext();
if (focusContext != null) {
context.recomputeFocus();
loadFromSystemConfig(context, task, result);
if (FocusType.class.isAssignableFrom(context.getFocusClass())) {
// this also removes the accountRef deltas
//noinspection unchecked
loadLinkRefs((LensContext<? extends FocusType>)context, task, result);
LOGGER.trace("loadLinkRefs done");
}
// Some cleanup
ObjectDelta<F> primaryDelta = focusContext.getPrimaryDelta();
if (ObjectDelta.isModify(primaryDelta) && primaryDelta.isEmpty()) {
focusContext.setPrimaryDelta(null);
}
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
if (projectionContext.getSynchronizationIntent() != null) {
// Accounts with explicitly set intent are never rotten. These are explicitly requested actions
// if they fail then they really should fail.
projectionContext.setFresh(true);
}
}
setPrimaryDeltaOldValue(focusContext);
} else {
// Projection contexts are not rotten in this case. There is no focus so there is no way to refresh them.
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
projectionContext.setFresh(true);
}
}
removeRottenContexts(context);
context.checkConsistenceIfNeeded();
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
context.checkAbortRequested();
// TODO: not perfect. Practically, we want loadProjection operation to contain all the projection
// results. But for that we would need code restructure.
OperationResult projectionResult = result.createMinorSubresult(OPERATION_LOAD_PROJECTION);
try {
finishLoadOfProjectionContext(context, projectionContext, task, projectionResult);
} catch (Throwable e) {
projectionResult.recordFatalError(e);
throw e;
} finally {
projectionResult.computeStatusIfUnknown();
}
}
context.checkConsistenceIfNeeded();
context.recompute();
if (consistencyChecks) {
fullCheckConsistence(context);
}
// Set the "fresh" mark now so following consistency check will be stricter
context.setFresh(true);
context.checkConsistenceIfNeeded();
medic.traceContext(LOGGER, activityDescription, "after load", false, context, false);
result.computeStatusComposite();
} catch (Throwable e) {
result.recordFatalError(e);
throw e;
} finally {
if (trace != null) {
if (result.isTracingNormal(ProjectorComponentTraceType.class)) {
trace.setOutputLensContextText(context.debugDump());
}
trace.setOutputLensContext(context.toLensContextType(getExportType(trace, result)));
}
}
}
/**
* Removes projection contexts that are not fresh.
* These are usually artifacts left after the context reload. E.g. an account that used to be linked to a user before
* but was removed in the meantime.
*/
private <F extends ObjectType> void removeRottenContexts(LensContext<F> context) {
Iterator<LensProjectionContext> projectionIterator = context.getProjectionContextsIterator();
while (projectionIterator.hasNext()) {
LensProjectionContext projectionContext = projectionIterator.next();
if (projectionContext.getPrimaryDelta() != null && !projectionContext.getPrimaryDelta().isEmpty()) {
// We must never remove contexts with primary delta. Even though it fails later on.
// What the user wishes should be done (or at least attempted) regardless of the consequences.
// Vox populi vox dei
continue;
}
if (projectionContext.getWave() >= context.getExecutionWave()) {
// We must not remove context from this and later execution waves. These haven't had the
// chance to be executed yet
continue;
}
if (projectionContext.isHigherOrder()) {
// HACK never rot higher-order context. TODO: check if lower-order context is rotten, the also rot this one
continue;
}
if (!projectionContext.isFresh()) {
LOGGER.trace("Removing rotten context {}", projectionContext.getHumanReadableName());
if (projectionContext.isToBeArchived()) {
context.getHistoricResourceObjects().add(projectionContext.getResourceShadowDiscriminator());
}
List<LensObjectDeltaOperation<ShadowType>> executedDeltas = projectionContext.getExecutedDeltas();
context.getRottenExecutedDeltas().addAll(executedDeltas);
projectionIterator.remove();
}
}
}
/**
* Make sure that the projection context is loaded as appropriate.
*/
<F extends ObjectType> void makeSureProjectionIsLoaded(LensContext<F> context,
LensProjectionContext projectionContext, Task task, OperationResult result) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException,
ExpressionEvaluationException {
preprocessProjectionContext(context, projectionContext, task, result);
finishLoadOfProjectionContext(context, projectionContext, task, result);
}
/**
* Make sure that the context is OK and consistent. It means that is has a resource, it has correctly processed
* discriminator, etc.
*/
private <F extends ObjectType> void preprocessProjectionContext(LensContext<F> context,
LensProjectionContext projectionContext, Task task, OperationResult result)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
if (!ShadowType.class.isAssignableFrom(projectionContext.getObjectTypeClass())) {
return;
}
String resourceOid = null;
boolean isThombstone = false;
ShadowKindType kind = ShadowKindType.ACCOUNT;
String intent = null;
String tag = null;
int order = 0;
ResourceShadowDiscriminator rsd = projectionContext.getResourceShadowDiscriminator();
if (rsd != null) {
resourceOid = rsd.getResourceOid();
isThombstone = rsd.isTombstone();
kind = rsd.getKind();
intent = rsd.getIntent();
tag = rsd.getTag();
order = rsd.getOrder();
}
if (resourceOid == null && projectionContext.getObjectCurrent() != null) {
resourceOid = ShadowUtil.getResourceOid(projectionContext.getObjectCurrent().asObjectable());
}
if (resourceOid == null && projectionContext.getObjectNew() != null) {
resourceOid = ShadowUtil.getResourceOid(projectionContext.getObjectNew().asObjectable());
}
// We still may not have resource OID here. E.g. in case of the delete when the account is not loaded yet. It is
// perhaps safe to skip this. It will be sorted out later.
if (resourceOid != null) {
if (intent == null && projectionContext.getObjectNew() != null) {
ShadowType shadowNewType = projectionContext.getObjectNew().asObjectable();
kind = ShadowUtil.getKind(shadowNewType);
intent = ShadowUtil.getIntent(shadowNewType);
tag = shadowNewType.getTag();
}
ResourceType resource = projectionContext.getResource();
if (resource == null) {
resource = LensUtil.getResourceReadOnly(context, resourceOid, provisioningService, task, result);
projectionContext.setResource(resource);
}
String refinedIntent = LensUtil.refineProjectionIntent(kind, intent, resource, prismContext);
rsd = new ResourceShadowDiscriminator(resourceOid, kind, refinedIntent, tag, isThombstone);
rsd.setOrder(order);
projectionContext.setResourceShadowDiscriminator(rsd);
}
if (projectionContext.getOid() == null && rsd != null && rsd.getOrder() != 0) {
// Try to determine OID from lower-order contexts
for (LensProjectionContext aProjCtx: context.getProjectionContexts()) {
ResourceShadowDiscriminator aDiscr = aProjCtx.getResourceShadowDiscriminator();
if (rsd.equivalent(aDiscr) && aProjCtx.getOid() != null) {
projectionContext.setOid(aProjCtx.getOid());
break;
}
}
}
}
/**
* try to load focus context from oid, delta, projections (e.g. by determining account owners)
*/
public <O extends ObjectType> void determineFocusContext(LensContext<O> context, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = parentResult.subresult(CLASS_DOT + "determineFocusContext")
.setMinor()
.build();
FocusLoadedTraceType trace;
if (result.isTracingAny(FocusLoadedTraceType.class)) {
trace = new FocusLoadedTraceType(prismContext);
if (result.isTracingNormal(FocusLoadedTraceType.class)) {
trace.setInputLensContextText(context.debugDump());
}
trace.setInputLensContext(context.toLensContextType(getExportType(trace, result)));
result.addTrace(trace);
} else {
trace = null;
}
try {
LensFocusContext<O> focusContext;
if (context.getFocusContext() != null) {
focusContext = context.getFocusContext();
} else {
focusContext = determineFocusContextFromProjections(context, result);
}
if (focusContext == null) {
result.addReturnComment("Nothing to load");
return;
}
// Make sure that we RELOAD the focus object if the context is not fresh
// the focus may have changed in the meantime
if (focusContext.getObjectCurrent() != null && focusContext.isFresh()) {
result.addReturnComment("Already loaded");
return;
}
ObjectDelta<O> objectDelta = focusContext.getSummaryDelta(); // TODO check this
if (ObjectDelta.isAdd(objectDelta) && focusContext.getExecutedDeltas().isEmpty()) {
//we're adding the focal object. No need to load it, it is in the delta
focusContext.setFresh(true);
result.addReturnComment("Obtained from delta");
return;
}
if (focusContext.getObjectCurrent() != null && ObjectDelta.isDelete(objectDelta)) {
// do not reload if the delta is delete. the reload will most likely fail anyway
// but DO NOT set the fresh flag in this case, it may be misleading
result.addReturnComment("Not loading as delta is DELETE");
return;
}
String focusOid = focusContext.getOid();
if (StringUtils.isBlank(focusOid)) {
throw new IllegalArgumentException("No OID in primary focus delta");
}
PrismObject<O> object;
if (ObjectTypes.isClassManagedByProvisioning(focusContext.getObjectTypeClass())) {
object = provisioningService.getObject(focusContext.getObjectTypeClass(), focusOid,
SelectorOptions.createCollection(GetOperationOptions.createNoFetch()), task, result);
setLoadedFocusInTrace(object, trace);
result.addReturnComment("Loaded via provisioning");
} else {
// Always load a complete object here, including the not-returned-by-default properties.
// This is temporary measure to make sure that the mappings will have all they need.
// See MID-2635
Collection<SelectorOptions<GetOperationOptions>> options =
SelectorOptions.createCollection(GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
object = cacheRepositoryService.getObject(focusContext.getObjectTypeClass(), focusOid, options, result);
setLoadedFocusInTrace(object, trace);
result.addReturnComment("Loaded from repository");
}
focusContext.setLoadedObject(object);
focusContext.setFresh(true);
LOGGER.trace("Focal object loaded: {}", object);
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
if (trace != null) {
if (result.isTracingNormal(FocusLoadedTraceType.class)) {
trace.setOutputLensContextText(context.debugDump());
}
trace.setOutputLensContext(context.toLensContextType(getExportType(trace, result)));
}
result.computeStatusIfUnknown();
}
}
private <O extends ObjectType> void setLoadedFocusInTrace(PrismObject<O> object, FocusLoadedTraceType trace) {
if (trace != null) {
trace.setFocusLoadedRef(ObjectTypeUtil.createObjectRefWithFullObject(object, prismContext));
}
}
private <O extends ObjectType> LensFocusContext<O> determineFocusContextFromProjections(LensContext<O> context, OperationResult result) {
String focusOid = null;
LensProjectionContext projectionContextThatYieldedFocusOid = null;
PrismObject<O> focusOwner = null;
for (LensProjectionContext projectionContext: context.getProjectionContexts()) {
String projectionOid = projectionContext.getOid();
if (projectionOid != null) {
PrismObject<? extends FocusType> shadowOwner = cacheRepositoryService.searchShadowOwner(projectionOid,
SelectorOptions.createCollection(GetOperationOptions.createAllowNotFound()),
result);
if (shadowOwner != null) {
if (focusOid == null || focusOid.equals(shadowOwner.getOid())) {
focusOid = shadowOwner.getOid();
//noinspection unchecked
focusOwner = (PrismObject<O>) shadowOwner;
projectionContextThatYieldedFocusOid = projectionContext;
} else {
throw new IllegalArgumentException("The context does not have explicit focus. Attempt to determine focus failed because two " +
"projections points to different foci: "+projectionContextThatYieldedFocusOid+"->"+focusOid+"; "+
projectionContext+"->"+shadowOwner);
}
}
}
}
if (focusOid != null) {
LensFocusContext<O> focusCtx = context.getOrCreateFocusContext(focusOwner.getCompileTimeClass());
focusCtx.setOid(focusOid);
return focusCtx;
} else {
return null;
}
}
private <O extends ObjectType> void setPrimaryDeltaOldValue(LensElementContext<O> ctx) {
if (ctx.getPrimaryDelta() != null && ctx.getObjectOld() != null && ctx.isModify()) {
boolean freezeAfterChange;
if (ctx.getPrimaryDelta().isImmutable()) {
ctx.setPrimaryDelta(ctx.getPrimaryDelta().clone());
freezeAfterChange = true;
} else {
freezeAfterChange = false;
}
for (ItemDelta<?,?> itemDelta: ctx.getPrimaryDelta().getModifications()) {
LensUtil.setDeltaOldValue(ctx, itemDelta);
}
if (freezeAfterChange) {
ctx.getPrimaryDelta().freeze();
}
}
}
private <F extends ObjectType> void loadFromSystemConfig(LensContext<F> context, Task task, OperationResult result)
throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException {
PrismObject<SystemConfigurationType> systemConfiguration = updateSystemConfigurationInContext(context, result);
if (systemConfiguration == null) {
// This happens in some tests. And also during first startup.
return;
}
SystemConfigurationType systemConfigurationType = systemConfiguration.asObjectable();
if (context.getFocusContext() != null) {
if (context.getFocusContext().getArchetypePolicyType() == null) {
ArchetypePolicyType archetypePolicy = determineArchetypePolicy(context, task, result);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Selected archetype policy:\n{}",
archetypePolicy==null?null:archetypePolicy.asPrismContainerValue().debugDump(1));
}
context.getFocusContext().setArchetypePolicyType(archetypePolicy);
}
}
if (context.getFocusTemplate() == null) {
// TODO is the nullity check needed here?
updateFocusTemplate(context, result);
}
if (context.getAccountSynchronizationSettings() == null) {
ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.getGlobalAccountSynchronizationSettings();
LOGGER.trace("Applying globalAccountSynchronizationSettings to context: {}", globalAccountSynchronizationSettings);
context.setAccountSynchronizationSettings(globalAccountSynchronizationSettings);
}
loadSecurityPolicy(context, task, result);
}
// TODO find a better home for this method
@Nullable
public <F extends ObjectType> PrismObject<SystemConfigurationType> updateSystemConfigurationInContext(LensContext<F> context,
OperationResult result) throws SchemaException {
PrismObject<SystemConfigurationType> systemConfiguration = systemObjectCache.getSystemConfiguration(result);
if (systemConfiguration != null) {
context.setSystemConfiguration(systemConfiguration);
}
return systemConfiguration;
}
private <F extends ObjectType> ArchetypePolicyType determineArchetypePolicy(LensContext<F> context, Task task, OperationResult result) throws SchemaException, ConfigurationException {
if (!canProcessArchetype(context)) {
return null;
}
PrismObject<F> object = context.getFocusContext().getObjectAny();
String explicitArchetypeOid = LensUtil.determineExplicitArchetypeOid(object);
return archetypeManager.determineArchetypePolicy(object, explicitArchetypeOid, result);
}
private <O extends ObjectType> boolean canProcessArchetype(LensContext<O> context) {
PrismObject<SystemConfigurationType> systemConfiguration = context.getSystemConfiguration();
if (systemConfiguration == null) {
return false;
}
if (context.getFocusContext() == null) {
return false;
}
return true;
}
public <F extends AssignmentHolderType> void updateArchetype(LensContext<F> context, Task task, OperationResult result) throws SchemaException, ConfigurationException {
if (!canProcessArchetype(context)) {
return;
}
PrismObject<F> object = context.getFocusContext().getObjectAny();
String explicitArchetypeOid = LensUtil.determineExplicitArchetypeOid(object);
PrismObject<ArchetypeType> archetype = archetypeManager.determineArchetype(object, explicitArchetypeOid, result);
if (archetype == null) {
return;
}
context.getFocusContext().setArchetype(archetype.asObjectable());
}
public <F extends ObjectType> void updateArchetypePolicy(LensContext<F> context, Task task, OperationResult result) throws SchemaException, ConfigurationException {
if (context.getFocusContext() == null) {
return;
}
ArchetypePolicyType newArchetypePolicy = determineArchetypePolicy(context, task, result);
if (newArchetypePolicy != context.getFocusContext().getArchetypePolicyType()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Changed policy configuration because of changed subtypes:\n{}",
newArchetypePolicy==null?null:newArchetypePolicy.asPrismContainerValue().debugDump(1));
}
context.getFocusContext().setArchetypePolicyType(newArchetypePolicy);
}
}
// expects that object policy configuration is already set in focusContext
public <F extends ObjectType> void updateFocusTemplate(LensContext<F> context, OperationResult result)
throws ObjectNotFoundException, SchemaException {
// 1. When this method is called after inbound processing, we might want to change the existing template
// (because e.g. subtype or archetype was determined and we want to move from generic to more specific template).
// 2. On the other hand, if focus template is set up explicitly from the outside (e.g. in synchronization section)
// we probably do not want to change it here.
if (context.getFocusTemplate() != null && context.isFocusTemplateExternallySet()) {
return;
}
String currentOid = context.getFocusTemplate() != null ? context.getFocusTemplate().getOid() : null;
String newOid;
LensFocusContext<F> focusContext = context.getFocusContext();
if (focusContext == null) {
newOid = null;
} else {
ArchetypePolicyType archetypePolicy = focusContext.getArchetypePolicyType();
if (archetypePolicy == null) {
LOGGER.trace("No default object template (no policy)");
newOid = null;
} else {
ObjectReferenceType templateRef = archetypePolicy.getObjectTemplateRef();
if (templateRef == null) {
LOGGER.trace("No default object template (no templateRef)");
newOid = null;
} else {
newOid = templateRef.getOid();
}
}
}
LOGGER.trace("current focus template OID = {}, new = {}", currentOid, newOid);
if (!java.util.Objects.equals(currentOid, newOid)) {
ObjectTemplateType template;
if (newOid != null) {
template = cacheRepositoryService.getObject(ObjectTemplateType.class, newOid, null, result).asObjectable();
} else {
template = null;
}
context.setFocusTemplate(template);
}
}
private <F extends FocusType> void loadLinkRefs(LensContext<F> context, Task task, OperationResult result)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
LOGGER.trace("loadLinkRefs starting");
LensFocusContext<F> focusContext = context.getFocusContext();
PrismObject<F> focusCurrent = focusContext.getObjectCurrent();
if (focusCurrent != null) {
loadLinkRefsFromFocus(context, focusCurrent, task, result);
LOGGER.trace("loadLinkRefsFromFocus done");
}
context.checkConsistenceIfNeeded();
loadLinkRefsFromDelta(context, focusCurrent, focusContext, task, result);
LOGGER.trace("loadLinkRefsFromDelta done");
context.checkConsistenceIfNeeded();
loadProjectionContextsSync(context, task, result);
LOGGER.trace("loadProjectionContextsSync done");
context.checkConsistenceIfNeeded();
}
/**
* Does not overwrite existing account contexts, just adds new ones.
*/
private <F extends FocusType> void loadLinkRefsFromFocus(LensContext<F> context, PrismObject<F> focus,
Task task, OperationResult result) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
PrismReference linkRef = focus.findReference(FocusType.F_LINK_REF);
if (linkRef == null) {
return;
}
for (PrismReferenceValue linkRefVal : linkRef.getValues()) {
String oid = linkRefVal.getOid();
if (!relationRegistry.isMember(linkRefVal.getRelation())) {
LOGGER.trace("Inactive linkRef: will only refresh it, no processing. Relation={}, ref={}",
linkRefVal.getRelation(), linkRefVal);
refreshInactiveLinkedShadow(oid, context, task, result);
continue;
}
if (StringUtils.isBlank(oid)) {
LOGGER.trace("Null or empty OID in link reference {} in:\n{}", linkRef,
focus.debugDump(1));
throw new SchemaException("Null or empty OID in link reference in " + focus);
}
LensProjectionContext existingAccountContext = findAccountContext(oid, context);
if (existingAccountContext != null) {
// TODO: do we need to reload the account inside here? yes we need
existingAccountContext.setFresh(true);
continue;
}
PrismObject<ShadowType> shadow;
//noinspection unchecked
PrismObject<ShadowType> shadowFromLink = linkRefVal.getObject();
if (shadowFromLink == null) {
var options = createStandardGetOptions();
LOGGER.trace("Loading shadow {} from linkRef, options={}", oid, options);
try {
shadow = provisioningService.getObject(ShadowType.class, oid, options, task, result);
} catch (ObjectNotFoundException e) {
// Broken accountRef. We need to mark it for deletion
LensProjectionContext projectionContext = getOrCreateEmptyThombstoneProjectionContext(context, oid);
projectionContext.setFresh(true);
projectionContext.setExists(false);
projectionContext.setShadowExistsInRepo(false);
OperationResult getObjectSubresult = result.getLastSubresult();
getObjectSubresult.setErrorsHandled();
continue;
}
} else {
shadow = shadowFromLink;
// Make sure it has a proper definition. This may come from outside of the model.
provisioningService.applyDefinition(shadow, task, result);
}
ContextAcquisitionResult acqResult = getOrCreateAccountContext(context, shadow, task, result);
LensProjectionContext projectionContext = acqResult.context;
if (acqResult.shadowSet) {
projectionContext.setFresh(projectionContext.getObjectOld() != null); // TODO reconsider
} else {
projectionContext.setFresh(true);
projectionContext.setExists(ShadowUtil.isExists(shadow.asObjectable()));
if (ShadowUtil.isDead(shadow.asObjectable())) {
projectionContext.markTombstone();
LOGGER.trace("Loading dead shadow {} for projection {}.", shadow, projectionContext.getHumanReadableName());
continue;
}
if (projectionContext.isDoReconciliation()) {
// Do not load old account now. It will get loaded later in the reconciliation step.
continue;
}
projectionContext.setLoadedObject(shadow);
}
}
}
private <F extends FocusType> Collection<SelectorOptions<GetOperationOptions>> createStandardGetOptions() {
// Using NO_FETCH so we avoid reading in a full account. This is more efficient as we don't need full account here.
// We need to fetch from provisioning and not repository so the correct definition will be set.
return schemaService.getOperationOptionsBuilder()
.noFetch()
.pointInTime(PointInTimeType.FUTURE)
.build();
}
/**
* We do this just to restore old behavior that ensures that linked shadows are quick-refreshed,
* deleting e.g. expired pending operations (see TestMultiResource.test429).
*/
private void refreshInactiveLinkedShadow(String oid, LensContext<?> context, Task task, OperationResult result) {
Collection<SelectorOptions<GetOperationOptions>> options;
if (context.isDoReconciliationForAllProjections()) {
// Ensures an attempt to complete any pending operations.
// TODO Shouldn't we include FUTURE option as well? E.g. to avoid failing on not-yet-created accounts?
// (Fortunately, we ignore any exceptions but anyway: FUTURE is used in other cases in this class.)
options = schemaService.getOperationOptionsBuilder()
.forceRetry()
.build();
} else {
// This ensures only minimal processing, e.g. the quick shadow refresh is done.
options = schemaService.getOperationOptionsBuilder()
.noFetch()
.pointInTime(PointInTimeType.FUTURE)
.build();
}
try {
provisioningService.getObject(ShadowType.class, oid, options, task, result);
} catch (Exception e) {
result.muteLastSubresultError();
LOGGER.debug("Couldn't refresh linked shadow {}. Continuing.", oid, e);
}
}
private <F extends FocusType> void loadLinkRefsFromDelta(LensContext<F> context, PrismObject<F> focus,
LensFocusContext<F> focusContext, Task task, OperationResult result) throws SchemaException,
ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, PolicyViolationException, ExpressionEvaluationException {
ObjectDelta<F> focusPrimaryDelta = focusContext.getPrimaryDelta();
if (focusPrimaryDelta == null) {
return;
}
ReferenceDelta linkRefDelta;
if (focusPrimaryDelta.getChangeType() == ChangeType.ADD) {
PrismReference linkRef = focusPrimaryDelta.getObjectToAdd().findReference(FocusType.F_LINK_REF);
if (linkRef == null) {
// Adding new focus with no linkRef -> nothing to do
return;
}
linkRefDelta = linkRef.createDelta(FocusType.F_LINK_REF);
linkRefDelta.addValuesToAdd(PrismValueCollectionsUtil.cloneValues(linkRef.getValues()));
} else if (focusPrimaryDelta.getChangeType() == ChangeType.MODIFY) {
linkRefDelta = focusPrimaryDelta.findReferenceModification(FocusType.F_LINK_REF);
if (linkRefDelta == null) {
return;
}
} else {
// delete, all existing account are already marked for delete
return;
}
if (linkRefDelta.isReplace()) {
// process "replace" by distributing values to delete and add
linkRefDelta = linkRefDelta.clone();
PrismReference linkRef = focus.findReference(FocusType.F_LINK_REF);
linkRefDelta.distributeReplace(linkRef == null ? null : linkRef.getValues());
}
if (linkRefDelta.getValuesToAdd() != null) {
for (PrismReferenceValue refVal : linkRefDelta.getValuesToAdd()) {
if (!relationRegistry.isMember(refVal.getRelation())) {
LOGGER.trace("loadLinkRefsFromDelta: Skipping inactive linkRef to add (relation={}): {}",
refVal.getRelation(), refVal);
continue;
}
LOGGER.trace("loadLinkRefsFromDelta: Processing value to add: {}", refVal);
String oid = refVal.getOid();
LensProjectionContext projectionContext;
PrismObject<ShadowType> shadow;
boolean isCombinedAdd = false;
if (oid == null) {
// Adding new account
//noinspection unchecked
shadow = refVal.getObject();
if (shadow == null) {
throw new SchemaException("Null or empty OID in account reference " + refVal + " in " + focus);
}
provisioningService.applyDefinition(shadow, task, result);
if (consistencyChecks) ShadowUtil.checkConsistence(shadow, "account from "+linkRefDelta);
// Check for conflicting change
projectionContext = LensUtil.getProjectionContext(context, shadow, provisioningService, prismContext, task, result);
if (projectionContext != null) {
// There is already existing context for the same discriminator. Tolerate this only if
// the deltas match. It is an error otherwise.
ObjectDelta<ShadowType> primaryDelta = projectionContext.getPrimaryDelta();
if (primaryDelta == null) {
throw new SchemaException("Attempt to add "+shadow+" to a focus that already contains "+
projectionContext.getHumanReadableKind()+" of type '"+
projectionContext.getResourceShadowDiscriminator().getIntent()+"' on "+projectionContext.getResource());
}
if (!primaryDelta.isAdd()) {
throw new SchemaException("Conflicting changes in the context. " +
"Add of linkRef in the focus delta with embedded object conflicts with explicit delta "+primaryDelta);
}
if (!shadow.equals(primaryDelta.getObjectToAdd())) {
throw new SchemaException("Conflicting changes in the context. " +
"Add of linkRef in the focus delta with embedded object is not adding the same object as explicit delta "+primaryDelta);
}
} else {
// Create account context from embedded object
projectionContext = createProjectionContext(context, shadow, task, result);
}
// This is a new account that is to be added. So it should
// go to account primary delta
ObjectDelta<ShadowType> accountPrimaryDelta = shadow.createAddDelta();
projectionContext.setPrimaryDelta(accountPrimaryDelta);
projectionContext.setFullShadow(true);
projectionContext.setExists(false);
isCombinedAdd = true;
} else {
// We have OID. This is either linking of existing account or
// add of new account
// therefore check for account existence to decide
try {
// Using NO_FETCH so we avoid reading in a full account. This is more efficient as we don't need full account here.
// We need to fetch from provisioning and not repository so the correct definition will be set.
GetOperationOptions rootOpts = GetOperationOptions.createNoFetch();
rootOpts.setPointInTimeType(PointInTimeType.FUTURE);
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(rootOpts);
shadow = provisioningService.getObject(ShadowType.class, oid, options, task, result);
// Create account context from retrieved object
projectionContext = getOrCreateAccountContext(context, shadow, task, result).context; // TODO what about shadowSet etc?
projectionContext.setLoadedObject(shadow);
projectionContext.setExists(ShadowUtil.isExists(shadow.asObjectable()));
} catch (ObjectNotFoundException e) {
if (refVal.getObject() == null) {
// account does not exist, no composite account in
// ref -> this is really an error
throw e;
} else {
// New account (with OID)
result.muteLastSubresultError();
shadow = refVal.getObject();
if (!shadow.hasCompleteDefinition()) {
provisioningService.applyDefinition(shadow, task, result);
}
// Create account context from embedded object
projectionContext = createProjectionContext(context, shadow, task, result);
ObjectDelta<ShadowType> accountPrimaryDelta = shadow.createAddDelta();
projectionContext.setPrimaryDelta(accountPrimaryDelta);
projectionContext.setFullShadow(true);
projectionContext.setExists(false);
projectionContext.setShadowExistsInRepo(false);
isCombinedAdd = true;
}
}
}
if (context.isDoReconciliationForAllProjections() && !isCombinedAdd) {
projectionContext.setDoReconciliation(true);
}
projectionContext.setFresh(true);
}
}
if (linkRefDelta.getValuesToDelete() != null) {
for (PrismReferenceValue refVal : linkRefDelta.getValuesToDelete()) {
if (!relationRegistry.isMember(refVal.getRelation())) {
LOGGER.trace("loadLinkRefsFromDelta: Skipping inactive linkRef to delete (relation={}): {}",
refVal.getRelation(), refVal);
continue;
}
LOGGER.trace("loadLinkRefsFromDelta: Processing value to delete: {}", refVal);
String oid = refVal.getOid();
LensProjectionContext projectionContext = null;
PrismObject<ShadowType> shadow = null;
if (oid == null) {
throw new SchemaException("Cannot delete account ref without an oid in " + focus);
} else {
try {
// Using NO_FETCH so we avoid reading in a full account. This is more efficient as we don't need full account here.
// We need to fetch from provisioning and not repository so the correct definition will be set.
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch());
shadow = provisioningService.getObject(ShadowType.class, oid, options, task, result);
// Create account context from retrieved object
projectionContext = getOrCreateAccountContext(context, shadow, task, result).context; // TODO what about shadowSet etc?
projectionContext.setLoadedObject(shadow);
projectionContext.setExists(ShadowUtil.isExists(shadow.asObjectable()));
LOGGER.trace("Loaded projection context: {}", projectionContext);
} catch (ObjectNotFoundException e) {
try {
LOGGER.trace("Broken linkRef? We need to try again with raw options, because the error could be "
+ "thrown because of non-existent resource", e);
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
shadow = provisioningService.getObject(ShadowType.class, oid, options, task, result);
projectionContext = getOrCreateEmptyThombstoneProjectionContext(context, oid);
projectionContext.setFresh(true);
projectionContext.setExists(false);
projectionContext.setShadowExistsInRepo(false);
LOGGER.trace("Loaded projection context: {}", projectionContext);
OperationResult getObjectSubresult = result.getLastSubresult();
getObjectSubresult.setErrorsHandled();
} catch (ObjectNotFoundException ex) {
// This is still OK. It means deleting an accountRef
// that points to non-existing object
// just log a warning
LOGGER.warn("Deleting accountRef of " + focus + " that points to non-existing OID " + oid);
}
}
}
if (projectionContext != null) {
if (refVal.getObject() == null) {
projectionContext.setSynchronizationIntent(SynchronizationIntent.UNLINK);
} else {
// I.e. this is when we request to delete link containing full object.
projectionContext.setSynchronizationIntent(SynchronizationIntent.DELETE);
ObjectDelta<ShadowType> accountPrimaryDelta = shadow.createDeleteDelta();
projectionContext.setPrimaryDelta(accountPrimaryDelta);
}
projectionContext.setFresh(true);
}
}
}
// remove the accountRefs without oid. These will get into the way now.
// The accounts
// are in the context now and will be linked at the end of the process
// (it they survive the policy)
// We need to make sure this happens on the real primary focus delta
ObjectDelta<F> primaryDeltaToUpdate;
if (focusPrimaryDelta.isImmutable()) {
primaryDeltaToUpdate = focusPrimaryDelta.clone();
focusContext.setPrimaryDelta(primaryDeltaToUpdate);
} else {
primaryDeltaToUpdate = focusPrimaryDelta;
}
if (primaryDeltaToUpdate.getChangeType() == ChangeType.ADD) {
primaryDeltaToUpdate.getObjectToAdd().removeReference(FocusType.F_LINK_REF);
} else if (primaryDeltaToUpdate.getChangeType() == ChangeType.MODIFY) {
primaryDeltaToUpdate.removeReferenceModification(FocusType.F_LINK_REF);
}
// It is little bit questionable whether we need to make primary delta immutable. It makes some sense, but I am not sure.
// Note that (as a side effect) this can make "focus new" immutable as well, in the case of ADD delta.
primaryDeltaToUpdate.freeze();
}
private <F extends ObjectType> void loadProjectionContextsSync(LensContext<F> context, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
for (LensProjectionContext projCtx : context.getProjectionContexts()) {
if (projCtx.isFresh() && projCtx.getObjectCurrent() != null) {
// already loaded
continue;
}
ObjectDelta<ShadowType> syncDelta = projCtx.getSyncDelta();
if (syncDelta != null) {
if (projCtx.isDoReconciliation()) {
// Do not load old account now. It will get loaded later in the reconciliation step. Just mark it as fresh.
projCtx.setFresh(true);
continue;
}
String oid = syncDelta.getOid();
PrismObject<ShadowType> shadow = null;
if (syncDelta.getChangeType() == ChangeType.ADD) {
shadow = syncDelta.getObjectToAdd().clone();
projCtx.setLoadedObject(shadow);
projCtx.setExists(ShadowUtil.isExists(shadow.asObjectable()));