/
MidpointFunctionsImpl.java
2607 lines (2303 loc) · 120 KB
/
MidpointFunctionsImpl.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-2023 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.expr;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static com.evolveum.midpoint.prism.delta.ObjectDelta.isAdd;
import static com.evolveum.midpoint.schema.GetOperationOptions.createNoFetchCollection;
import static com.evolveum.midpoint.schema.GetOperationOptions.createReadOnlyCollection;
import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD;
import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE;
import static com.evolveum.midpoint.schema.util.ObjectTypeUtil.asObjectable;
import static com.evolveum.midpoint.schema.util.ObjectTypeUtil.createObjectRef;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskExecutionStateType.RUNNABLE;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serial;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import com.evolveum.midpoint.model.api.*;
import com.evolveum.midpoint.common.AvailableLocale;
import com.evolveum.midpoint.schema.processor.*;
import com.evolveum.midpoint.schema.query.PreparedQuery;
import com.evolveum.midpoint.schema.query.TypedQuery;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.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.LocalizationService;
import com.evolveum.midpoint.model.api.context.*;
import com.evolveum.midpoint.model.api.expr.MidpointFunctions;
import com.evolveum.midpoint.model.api.expr.OptimizingTriggerCreator;
import com.evolveum.midpoint.model.common.ConstantsManager;
import com.evolveum.midpoint.model.common.archetypes.ArchetypeManager;
import com.evolveum.midpoint.model.common.expression.ModelExpressionThreadLocalHolder;
import com.evolveum.midpoint.model.common.expression.script.ScriptExpressionEvaluationContext;
import com.evolveum.midpoint.model.impl.ModelBeans;
import com.evolveum.midpoint.model.impl.ModelObjectResolver;
import com.evolveum.midpoint.model.impl.correlation.CorrelationCaseManager;
import com.evolveum.midpoint.model.impl.correlation.CorrelationServiceImpl;
import com.evolveum.midpoint.model.impl.expr.triggerSetter.OptimizingTriggerCreatorImpl;
import com.evolveum.midpoint.model.impl.expr.triggerSetter.TriggerCreatorGlobalState;
import com.evolveum.midpoint.model.impl.lens.LensContext;
import com.evolveum.midpoint.model.impl.lens.LensFocusContext;
import com.evolveum.midpoint.model.impl.lens.LensProjectionContext;
import com.evolveum.midpoint.model.impl.lens.projector.loader.ContextLoader;
import com.evolveum.midpoint.model.impl.trigger.RecomputeTriggerHandler;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.delta.builder.S_ItemEntry;
import com.evolveum.midpoint.prism.path.ItemName;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.repo.common.SystemObjectCache;
import com.evolveum.midpoint.repo.common.expression.ExpressionEnvironmentThreadLocalHolder;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.messaging.MessageWrapper;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.*;
import com.evolveum.midpoint.security.api.HttpConnectionInformation;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.SecurityContextManager;
import com.evolveum.midpoint.security.api.SecurityUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.*;
import com.evolveum.midpoint.util.annotation.Experimental;
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.CredentialsCapabilityType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PasswordCapabilityType;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
* @author semancik
*/
@SuppressWarnings("unused")
@Component
public class MidpointFunctionsImpl implements MidpointFunctions {
private static final Trace LOGGER = TraceManager.getTrace(MidpointFunctionsImpl.class);
public static final String CLASS_DOT = MidpointFunctions.class.getName() + ".";
private static final String OP_FIND_CANDIDATE_OWNERS = CLASS_DOT + "findCandidateOwners";
@Autowired private PrismContext prismContext;
@Autowired private RelationRegistry relationRegistry;
@Autowired private ModelService modelService;
@Autowired private ModelInteractionService modelInteractionService;
@Autowired private ModelObjectResolver modelObjectResolver;
@Autowired private ProvisioningService provisioningService;
@Autowired private SecurityContextManager securityContextManager;
@Autowired private Protector protector;
@Autowired private OrgStructFunctionsImpl orgStructFunctions;
@Autowired private LinkedObjectsFunctions linkedObjectsFunctions;
@Autowired private CaseService caseService;
@Autowired private ConstantsManager constantsManager;
@Autowired private LocalizationService localizationService;
@Autowired private ExpressionFactory expressionFactory;
@Autowired private ModelBeans beans;
@Autowired private ArchetypeManager archetypeManager;
@Autowired private TriggerCreatorGlobalState triggerCreatorGlobalState;
@Autowired private TaskManager taskManager;
@Autowired private SchemaService schemaService;
@Autowired private CorrelationCaseManager correlationCaseManager;
@Autowired private CorrelationServiceImpl correlationService;
@Autowired private SystemObjectCache systemObjectCache;
@Autowired private ContextLoader contextLoader;
@Autowired
@Qualifier("cacheRepositoryService")
private RepositoryService repositoryService;
public String hello(String name) {
return "Hello " + name;
}
@Override
public PrismContext getPrismContext() {
return prismContext;
}
@Override
public RelationRegistry getRelationRegistry() {
return relationRegistry;
}
@Override
public List<String> toList(String... s) {
return Arrays.asList(s);
}
@Override
public UserType getUserByOid(String oid) throws ObjectNotFoundException, SchemaException {
return repositoryService.getObject(UserType.class, oid, null, new OperationResult("getUserByOid")).asObjectable();
}
@Override
public boolean isMemberOf(UserType user, String orgOid) {
for (ObjectReferenceType objectReferenceType : user.getParentOrgRef()) {
if (orgOid.equals(objectReferenceType.getOid())) {
return true;
}
}
return false;
}
@Override
public String getPlaintextUserPassword(FocusType user) throws EncryptionException {
if (user == null || user.getCredentials() == null || user.getCredentials().getPassword() == null) {
return null; // todo log a warning here?
}
ProtectedStringType protectedStringType = user.getCredentials().getPassword().getValue();
if (protectedStringType != null) {
return protector.decryptString(protectedStringType);
} else {
return null;
}
}
@Override
public String getPlaintextAccountPassword(ShadowType account) throws EncryptionException {
if (account == null || account.getCredentials() == null || account.getCredentials().getPassword() == null) {
return null; // todo log a warning here?
}
ProtectedStringType protectedStringType = account.getCredentials().getPassword().getValue();
if (protectedStringType != null) {
return protector.decryptString(protectedStringType);
} else {
return null;
}
}
@Override
public String getPlaintextAccountPasswordFromDelta(ObjectDelta<? extends ShadowType> delta) throws EncryptionException {
if (delta.isAdd()) {
ShadowType newShadow = delta.getObjectToAdd().asObjectable();
return getPlaintextAccountPassword(newShadow);
}
if (!delta.isModify()) {
return null;
}
List<ProtectedStringType> passwords = new ArrayList<>();
for (ItemDelta<?, ?> itemDelta : delta.getModifications()) {
takePasswordsFromItemDelta(passwords, itemDelta);
}
LOGGER.trace("Found " + passwords.size() + " password change value(s)");
if (!passwords.isEmpty()) {
return protector.decryptString(passwords.get(passwords.size() - 1));
} else {
return null;
}
}
@SuppressWarnings("rawtypes")
private void takePasswordsFromItemDelta(List<ProtectedStringType> passwords, ItemDelta itemDelta) {
if (itemDelta.isDelete()) {
return;
}
if (itemDelta.getPath().equivalent(PATH_CREDENTIALS_PASSWORD_VALUE)) {
LOGGER.trace("Found password value add/modify delta");
//noinspection unchecked
Collection<PrismPropertyValue<ProtectedStringType>> values = itemDelta.isAdd() ?
itemDelta.getValuesToAdd() :
itemDelta.getValuesToReplace();
for (PrismPropertyValue<ProtectedStringType> value : values) {
passwords.add(value.getValue());
}
} else if (itemDelta.getPath().equivalent(PATH_CREDENTIALS_PASSWORD)) {
LOGGER.trace("Found password add/modify delta");
//noinspection unchecked
Collection<PrismContainerValue<PasswordType>> values = itemDelta.isAdd() ?
itemDelta.getValuesToAdd() :
itemDelta.getValuesToReplace();
for (PrismContainerValue<PasswordType> value : values) {
if (value.asContainerable().getValue() != null) {
passwords.add(value.asContainerable().getValue());
}
}
} else if (itemDelta.getPath().equivalent(ShadowType.F_CREDENTIALS)) {
LOGGER.trace("Found credentials add/modify delta");
//noinspection unchecked
Collection<PrismContainerValue<CredentialsType>> values = itemDelta.isAdd() ?
itemDelta.getValuesToAdd() :
itemDelta.getValuesToReplace();
for (PrismContainerValue<CredentialsType> value : values) {
if (value.asContainerable().getPassword() != null && value.asContainerable().getPassword().getValue() != null) {
passwords.add(value.asContainerable().getPassword().getValue());
}
}
}
}
@Override
public String getPlaintextUserPasswordFromDeltas(List<ObjectDelta<? extends FocusType>> objectDeltas) throws EncryptionException {
List<ProtectedStringType> passwords = new ArrayList<>();
for (ObjectDelta<? extends FocusType> delta : objectDeltas) {
if (delta.isAdd()) {
FocusType newObject = delta.getObjectToAdd().asObjectable();
return getPlaintextUserPassword(newObject); // for simplicity we do not look for other values
}
if (!delta.isModify()) {
continue;
}
for (ItemDelta<?, ?> itemDelta : delta.getModifications()) {
takePasswordsFromItemDelta(passwords, itemDelta);
}
}
LOGGER.trace("Found " + passwords.size() + " password change value(s)");
if (!passwords.isEmpty()) {
return protector.decryptString(passwords.get(passwords.size() - 1));
} else {
return null;
}
}
@Override
public <F extends ObjectType> boolean hasLinkedAccount(String resourceOid) {
ModelContext<?> ctx = ModelExpressionThreadLocalHolder.getLensContextRequired();
ProjectionContextFilter filter =
new ProjectionContextFilter(resourceOid, ShadowKindType.ACCOUNT, null);
for (ModelProjectionContext projectionContext : ctx.findProjectionContexts(filter)) {
LOGGER.trace("hasLinkedAccount: considering a projection context {} for {}", projectionContext, filter);
if (isProjectionConsideredLinked(projectionContext)) {
return true;
}
}
return isThereDeletedAccountContextForEvaluateOld(ctx, resourceOid);
}
private boolean isThereDeletedAccountContextForEvaluateOld(ModelContext<?> ctx, String resourceOid) {
ScriptExpressionEvaluationContext scriptContext = ScriptExpressionEvaluationContext.getThreadLocal();
if (scriptContext == null || scriptContext.isEvaluateNew()) {
return false; // Deleted context counts only if we are evaluating the old state
}
for (ProjectionContextKey deletedOne : ctx.getHistoricResourceObjects()) {
if (resourceOid.equals(deletedOne.getResourceOid()) && deletedOne.getKind() == ShadowKindType.ACCOUNT) {
LOGGER.trace("Found deleted one: {}", deletedOne);
return true;
}
}
return false;
}
private boolean isProjectionConsideredLinked(
ModelProjectionContext projectionContext) {
if (projectionContext.isGone()) {
return false;
}
ModelElementContext<?> focusContext = projectionContext.getModelContext().getFocusContextRequired();
ScriptExpressionEvaluationContext scriptContext = ScriptExpressionEvaluationContext.getThreadLocal();
SynchronizationPolicyDecision synchronizationPolicyDecision = projectionContext.getSynchronizationPolicyDecision();
SynchronizationIntent synchronizationIntent = projectionContext.getSynchronizationIntent();
if (scriptContext == null) {
if (synchronizationPolicyDecision == null) {
return synchronizationIntent != SynchronizationIntent.DELETE && synchronizationIntent != SynchronizationIntent.UNLINK;
} else {
return synchronizationPolicyDecision != SynchronizationPolicyDecision.DELETE && synchronizationPolicyDecision != SynchronizationPolicyDecision.UNLINK;
}
} else if (scriptContext.isEvaluateNew()) {
// Evaluating new state
if (focusContext.isDelete()) {
return false;
}
if (synchronizationPolicyDecision == null) {
return synchronizationIntent != SynchronizationIntent.DELETE && synchronizationIntent != SynchronizationIntent.UNLINK;
} else {
return synchronizationPolicyDecision != SynchronizationPolicyDecision.DELETE && synchronizationPolicyDecision != SynchronizationPolicyDecision.UNLINK;
}
} else {
// Evaluating old state
if (focusContext.isAdd()) {
return false;
}
if (synchronizationPolicyDecision == null) {
return synchronizationIntent != SynchronizationIntent.ADD;
} else {
return synchronizationPolicyDecision != SynchronizationPolicyDecision.ADD;
}
}
}
@Override
public boolean isCurrentProjectionBeingEnabled() {
return isProjectionActivationChanged(true);
}
@Override
public boolean isCurrentProjectionBeingDisabled() {
return isProjectionActivationChanged(false);
}
private boolean isProjectionActivationChanged(boolean newState) {
return isProjectionActivationChanged(ModelExpressionThreadLocalHolder.getProjectionContextRequired(), newState);
}
private boolean isProjectionActivationChanged(ModelProjectionContext projectionContext, boolean newState) {
// Shadows are not re-loaded after delta application, hence "object current" is as good as "object old".
// We do not use object old, because the newly-loaded full object is not stored there.
ShadowType objectCurrent = asObjectable(projectionContext.getObjectCurrent());
if (objectCurrent == null) {
LOGGER.trace("Considering admin status changed (to '{}') for {}: no current object", newState, projectionContext);
return false;
}
ShadowType objectNew = asObjectable(projectionContext.getObjectNew());
if (objectNew == null) {
LOGGER.trace("Considering admin status changed (to '{}') for {}: no new object", newState, projectionContext);
return false;
}
ActivationStatusType statusNew = getAdministrativeStatus(objectNew);
if (statusNew == null) {
LOGGER.trace("Considering admin status changed (to '{}') for {}: No new value for admin status, probably we"
+ "don't have full shadow (and there is no change) or the activation is not supported at all",
newState, projectionContext);
return false;
}
boolean enabledNew = statusNew == ActivationStatusType.ENABLED;
ActivationStatusType statusCurrent = getAdministrativeStatus(objectCurrent);
if (statusCurrent == null) {
LOGGER.trace("Considering admin status changed (to '{}') for {}: No current value for admin status, probably we"
+ "don't have full shadow. But there is new value ({}) so there must be the delta",
newState, projectionContext, statusNew);
return enabledNew == newState;
}
boolean enabledCurrent = statusCurrent == ActivationStatusType.ENABLED;
boolean matches = enabledNew == newState && enabledCurrent != newState;
LOGGER.trace("Considering admin status changed (to '{}') for {}: Current value: {}, new value: {}, matches: {}",
newState, projectionContext, statusCurrent, statusNew, matches);
return matches;
}
private static @Nullable ActivationStatusType getAdministrativeStatus(ShadowType shadow) {
ActivationType activationNew = shadow.getActivation();
return activationNew != null ? activationNew.getAdministrativeStatus() : null;
}
@Override
public boolean isCurrentProjectionActivated()
throws SchemaException, ExpressionEvaluationException, CommunicationException, SecurityViolationException,
ConfigurationException, ObjectNotFoundException {
boolean wasActive = wasCurrentProjectionActive();
boolean willBeActive = willCurrentProjectionBeActive();
LOGGER.trace("isCurrentProjectionActivated: wasActive = {}, willBeActive = {}", wasActive, willBeActive);
return !wasActive && willBeActive;
}
@Override
public boolean isCurrentProjectionDeactivated()
throws SchemaException, ExpressionEvaluationException, CommunicationException, SecurityViolationException,
ConfigurationException, ObjectNotFoundException {
boolean wasActive = wasCurrentProjectionActive();
boolean willBeActive = willCurrentProjectionBeActive();
LOGGER.trace("isCurrentProjectionDeactivated: wasActive = {}, willBeActive = {}", wasActive, willBeActive);
return wasActive && !willBeActive;
}
private boolean wasCurrentProjectionActive()
throws SchemaException, ExpressionEvaluationException, CommunicationException, SecurityViolationException,
ConfigurationException, ObjectNotFoundException {
LensProjectionContext projCtx = getCurrentProjectionContextRequired();
if (projCtx.isAdministrativeStatusSupported()) {
ensureActivationInformationAvailable(projCtx);
ShadowType objectCurrent = asObjectable(projCtx.getObjectCurrent());
return objectCurrent != null && isShadowEnabled(objectCurrent);
} else {
// No need to load the shadow, as the administrative status is not relevant here
return projCtx.getObjectCurrent() != null;
}
}
private boolean willCurrentProjectionBeActive()
throws SchemaException, ExpressionEvaluationException, CommunicationException, SecurityViolationException,
ConfigurationException, ObjectNotFoundException {
// "objectNew" is not a good indicator here - we have to look at sync decision instead
LensProjectionContext projCtx = getCurrentProjectionContextRequired();
if (projCtx.isAdministrativeStatusSupported()) {
ensureActivationInformationAvailable(projCtx);
ShadowType objectNew = asObjectable(projCtx.getObjectNew());
return objectNew != null && !projCtx.isDelete() && isShadowEnabled(objectNew);
} else {
// No need to load the shadow, as the administrative status is not relevant here
return projCtx.getObjectNew() != null && !projCtx.isDelete();
}
}
private static boolean isShadowEnabled(@NotNull ShadowType shadow) {
ActivationStatusType status = getAdministrativeStatus(shadow);
return status == null || status == ActivationStatusType.ENABLED;
}
private void ensureActivationInformationAvailable(LensProjectionContext projCtx)
throws SchemaException, ExpressionEvaluationException, CommunicationException, SecurityViolationException,
ConfigurationException, ObjectNotFoundException {
if (!projCtx.isFullShadow()) {
LOGGER.trace("Will load full shadow in order to determine the activation status: {}", projCtx);
contextLoader.loadFullShadowNoDiscovery(
projCtx, "projection activation determination", getCurrentTaskRequired(), getCurrentResult());
}
}
private @NotNull LensProjectionContext getCurrentProjectionContextRequired() {
return (LensProjectionContext) ModelExpressionThreadLocalHolder.getProjectionContextRequired();
}
@Override
public boolean isFocusActivated() {
boolean wasActive = wasFocusActive();
boolean willBeActive = willFocusBeActive();
LOGGER.trace("isFocusActivated: wasActive = {}, willBeActive = {}", wasActive, willBeActive);
return !wasActive && willBeActive;
}
@Override
public boolean isFocusDeactivated() {
boolean wasActive = wasFocusActive();
boolean willBeActive = willFocusBeActive();
LOGGER.trace("isFocusDeactivated: wasActive = {}, willBeActive = {}", wasActive, willBeActive);
return wasActive && !willBeActive;
}
private boolean wasFocusActive() {
return isEffectivelyEnabled(
asObjectable(
getFocusContextRequired().getObjectOld()));
}
private boolean willFocusBeActive() {
return isEffectivelyEnabled(
asObjectable(
getFocusContextRequired().getObjectNew()));
}
@NotNull
private static <O extends ObjectType> LensFocusContext<O> getFocusContextRequired() {
//noinspection unchecked
return (LensFocusContext<O>) ModelExpressionThreadLocalHolder.getLensContextRequired().getFocusContextRequired();
}
@Override
public <F extends FocusType> boolean isDirectlyAssigned(F focus, String targetOid) {
for (AssignmentType assignment : focus.getAssignment()) {
ObjectReferenceType targetRef = assignment.getTargetRef();
if (targetRef != null && targetRef.getOid().equals(targetOid)) {
return true;
}
}
return false;
}
@Override
public <F extends FocusType> boolean isDirectlyAssigned(F focusType, ObjectType target) {
return isDirectlyAssigned(focusType, target.getOid());
}
@Override
public boolean isDirectlyAssigned(String targetOid) {
ModelContext<?> ctx = ModelExpressionThreadLocalHolder.getLensContextRequired();
ModelElementContext<?> focusContext = ctx.getFocusContextRequired();
PrismObject<?> focus;
ScriptExpressionEvaluationContext scriptContext = ScriptExpressionEvaluationContext.getThreadLocal();
if (scriptContext == null) {
focus = focusContext.getObjectAny();
} else if (scriptContext.isEvaluateNew()) {
// Evaluating new state
if (focusContext.isDelete()) {
return false;
}
focus = focusContext.getObjectNew();
} else {
// Evaluating old state
if (focusContext.isAdd()) {
return false;
}
focus = focusContext.getObjectOld();
}
var focusBean = asObjectable(focus);
return focusBean instanceof FocusType focusTypedBean
&& isDirectlyAssigned(focusTypedBean, targetOid);
}
@Override
public boolean isDirectlyAssigned(ObjectType target) {
return isDirectlyAssigned(target.getOid());
}
// EXPERIMENTAL!!
@SuppressWarnings("unused")
@Experimental
public boolean hasActiveAssignmentTargetSubtype(String roleSubtype) {
ModelContext<?> lensContext = ModelExpressionThreadLocalHolder.getLensContextRequired();
DeltaSetTriple<? extends EvaluatedAssignment> evaluatedAssignmentTriple = lensContext.getEvaluatedAssignmentTriple();
if (evaluatedAssignmentTriple == null) {
throw new UnsupportedOperationException("hasActiveAssignmentRoleSubtype works only with evaluatedAssignmentTriple");
}
Collection<? extends EvaluatedAssignment> nonNegativeEvaluatedAssignments = evaluatedAssignmentTriple.getNonNegativeValues(); // MID-6403
for (EvaluatedAssignment nonNegativeEvaluatedAssignment : nonNegativeEvaluatedAssignments) {
PrismObject<?> target = nonNegativeEvaluatedAssignment.getTarget();
if (target == null) {
continue;
}
//noinspection unchecked,rawtypes
Collection<String> targetSubtypes = FocusTypeUtil.determineSubTypes((PrismObject) target);
if (targetSubtypes.contains(roleSubtype)) {
return true;
}
}
return false;
}
@Override
public @NotNull List<ShadowType> getLinkedShadows(FocusType focus, String resourceOid, boolean repositoryObjectOnly)
throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
if (focus == null) {
return emptyList();
}
List<ShadowType> shadows = new ArrayList<>();
List<ObjectReferenceType> linkRefs = focus.getLinkRef();
for (ObjectReferenceType linkRef : linkRefs) {
ShadowType shadow;
try {
shadow = getObject(ShadowType.class, linkRef.getOid(),
SelectorOptions.createCollection(GetOperationOptions.createNoFetch()));
} catch (ObjectNotFoundException e) {
// Shadow is gone in the meantime. MidPoint will resolve that by itself.
// It is safe to ignore this error in this method.
LOGGER.trace("Ignoring shadow {} linked in {} because it no longer exists in repository",
linkRef.getOid(), focus);
continue;
}
if (shadow.getResourceRef().getOid().equals(resourceOid)) {
// We have repo shadow here. Re-read resource shadow if necessary.
if (!repositoryObjectOnly) {
try {
shadow = getObject(ShadowType.class, shadow.getOid());
} catch (ObjectNotFoundException e) {
// Shadow is gone in the meantime. MidPoint will resolve that by itself.
// It is safe to ignore this error in this method.
LOGGER.trace("Ignoring shadow {} linked in {} because it no longer exists on the resource",
linkRef.getOid(), focus);
continue;
}
}
shadows.add(shadow);
}
}
return shadows;
}
@Override
public ShadowType getLinkedShadow(
FocusType focus, String resourceOid, ShadowKindType kind, String intent, boolean repositoryObjectOnly)
throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
List<ObjectReferenceType> linkRefs = focus.getLinkRef();
for (ObjectReferenceType linkRef : linkRefs) {
ShadowType shadow;
try {
shadow = getObject(ShadowType.class, linkRef.getOid(), createNoFetchCollection());
} catch (ObjectNotFoundException e) {
// Shadow is gone in the meantime. MidPoint will resolve that by itself.
// It is safe to ignore this error in this method.
LOGGER.trace("Ignoring shadow {} linked in {} because it no longer exists in repository",
linkRef.getOid(), focus);
continue;
}
if (ShadowUtil.matches(shadow, resourceOid, kind, intent)) {
// We have repo shadow here. Re-read resource shadow if necessary.
if (repositoryObjectOnly) {
return shadow;
} else {
try {
return getObject(ShadowType.class, shadow.getOid());
} catch (ObjectNotFoundException e) {
// Shadow is gone in the meantime. MidPoint will resolve that by itself.
// It is safe to ignore this error in this method.
LOGGER.trace("Ignoring shadow {} linked in {} because it no longer exists on resource",
linkRef.getOid(), focus);
}
}
}
}
return null;
}
@Override
public boolean isFullShadow() {
ModelProjectionContext projectionContext = getProjectionContext();
if (projectionContext == null) {
LOGGER.debug("Call to isFullShadow while there is no projection context");
return false;
}
return projectionContext.isFullShadow();
}
@Override
public boolean isProjectionExists() {
ModelProjectionContext projectionContext = getProjectionContext();
if (projectionContext == null) {
return false;
}
return projectionContext.isExists();
}
@Override
public <T> Integer countAccounts(String resourceOid, QName attributeName, T attributeValue)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = getCurrentResult(CLASS_DOT + "countAccounts");
// Intentionally ignoring authorizations, as we are not interested in the resource as such.
ResourceType resource = modelObjectResolver.getObjectSimple(ResourceType.class, resourceOid, null, null, result);
return countAccounts(resource, attributeName, attributeValue, getCurrentTask(), result);
}
@Override
public <T> Integer countAccounts(ResourceType resourceType, QName attributeName, T attributeValue)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = getCurrentResult(MidpointFunctions.class.getName() + "countAccounts");
return countAccounts(resourceType, attributeName, attributeValue, getCurrentTask(), result);
}
@Override
public <T> Integer countAccounts(ResourceType resourceType, String attributeName, T attributeValue)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
OperationResult result = getCurrentResult(MidpointFunctions.class.getName() + "countAccounts");
QName attributeQName = getRiAttributeQName(attributeName);
return countAccounts(resourceType, attributeQName, attributeValue, getCurrentTask(), result);
}
@NotNull
private QName getRiAttributeQName(String attributeName) {
return new QName(MidPointConstants.NS_RI, attributeName);
}
private <T> Integer countAccounts(
ResourceType resource, QName attributeName, T attributeValue, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
ObjectQuery query = createAttributeQuery(resource, attributeName, attributeValue);
return modelService.countObjects(ShadowType.class, query, null, task, result);
}
@Override
public <T> boolean isUniquePropertyValue(ObjectType objectType, String propertyPathString, T propertyValue)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
Validate.notEmpty(propertyPathString, "Empty property path");
OperationResult result = getCurrentResult(MidpointFunctions.class.getName() + "isUniquePropertyValue");
ItemPath propertyPath = prismContext.itemPathParser().asItemPath(propertyPathString);
return isUniquePropertyValue(objectType, propertyPath, propertyValue, getCurrentTask(), result);
}
private <T> boolean isUniquePropertyValue(
ObjectType object, ItemPath propertyPath, T propertyValue, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
List<? extends ObjectType> conflictingObjects = getObjectsInConflictOnPropertyValue(
object, propertyPath, propertyValue, null, false, task, result);
return conflictingObjects.isEmpty();
}
@Override
public <O extends ObjectType, T> List<O> getObjectsInConflictOnPropertyValue(
O object, String propertyPathString, T propertyValue, boolean getAllConflicting)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
return getObjectsInConflictOnPropertyValue(object, propertyPathString, propertyValue,
PrismConstants.DEFAULT_MATCHING_RULE_NAME.getLocalPart(), getAllConflicting);
}
private <O extends ObjectType, T> List<O> getObjectsInConflictOnPropertyValue(
O object, String propertyPathString, T propertyValue, String matchingRuleName, boolean getAllConflicting)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
Validate.notEmpty(propertyPathString, "Empty property path");
OperationResult result = getCurrentResult(MidpointFunctions.class.getName() + "getObjectsInConflictOnPropertyValue");
ItemPath propertyPath = prismContext.itemPathParser().asItemPath(propertyPathString);
QName matchingRuleQName = new QName(matchingRuleName); // no namespace for now
return getObjectsInConflictOnPropertyValue(object, propertyPath, propertyValue, matchingRuleQName, getAllConflicting,
getCurrentTask(), result);
}
private <O extends ObjectType, T> List<O> getObjectsInConflictOnPropertyValue(
@NotNull O object,
@NotNull ItemPath propertyPath,
@NotNull T propertyValue,
QName matchingRule,
boolean getAllConflicting,
Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
Validate.notNull(propertyPath, "Null property path");
Validate.notNull(propertyValue, "Null property value"); // we must check this explicitly
PrismPropertyDefinition<T> propertyDefinition =
object.asPrismObject().getDefinition().findPropertyDefinition(propertyPath);
if (matchingRule == null) {
if (propertyDefinition != null && PolyStringType.COMPLEX_TYPE.equals(propertyDefinition.getTypeName())) {
matchingRule = PrismConstants.POLY_STRING_ORIG_MATCHING_RULE_NAME;
} else {
matchingRule = PrismConstants.DEFAULT_MATCHING_RULE_NAME;
}
}
ObjectQuery query = prismContext.queryFor(object.getClass())
.item(propertyPath, propertyDefinition).eq(propertyValue).matching(matchingRule)
.build();
LOGGER.trace("Determining uniqueness of property {} using query:\n{}", propertyPath, query.debugDumpLazily());
final List<O> conflictingObjects = new ArrayList<>();
ResultHandler<O> handler = (foundObject, lResult) -> {
if (object.getOid() != null && object.getOid().equals(foundObject.getOid())) {
// We have found ourselves. No conflict (yet). Just go on.
return true;
} else {
// We have found someone else. Conflict.
conflictingObjects.add(foundObject.asObjectable());
return getAllConflicting;
}
};
//noinspection unchecked
modelService.searchObjectsIterative((Class<O>) object.getClass(), query, handler, null, task, result);
LOGGER.trace("Found {} conflicting objects", conflictingObjects.size());
return conflictingObjects;
}
@Override
public <T> boolean isUniqueAccountValue(
ResourceType resource, ShadowType shadow, String attributeName, T attributeValue)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
Validate.notEmpty(attributeName, "Empty attribute name");
OperationResult result = getCurrentResult(MidpointFunctions.class.getName() + "isUniqueAccountValue");
QName attributeQName = getRiAttributeQName(attributeName);
return isUniqueAccountValue(resource, shadow, attributeQName, attributeValue, getCurrentTask(), result);
}
private <T> boolean isUniqueAccountValue(
ResourceType resource, ShadowType shadow, QName attributeName, T attributeValue,
Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
Validate.notNull(resource, "Null resource");
Validate.notNull(shadow, "Null shadow");
Validate.notNull(attributeName, "Null attribute name");
Validate.notNull(attributeValue, "Null attribute value");
ObjectQuery query = createAttributeQuery(resource, attributeName, attributeValue);
LOGGER.trace("Determining uniqueness of attribute {} using query:\n{}", attributeName, query.debugDumpLazily());
final Holder<Boolean> isUniqueHolder = new Holder<>(true);
ResultHandler<ShadowType> handler = (object, parentResult) -> {
if (shadow.getOid() != null && shadow.getOid().equals(object.getOid())) {
// We have found ourselves. No conflict (yet). Just go on.
return true;
} else {
// We have found someone else. Conflict.
isUniqueHolder.setValue(false);
return false;
}
};
modelService.searchObjectsIterative(ShadowType.class, query, handler, createReadOnlyCollection(), task, result);
return isUniqueHolder.getValue();
}
private <T> ObjectQuery createAttributeQuery(ResourceType resourceType, QName attributeName, T attributeValue)
throws SchemaException, ConfigurationException {
ResourceSchema rSchema = ResourceSchemaFactory.getCompleteSchema(resourceType);
ResourceObjectDefinition rAccountDef = rSchema.findDefaultDefinitionForKindRequired(ShadowKindType.ACCOUNT);
ResourceAttributeDefinition<?> attrDef = rAccountDef.findAttributeDefinition(attributeName);
if (attrDef == null) {
throw new SchemaException("No attribute '" + attributeName + "' in " + rAccountDef);
}
return prismContext.queryFor(ShadowType.class)
.itemWithDef(attrDef, ShadowType.F_ATTRIBUTES, attrDef.getItemName()).eq(attributeValue)
.and().item(ShadowType.F_OBJECT_CLASS).eq(rAccountDef.getObjectClassName())
.and().item(ShadowType.F_RESOURCE_REF).ref(resourceType.getOid())
.build();
}
@Override
public <F extends ObjectType> ModelContext<F> getModelContext() {
//noinspection unchecked
return (ModelContext<F>) ModelExpressionThreadLocalHolder.getLensContext();
}
@Override
public <F extends ObjectType> ModelElementContext<F> getFocusContext() {
var lensContext = ModelExpressionThreadLocalHolder.getLensContext();
if (lensContext == null) {
return null;
}
//noinspection unchecked
return (ModelElementContext<F>) lensContext.getFocusContext();
}
@Override
public ModelProjectionContext getProjectionContext() {
return ModelExpressionThreadLocalHolder.getProjectionContext();
}
@Override
public <V extends PrismValue, D extends ItemDefinition<?>> Mapping<V, D> getMapping() {
return ModelExpressionThreadLocalHolder.getMapping();
}
@Override
public Task getCurrentTask() {
Task fromModelHolder = ExpressionEnvironmentThreadLocalHolder.getCurrentTask();
if (fromModelHolder != null) {
return fromModelHolder;
}
// fallback (MID-4130): but maybe we should instead make sure ModelExpressionThreadLocalHolder is set up correctly
ScriptExpressionEvaluationContext ctx = ScriptExpressionEvaluationContext.getThreadLocal();
if (ctx != null) {
return ctx.getTask();
}
return null;
}
public @NotNull Task getCurrentTaskRequired() {
return MiscUtil.requireNonNull(getCurrentTask(), () -> new IllegalStateException("no current task"));
}
@Override
public OperationResult getCurrentResult() {
// This is the most current operation result, reflecting e.g. the fact that mapping evaluation was started.
ScriptExpressionEvaluationContext ctx = ScriptExpressionEvaluationContext.getThreadLocal();
if (ctx != null) {
return ctx.getResult();
} else {
// This is a bit older. But better than nothing.
return ExpressionEnvironmentThreadLocalHolder.getCurrentResult();
}
}
@Override
public OperationResult getCurrentResult(String operationName) {
OperationResult currentResult = getCurrentResult();
if (currentResult != null) {
return currentResult;
} else {
LOGGER.warn("No operation result for {}, creating a new one", operationName);
return new OperationResult(operationName);
}
}
// functions working with ModelContext
@Override
public ModelContext<?> unwrapModelContext(LensContextType lensContextType)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
return LensContext.fromLensContextBean(lensContextType, getCurrentTask(),
getCurrentResult(MidpointFunctions.class.getName() + "getObject"));
}
@Override
public LensContextType wrapModelContext(ModelContext<?> lensContext) throws SchemaException {
return ((LensContext<?>) lensContext).toBean();
}
// Convenience functions
@Override
public <T extends ObjectType> T createEmptyObject(Class<T> type) throws SchemaException {
PrismObjectDefinition<T> objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type);
PrismObject<T> object = objectDefinition.instantiate();
return object.asObjectable();
}
@Override
public <T extends ObjectType> T createEmptyObjectWithName(Class<T> type, String name) throws SchemaException {
T objectType = createEmptyObject(type);
objectType.setName(new PolyStringType(name));
return objectType;
}
@Override
public <T extends ObjectType> T createEmptyObjectWithName(Class<T> type, PolyString name) throws SchemaException {
T objectType = createEmptyObject(type);
objectType.setName(new PolyStringType(name));
return objectType;
}
@Override
public <T extends ObjectType> T createEmptyObjectWithName(Class<T> type, PolyStringType name) throws SchemaException {
T objectType = createEmptyObject(type);
objectType.setName(name);
return objectType;
}
// Functions accessing modelService
@Override
public <T extends ObjectType> T resolveReference(ObjectReferenceType reference)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException,
SecurityViolationException, ExpressionEvaluationException {
return resolveReferenceInternal(reference, false);