-
Notifications
You must be signed in to change notification settings - Fork 188
/
Mapping.java
1732 lines (1490 loc) · 53.4 KB
/
Mapping.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.model.common.mapping;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.constants.ExpressionConstants;
import com.evolveum.midpoint.security.api.SecurityEnforcer;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;
import com.evolveum.midpoint.common.filter.Filter;
import com.evolveum.midpoint.common.filter.FilterManager;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.model.common.expression.Expression;
import com.evolveum.midpoint.model.common.expression.ExpressionEvaluationContext;
import com.evolveum.midpoint.model.common.expression.ExpressionFactory;
import com.evolveum.midpoint.model.common.expression.ExpressionUtil;
import com.evolveum.midpoint.model.common.expression.ExpressionVariables;
import com.evolveum.midpoint.model.common.expression.ItemDeltaItem;
import com.evolveum.midpoint.model.common.expression.ObjectDeltaObject;
import com.evolveum.midpoint.model.common.expression.Source;
import com.evolveum.midpoint.model.common.expression.StringPolicyResolver;
import com.evolveum.midpoint.model.common.expression.ValueSetDefinition;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.NameItemPathSegment;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.TunnelException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
*
* Mapping is non-recyclable single-use object. Once evaluated it should not be evaluated again. It will retain its original
* inputs and outputs that can be read again and again. But these should not be changed after evaluation.
*
* Configuration properties are unmodifiable. They are to be set via Mapping.Builder.
*
* @author Radovan Semancik
*
*/
public class Mapping<V extends PrismValue,D extends ItemDefinition> implements DebugDumpable, PrismValueDeltaSetTripleProducer<V, D> {
// configuration properties (unmodifiable)
private final MappingType mappingType;
private final ExpressionFactory expressionFactory;
private final ExpressionVariables variables;
private final ObjectDeltaObject<?> sourceContext;
private final Collection<Source<?,?>> sources;
private final Source<?,?> defaultSource;
private final PrismObjectDefinition<?> targetContext;
private final ItemPath defaultTargetPath;
private final D defaultTargetDefinition;
private final Collection<V> originalTargetValues;
private final ObjectResolver objectResolver;
private final SecurityEnforcer securityEnforcer; // in order to get c:actor variable
private final OriginType originType;
private final ObjectType originObject;
private final FilterManager<Filter> filterManager;
private final StringPolicyResolver stringPolicyResolver;
private final boolean conditionMaskOld;
private final boolean conditionMaskNew;
private final XMLGregorianCalendar defaultReferenceTime;
private final XMLGregorianCalendar now;
private final boolean profiling;
private final String contextDescription;
private final QName mappingQName; // This is sometimes used to identify the element that mapping produces
// if it is different from itemName. E.g. this happens with associations.
private final RefinedObjectClassDefinition refinedObjectClassDefinition;
// working and output properties
private D outputDefinition;
private ItemPath outputPath;
private PrismValueDeltaSetTriple<V> outputTriple;
private PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> conditionOutputTriple;
private Boolean timeConstraintValid = null;
private XMLGregorianCalendar nextRecomputeTime = null;
private Long evaluationStartTime = null;
private Long evaluationEndTime = null;
private String mappingContextDescription = null;
// This is single-use only. Once evaluated it is not used any more
// it is remembered only for tracing purposes.
private Expression<V,D> expression;
private static final Trace LOGGER = TraceManager.getTrace(Mapping.class);
private Mapping(Builder<V,D> builder) {
expressionFactory = builder.expressionFactory;
variables = builder.variables;
mappingType = builder.mappingType;
objectResolver = builder.objectResolver;
securityEnforcer = builder.securityEnforcer;
defaultSource = builder.defaultSource;
defaultTargetDefinition = builder.defaultTargetDefinition;
defaultTargetPath = builder.defaultTargetPath;
originalTargetValues = builder.originalTargetValues;
sourceContext = builder.sourceContext;
targetContext = builder.targetContext;
sources = builder.sources;
originType = builder.originType;
originObject = builder.originObject;
filterManager = builder.filterManager;
stringPolicyResolver = builder.stringPolicyResolver;
conditionMaskOld = builder.conditionMaskOld;
conditionMaskNew = builder.conditionMaskNew;
defaultReferenceTime = builder.defaultReferenceTime;
profiling = builder.profiling;
contextDescription = builder.contextDescription;
mappingQName = builder.mappingQName;
refinedObjectClassDefinition = builder.refinedObjectClassDefinition;
now = builder.now;
}
public ObjectResolver getObjectResolver() {
return objectResolver;
}
public QName getItemName() {
if (outputDefinition != null) {
return outputDefinition.getName();
}
return null;
}
public OriginType getOriginType() {
return originType;
}
public ObjectType getOriginObject() {
return originObject;
}
public Source<?,?> getDefaultSource() {
return defaultSource;
}
public D getDefaultTargetDefinition() {
return defaultTargetDefinition;
}
public ItemPath getDefaultTargetPath() {
return defaultTargetPath;
}
public ObjectDeltaObject<?> getSourceContext() {
return sourceContext;
}
public PrismObjectDefinition<?> getTargetContext() {
return targetContext;
}
public String getContextDescription() {
return contextDescription;
}
public String getMappingContextDescription() {
if (mappingContextDescription == null) {
StringBuilder sb = new StringBuilder("mapping ");
if (mappingType.getName() != null) {
sb.append("'").append(mappingType.getName()).append("' ");
}
sb.append("in ");
sb.append(contextDescription);
mappingContextDescription = sb.toString();
}
return mappingContextDescription;
}
public MappingType getMappingType() {
return mappingType;
}
@Override
public boolean isSourceless() {
return sources.isEmpty();
}
public MappingStrengthType getStrength() {
return getStrength(mappingType);
}
public static MappingStrengthType getStrength(MappingType mappingType) {
if (mappingType == null) {
return MappingStrengthType.NORMAL;
}
MappingStrengthType value = mappingType.getStrength();
if (value == null) {
value = MappingStrengthType.NORMAL;
}
return value;
}
public boolean isAuthoritative() {
if (mappingType == null) {
return true;
}
Boolean value = mappingType.isAuthoritative();
if (value == null) {
value = true;
}
return value;
}
public boolean isExclusive() {
if (mappingType == null) {
return false;
}
Boolean value = mappingType.isExclusive();
if (value == null) {
value = false;
}
return value;
}
public Boolean isTolerant() {
if (mappingType == null) {
return null;
}
return mappingType.isTolerant();
}
public boolean isConditionMaskOld() {
return conditionMaskOld;
}
public boolean isConditionMaskNew() {
return conditionMaskNew;
}
private PrismContext getPrismContext() {
return outputDefinition.getPrismContext();
}
public FilterManager<Filter> getFilterManager() {
return filterManager;
}
public StringPolicyResolver getStringPolicyResolver() {
return stringPolicyResolver;
}
public boolean isApplicableToChannel(String channelUri) {
return isApplicableToChannel(mappingType, channelUri);
}
public static boolean isApplicableToChannel(MappingType mappingType, String channelUri) {
List<String> exceptChannel = mappingType.getExceptChannel();
if (exceptChannel != null && !exceptChannel.isEmpty()){
return !exceptChannel.contains(channelUri);
}
List<String> applicableChannels = mappingType.getChannel();
if (applicableChannels == null || applicableChannels.isEmpty()) {
return true;
}
return applicableChannels.contains(channelUri);
}
public XMLGregorianCalendar getNow() {
return now;
}
public XMLGregorianCalendar getDefaultReferenceTime() {
return defaultReferenceTime;
}
public XMLGregorianCalendar getNextRecomputeTime() {
return nextRecomputeTime;
}
public boolean isProfiling() {
return profiling;
}
public Long getEvaluationStartTime() {
return evaluationStartTime;
}
public Long getEvaluationEndTime() {
return evaluationEndTime;
}
public Long getEtime() {
if (evaluationStartTime == null || evaluationEndTime == null) {
return null;
}
return evaluationEndTime - evaluationStartTime;
}
/* (non-Javadoc)
* @see com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer#getMappingQName()
*/
@Override
public QName getMappingQName() {
return mappingQName;
}
public RefinedObjectClassDefinition getRefinedObjectClassDefinition() {
return refinedObjectClassDefinition;
}
public void evaluate(Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
OperationResult result = parentResult.createMinorSubresult(Mapping.class.getName()+".evaluate");
ExpressionUtil.addActorVariable(variables, securityEnforcer);
traceEvaluationStart();
try {
evaluateTimeConstraintValid(task, result);
if (!timeConstraintValid) {
outputTriple = null;
result.recordNotApplicableIfUnknown();
traceDeferred();
return;
}
parseSources(task, result);
parseTarget();
if (outputPath != null && outputDefinition == null) {
throw new IllegalArgumentException("No output definition, cannot evaluate "+getMappingContextDescription());
}
evaluateCondition(task, result);
boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues());
boolean conditionResultOld = conditionOutputOld && conditionMaskOld;
boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues());
boolean conditionResultNew = conditionOutputNew && conditionMaskNew;
if (conditionResultOld || conditionResultNew) {
// TODO: input filter
evaluateExpression(task, result, conditionResultOld, conditionResultNew);
fixDefinition();
recomputeValues();
setOrigin();
// TODO: output filter
checkRange(task, result);
}
result.recordSuccess();
traceSuccess(conditionResultOld, conditionResultNew);
} catch (ExpressionEvaluationException | ObjectNotFoundException | RuntimeException | SchemaException | Error e) {
result.recordFatalError(e);
traceFailure(e);
throw e;
}
}
private void checkRange(Task task, OperationResult result)
throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
VariableBindingDefinitionType target = mappingType.getTarget();
if (target != null && target.getSet() != null) {
checkRangeTarget(task, result);
}
if (mappingType.getRange() != null) {
checkRangeLegacy(task, result);
}
}
private void checkRangeTarget(Task task, OperationResult result)
throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
if (originalTargetValues == null) {
throw new IllegalStateException("Couldn't check range for mapping in " + contextDescription + ", as original target values are not known.");
}
ValueSetDefinitionType rangetSetDefType = mappingType.getTarget().getSet();
QName name = outputPath.lastNamed().getName();
ValueSetDefinition setDef = new ValueSetDefinition(rangetSetDefType, name, "range of "+name.getLocalPart()+" in "+getMappingContextDescription(), task, result);
setDef.init(expressionFactory);
for (V originalValue : originalTargetValues) {
if (!setDef.contains(originalValue)) {
continue;
}
addToMinusIfNecessary(originalValue);
}
}
private void addToMinusIfNecessary(V originalValue) {
if (outputTriple != null && (outputTriple.presentInPlusSet(originalValue) || outputTriple.presentInZeroSet(originalValue))) {
return;
}
// remove it!
if (outputTriple == null) {
outputTriple = new PrismValueDeltaSetTriple<>();
}
LOGGER.trace("Original value is in the mapping range (while not in mapping result), adding it to minus set: {}", originalValue);
outputTriple.addToMinusSet(originalValue);
}
private void checkRangeLegacy(Task task, OperationResult result)
throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
if (originalTargetValues == null) {
throw new IllegalStateException("Couldn't check range for mapping in " + contextDescription + ", as original target values are not known.");
}
for (V originalValue : originalTargetValues) {
if (!isInRange(originalValue, task, result)) {
continue;
}
addToMinusIfNecessary(originalValue);
}
}
private boolean isInRange(V value, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
@NotNull ValueSetSpecificationType range = mappingType.getRange();
if (range.getIsInSetExpression() == null) {
return false;
}
ExpressionVariables variables = new ExpressionVariables();
variables.addVariableDefinitions(this.variables); // TODO is this ok?
if (value instanceof PrismContainerValue) {
// artifically create parent for PCV in order to pass it to expression
PrismContainer.createParentIfNeeded((PrismContainerValue) value, outputDefinition);
}
variables.addVariableDefinition(ExpressionConstants.VAR_VALUE, value);
PrismPropertyDefinition<Boolean> outputDef = new PrismPropertyDefinitionImpl<Boolean>(SchemaConstantsGenerated.C_VALUE, DOMUtil.XSD_BOOLEAN, getPrismContext(), null, false);
PrismPropertyValue<Boolean> rv = ExpressionUtil.evaluateExpression(variables, outputDef, range.getIsInSetExpression(), expressionFactory, "isInSet expression in " + contextDescription, task, result);
// but now remove the parent!
if (value.getParent() != null) {
value.setParent(null);
}
return rv != null && rv.getValue() != null ? rv.getValue() : Boolean.FALSE;
}
public boolean isSatisfyCondition() {
boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues());
boolean conditionResultOld = conditionOutputOld && conditionMaskOld;
boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues());
boolean conditionResultNew = conditionOutputNew && conditionMaskNew;
return (conditionResultOld || conditionResultNew);
}
public PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> getConditionOutputTriple() {
return conditionOutputTriple;
}
private void traceEvaluationStart() {
if (profiling) {
evaluationStartTime = System.currentTimeMillis();
}
}
private void traceEvaluationEnd() {
if (profiling) {
evaluationEndTime = System.currentTimeMillis();
}
}
private void traceSuccess(boolean conditionResultOld, boolean conditionResultNew) {
traceEvaluationEnd();
if (!isTrace()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("Mapping trace:\n");
appendTraceHeader(sb);
sb.append("\nCondition: ").append(conditionResultOld).append(" -> ").append(conditionResultNew);
if (nextRecomputeTime != null) {
sb.append("\nNext recompute: ");
sb.append(nextRecomputeTime);
}
sb.append("\nResult: ");
if (outputTriple == null) {
sb.append("null");
} else {
sb.append(outputTriple.toHumanReadableString());
}
if (profiling) {
sb.append("\nEtime: ");
sb.append(getEtime());
sb.append(" ms");
}
appendTraceFooter(sb);
trace(sb.toString());
}
private void traceDeferred() {
traceEvaluationEnd();
if (!isTrace()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("Mapping trace:\n");
appendTraceHeader(sb);
sb.append("\nEvaluation DEFERRED to: ");
if (nextRecomputeTime == null) {
sb.append("null");
} else {
sb.append(nextRecomputeTime);
}
if (profiling) {
sb.append("\nEtime: ");
sb.append(getEtime());
sb.append(" ms");
}
appendTraceFooter(sb);
trace(sb.toString());
}
private void traceFailure(Throwable e) {
LOGGER.error("Error evaluating {}: {}", new Object[]{getMappingContextDescription(), e.getMessage(), e});
traceEvaluationEnd();
if (!isTrace()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("Mapping failure:\n");
appendTraceHeader(sb);
sb.append("\nERROR: ").append(e.getClass().getSimpleName()).append(": ").append(e.getMessage());
if (profiling) {
sb.append("\nEtime: ");
sb.append(getEtime());
sb.append(" ms");
}
appendTraceFooter(sb);
trace(sb.toString());
}
private boolean isTrace() {
return LOGGER.isTraceEnabled() || (mappingType != null && mappingType.isTrace() == Boolean.TRUE);
}
private void trace(String msg) {
if (mappingType != null && mappingType.isTrace() == Boolean.TRUE) {
LOGGER.info(msg);
} else {
LOGGER.trace(msg);
}
}
private void appendTraceHeader(StringBuilder sb) {
sb.append("---[ MAPPING ");
if (mappingType.getName() != null) {
sb.append("'").append(mappingType.getName()).append("' ");
}
sb.append(" in ");
sb.append(contextDescription);
sb.append("]---------------------------");
for (Source<?,?> source: sources) {
sb.append("\nSource: ");
sb.append(source.shortDebugDump());
}
sb.append("\nTarget: ").append(MiscUtil.toString(outputDefinition));
sb.append("\nExpression: ");
if (expression == null) {
sb.append("null");
} else {
sb.append(expression.shortDebugDump());
}
}
private void appendTraceFooter(StringBuilder sb) {
sb.append("\n------------------------------------------------------");
}
private boolean computeConditionResult(Collection<PrismPropertyValue<Boolean>> booleanPropertyValues) {
if (mappingType.getCondition() == null) {
// If condition is not present at all consider it to be true
return true;
}
return ExpressionUtil.computeConditionResult(booleanPropertyValues);
}
public Boolean evaluateTimeConstraintValid(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
if (timeConstraintValid == null) {
parseTimeConstraints(task, result);
}
return timeConstraintValid;
}
private void parseTimeConstraints(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
MappingTimeDeclarationType timeFromType = mappingType.getTimeFrom();
MappingTimeDeclarationType timeToType = mappingType.getTimeTo();
if (timeFromType == null && timeToType == null) {
timeConstraintValid = true;
return;
}
XMLGregorianCalendar timeFrom = parseTime(timeFromType, task, result);
if (timeFrom == null && timeFromType != null) {
// Time is specified but there is no value for it.
// This means that event that should start validity haven't happened yet
// therefore the mapping is not yet valid.
timeConstraintValid = false;
return;
}
XMLGregorianCalendar timeTo = parseTime(timeToType, task, result);
if (timeFrom != null && timeFrom.compare(now) == DatatypeConstants.GREATER) {
// before timeFrom
nextRecomputeTime = timeFrom;
timeConstraintValid = false;
return;
}
if (timeTo == null && timeToType != null) {
// Time is specified but there is no value for it.
// This means that event that should stop validity haven't happened yet
// therefore the mapping is still valid.
timeConstraintValid = true;
return;
}
if (timeTo != null && timeTo.compare(now) == DatatypeConstants.GREATER) {
// between timeFrom and timeTo (also no timeFrom and before timeTo)
nextRecomputeTime = timeTo;
timeConstraintValid = true;
return;
}
if (timeTo == null) {
// after timeFrom and no timeTo
// no nextRecomputeTime set, there is nothing to recompute in the future
timeConstraintValid = true;
return;
} else {
// after timeTo
// no nextRecomputeTime set, there is nothing to recompute in the future
timeConstraintValid = false;
return;
}
}
private XMLGregorianCalendar parseTime(MappingTimeDeclarationType timeType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
if (timeType == null) {
return null;
}
XMLGregorianCalendar time;
VariableBindingDefinitionType referenceTimeType = timeType.getReferenceTime();
if (referenceTimeType == null) {
if (defaultReferenceTime == null) {
throw new SchemaException("No reference time specified (and there is also no default) in time specification in "+getMappingContextDescription());
} else {
time = (XMLGregorianCalendar) defaultReferenceTime.clone();
}
} else {
time = parseTimeSource(referenceTimeType, task, result);
if (time == null) {
// Reference time is specified but the value is not present.
return null;
}
time = (XMLGregorianCalendar) time.clone();
}
Duration offset = timeType.getOffset();
if (offset != null) {
time.add(offset);
}
return time;
}
private XMLGregorianCalendar parseTimeSource(VariableBindingDefinitionType sourceType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
ItemPathType itemPathType = sourceType.getPath();
if (itemPathType == null) {
throw new SchemaException("No path in source definition in "+getMappingContextDescription());
}
ItemPath path = itemPathType.getItemPath();
if (path.isEmpty()) {
throw new SchemaException("Empty source path in "+getMappingContextDescription());
}
Object sourceObject = ExpressionUtil.resolvePath(path, variables, sourceContext, objectResolver, "reference time definition in "+getMappingContextDescription(), task, result);
if (sourceObject == null) {
return null;
}
PrismProperty<XMLGregorianCalendar> timeProperty;
if (sourceObject instanceof ItemDeltaItem<?,?>) {
timeProperty = (PrismProperty<XMLGregorianCalendar>) ((ItemDeltaItem<?,?>)sourceObject).getItemNew();
} else if (sourceObject instanceof Item<?,?>) {
timeProperty = (PrismProperty<XMLGregorianCalendar>) sourceObject;
} else {
throw new IllegalStateException("Unknown resolve result "+sourceObject);
}
if (timeProperty == null) {
return null;
}
return timeProperty.getRealValue();
}
private Collection<Source<?,?>> parseSources(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
List<VariableBindingDefinitionType> sourceTypes = mappingType.getSource();
if (defaultSource != null) {
defaultSource.recompute();
sources.add(defaultSource);
defaultSource.recompute();
}
if (sourceTypes != null) {
for (VariableBindingDefinitionType sourceType: sourceTypes) {
Source<?,?> source = parseSource(sourceType, task, result);
source.recompute();
// Override existing sources (e.g. default source)
Iterator<Source<?,?>> iterator = sources.iterator();
while (iterator.hasNext()) {
Source<?,?> next = iterator.next();
if (next.getName().equals(source.getName())) {
iterator.remove();
}
}
sources.add(source);
}
}
return sources;
}
private <IV extends PrismValue, ID extends ItemDefinition> Source<IV,ID> parseSource(VariableBindingDefinitionType sourceType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
ItemPathType itemPathType = sourceType.getPath();
if (itemPathType == null) {
throw new SchemaException("No path in source definition in "+getMappingContextDescription());
}
ItemPath path = itemPathType.getItemPath();
if (path.isEmpty()) {
throw new SchemaException("Empty source path in "+getMappingContextDescription());
}
QName name = sourceType.getName();
if (name == null) {
name = ItemPath.getName(path.last());
}
ItemPath resolvePath = path;
Object sourceObject = ExpressionUtil.resolvePath(path, variables, sourceContext, objectResolver, "source definition in "+getMappingContextDescription(), task, result);
Item<IV,ID> itemOld = null;
ItemDelta<IV,ID> delta = null;
Item<IV,ID> itemNew = null;
ItemPath residualPath = null;
Collection<? extends ItemDelta<?,?>> subItemDeltas = null;
if (sourceObject != null) {
if (sourceObject instanceof ItemDeltaItem<?,?>) {
itemOld = ((ItemDeltaItem<IV,ID>)sourceObject).getItemOld();
delta = ((ItemDeltaItem<IV,ID>)sourceObject).getDelta();
itemNew = ((ItemDeltaItem<IV,ID>)sourceObject).getItemNew();
residualPath = ((ItemDeltaItem<IV,ID>)sourceObject).getResidualPath();
resolvePath = ((ItemDeltaItem<IV,ID>)sourceObject).getResolvePath();
subItemDeltas = ((ItemDeltaItem<IV,ID>)sourceObject).getSubItemDeltas();
} else if (sourceObject instanceof Item<?,?>) {
itemOld = (Item<IV,ID>) sourceObject;
itemNew = (Item<IV,ID>) sourceObject;
} else {
throw new IllegalStateException("Unknown resolve result "+sourceObject);
}
}
// apply domain
ValueSetDefinitionType domainSetType = sourceType.getSet();
if (domainSetType != null) {
ValueSetDefinition setDef = new ValueSetDefinition(domainSetType, name, "domain of "+name.getLocalPart()+" in "+getMappingContextDescription(), task, result);
setDef.init(expressionFactory);
try {
if (itemOld != null) {
itemOld = itemOld.clone();
itemOld.filterValues(val -> setDef.containsTunnel(val));
}
if (itemNew != null) {
itemNew = itemNew.clone();
itemNew.filterValues(val -> setDef.containsTunnel(val));
}
if (delta != null) {
delta = delta.clone();
delta.filterValues(val -> setDef.containsTunnel(val));
}
} catch (TunnelException te) {
Throwable cause = te.getCause();
if (cause instanceof SchemaException) {
throw (SchemaException)cause;
} else if (cause instanceof ExpressionEvaluationException) {
throw (ExpressionEvaluationException)cause;
} else if (cause instanceof ObjectNotFoundException) {
throw (ObjectNotFoundException)cause;
}
}
}
Source<IV,ID> source = new Source<>(itemOld, delta, itemNew, name);
source.setResidualPath(residualPath);
source.setResolvePath(resolvePath);
source.setSubItemDeltas(subItemDeltas);
return source;
}
private void parseTarget() throws SchemaException {
VariableBindingDefinitionType targetType = mappingType.getTarget();
if (targetType == null) {
outputDefinition = defaultTargetDefinition;
outputPath = defaultTargetPath;
} else {
ItemPathType itemPathType = targetType.getPath();
if (itemPathType == null) {
outputDefinition = defaultTargetDefinition;
outputPath = defaultTargetPath;
} else {
ItemPath path = itemPathType.getItemPath();
outputDefinition = ExpressionUtil.resolveDefinitionPath(path, variables, targetContext, "target definition in "+getMappingContextDescription());
if (outputDefinition == null) {
throw new SchemaException("No target item that would conform to the path "+path+" in "+getMappingContextDescription());
}
// Make the path relative if needed
if (!path.isEmpty() && (path.first() instanceof NameItemPathSegment) &&
((NameItemPathSegment)path.first()).isVariable()) {
outputPath = path.rest();
} else {
outputPath = path;
}
}
}
if (stringPolicyResolver != null) {
stringPolicyResolver.setOutputDefinition(outputDefinition);
stringPolicyResolver.setOutputPath(outputPath);
}
}
public D getOutputDefinition() throws SchemaException {
if (outputDefinition == null) {
parseTarget();
}
return outputDefinition;
}
public ItemPath getOutputPath() throws SchemaException {
if (outputDefinition == null) {
parseTarget();
}
return outputPath;
}
/**
* Applies definition to the output if needed.
*/
private void fixDefinition() throws SchemaException {
if (outputTriple == null) {
return;
}
if (outputTriple.isRaw()) {
outputTriple.applyDefinition(outputDefinition);
}
}
private void recomputeValues() {
if (outputTriple == null) {
return;
}
Visitor visitor = new Visitor() {
@Override
public void visit(Visitable visitable) {
if (visitable instanceof PrismValue) {
((PrismValue)visitable).recompute(getPrismContext());
}
}
};
outputTriple.accept(visitor);
}
private void setOrigin() {
if (outputTriple == null) {
return;
}
if (originType != null) {
outputTriple.setOriginType(originType);
}
if (originObject != null) {
outputTriple.setOriginObject(originObject);
}
}
private void evaluateCondition(Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
ExpressionType conditionExpressionType = mappingType.getCondition();
if (conditionExpressionType == null) {
// True -> True
conditionOutputTriple = new PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>>();
conditionOutputTriple.addToZeroSet(new PrismPropertyValue<Boolean>(Boolean.TRUE));
return;
}
Expression<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> expression =
ExpressionUtil.createCondition(conditionExpressionType, expressionFactory,
"condition in "+getMappingContextDescription(), task, result);
ExpressionEvaluationContext params = new ExpressionEvaluationContext(sources, variables,
"condition in "+getMappingContextDescription(), task, result);
params.setStringPolicyResolver(stringPolicyResolver);
params.setExpressionFactory(expressionFactory);
params.setDefaultSource(defaultSource);
params.setDefaultTargetContext(getTargetContext());
params.setRefinedObjectClassDefinition(getRefinedObjectClassDefinition());
params.setMappingQName(mappingQName);
conditionOutputTriple = expression.evaluate(params);
}
private void evaluateExpression(Task task, OperationResult result, boolean conditionResultOld, boolean conditionResultNew) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
ExpressionType expressionType = null;
if (mappingType != null) {
expressionType = mappingType.getExpression();
}
expression = expressionFactory.makeExpression(expressionType, outputDefinition,
"expression in "+getMappingContextDescription(), task, result);
ExpressionEvaluationContext params = new ExpressionEvaluationContext(sources, variables,
"expression in "+getMappingContextDescription(), task, result);
params.setDefaultSource(defaultSource);
params.setSkipEvaluationMinus(!conditionResultOld);
params.setSkipEvaluationPlus(!conditionResultNew);
params.setStringPolicyResolver(stringPolicyResolver);
params.setExpressionFactory(expressionFactory);
params.setDefaultTargetContext(getTargetContext());
params.setRefinedObjectClassDefinition(getRefinedObjectClassDefinition());
params.setMappingQName(mappingQName);
outputTriple = expression.evaluate(params);
if (outputTriple == null) {
if (conditionResultNew) {
// We need to return empty triple instead of null.
// The condition was true (or there was not condition at all)
// so the mapping is applicable.
// Returning null would mean that the mapping is not applicable
// at all.
outputTriple = new PrismValueDeltaSetTriple<>();
}
} else {
// reflect condition change
if (!conditionResultOld && conditionResultNew) {
// Condition change false -> true
outputTriple.addAllToPlusSet(outputTriple.getZeroSet());
outputTriple.clearZeroSet();
outputTriple.clearMinusSet();
}
if (conditionResultOld && !conditionResultNew) {
// Condition change true -> false
outputTriple.addAllToMinusSet(outputTriple.getZeroSet());
outputTriple.clearZeroSet();
outputTriple.clearPlusSet();
}
}
}
/* (non-Javadoc)
* @see com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer#getOutputTriple()
*/