-
Notifications
You must be signed in to change notification settings - Fork 188
/
ValueTupleTransformation.java
439 lines (390 loc) · 19 KB
/
ValueTupleTransformation.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
/*
* Copyright (c) 2020 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.common.expression.evaluator.transformation;
import static java.util.Collections.emptySet;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import com.evolveum.midpoint.prism.ValueMetadata;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValueMetadataType;
import org.jetbrains.annotations.NotNull;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismValue;
import com.evolveum.midpoint.prism.delta.PlusMinusZero;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.repo.common.expression.*;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ExceptionUtil;
import com.evolveum.midpoint.schema.util.TraceUtil;
import com.evolveum.midpoint.util.MiscUtil;
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.ValueTransformationTraceType;
import com.evolveum.prism.xml.ns._public.types_3.PlusMinusZeroType;
/**
* Transformation of a value tuple (single value from each source) to a collection of output values.
* <p>
* It is is a part of combinatorial evaluation.
*
* @param <V> type of the output value
*/
class ValueTupleTransformation<V extends PrismValue> implements AutoCloseable {
private static final Trace LOGGER = TraceManager.getTrace(ValueTupleTransformation.class);
private static final String OP_EVALUATE = ValueTupleTransformation.class.getName() + ".evaluate";
/**
* The whole combinatorial evaluation.
*/
@NotNull private final CombinatorialEvaluation<V, ?, ?> combinatorialEvaluation;
/**
* (Client-supplied) context of the expression evaluation.
*/
@NotNull private final ExpressionEvaluationContext context;
/**
* List of source triples (plus-minus-zero); with some null tweaks.
*/
@NotNull private final List<SourceTriple<?, ?>> sourceTripleList;
/**
* Sets (plus/minus/zero) from which individual values were selected.
*/
@NotNull private final List<PlusMinusZero> sets;
/**
* Currently transformed value tuple - one value from every source.
*/
@NotNull private final List<PrismValue> valuesTuple;
/**
* Resulting output triple where we collect results of the whole combinatorial evaluation.
*/
@NotNull private final PrismValueDeltaSetTriple<V> outputTriple;
/**
* Operation result for this tuple evaluation (condition + transformation).
*/
@NotNull private final OperationResult result;
/**
* Trace for the tuple evaluation.
*/
private final ValueTransformationTraceType trace;
/**
* How many sources do we have?
*/
private final int numberOfSources;
/**
* What state (old, new) should be input variables taken from?
*/
private final InputVariableState inputVariableState;
/**
* To what set should the output go?
*/
private final PlusMinusZero outputSet;
/**
* Result of condition evaluation (or true if there's no condition).
* (Boolean instead of boolean to be sure that we know when it's evaluated.)
*/
private Boolean conditionResult;
/**
* Result of the transformation. Empty set if condition is false. (Null means the transformation was not carried out).
*/
private Collection<V> transformationResult;
ValueTupleTransformation(@NotNull List<PlusMinusZero> sets, List<PrismValue> valuesTuple, PlusMinusZero outputSet,
CombinatorialEvaluation<V, ?, ?> combinatorialEvaluation, OperationResult parentResult) {
this.combinatorialEvaluation = combinatorialEvaluation;
this.context = combinatorialEvaluation.context;
this.sourceTripleList = combinatorialEvaluation.sourceTripleList;
this.sets = sets;
this.valuesTuple = valuesTuple;
this.outputSet = outputSet;
this.inputVariableState = InputVariableState.forOutputSet(outputSet);
this.outputTriple = combinatorialEvaluation.outputTriple;
this.numberOfSources = sourceTripleList.size();
assert numberOfSources == valuesTuple.size();
this.result = parentResult.subresult(OP_EVALUATE)
.setMinor()
.build();
result.addParam("context", context.getContextDescription());
if (result.isTraced()) {
trace = new ValueTransformationTraceType(combinatorialEvaluation.prismContext);
result.getTraces().add(trace);
dumpValueCombinationToTrace();
} else {
trace = null;
}
}
void evaluate() {
try {
if (!combinatorialEvaluation.evaluator.isIncludeNullInputs() && MiscUtil.isAllNull(valuesTuple)) {
// The case that all the sources are null. There is no point executing the expression.
setTraceComment("All sources are null and includeNullInputs is true.");
return;
}
ExpressionVariables staticVariables = createStaticVariablesFromSources();
recordBeforeTransformation();
augmentStaticVariablesWithInputVariables(staticVariables);
evaluateConditionAndTransformation(staticVariables);
recordTransformationResult();
outputTriple.addAllToSet(outputSet, transformationResult);
} catch (Throwable t) {
result.recordFatalError(t.getMessage(), t);
throw t;
}
}
/**
* @return Final form of static (delta-less) variables derived from the sources.
* Also sets hasPlus/hasZero/hasMinus flags.
*/
@NotNull
private ExpressionVariables createStaticVariablesFromSources() {
ExpressionVariables staticVariables = new ExpressionVariables();
for (int sourceIndex = 0; sourceIndex < numberOfSources; sourceIndex++) {
// This strange casting is needed because of presentInPlusSet/MinusSet/ZeroSet calls
// that expect the same type as the SourceTriple has.
//noinspection unchecked
SourceTriple<PrismValue, ?> sourceTriple = (SourceTriple<PrismValue, ?>) sourceTripleList.get(sourceIndex);
PrismValue value = valuesTuple.get(sourceIndex);
String name = sourceTriple.getName().getLocalPart();
ItemDefinition definition = sourceTriple.getSource().getDefinition();
if (definition == null) { // TODO reconsider @NotNull annotation on getDefinition
throw new IllegalArgumentException("Source '" + name + "' without a definition");
}
staticVariables.put(name, getRealContent(value, sourceTriple.getResidualPath()), definition);
// Note: a value may be both in plus and minus sets, e.g. in case that the value is replaced
// with the same value. We pretend that this is the same as ADD case.
// TODO: Maybe we will need better handling in the future. Maybe we would need
// to execute the script twice?
// TODO: Couldn't we remember the set when constructing the union of triple values?
// We would be able to avoid searching the sets for the values here.
// if (sourceTriple.presentInPlusSet(value)) {
// hasPlus = true;
// } else if (sourceTriple.presentInZeroSet(value)) {
// hasZero = true;
// } else if (sourceTriple.presentInMinusSet(value)) {
// hasMinus = true;
// }
if (context.getVariableProducer() != null) {
//noinspection unchecked
((VariableProducer<PrismValue>) context.getVariableProducer())
.produce(value, context.getVariables());
}
}
return staticVariables;
}
private Object getRealContent(PrismValue pval, ItemPath residualPath) {
if (residualPath == null || residualPath.isEmpty()) {
return pval;
}
if (pval == null) {
return null;
}
return pval.find(residualPath);
}
private void augmentStaticVariablesWithInputVariables(ExpressionVariables staticVariables) {
if (inputVariableState == InputVariableState.NEW) {
staticVariables.addVariableDefinitionsNew(context.getVariables());
} else if (inputVariableState == InputVariableState.OLD) {
staticVariables.addVariableDefinitionsOld(context.getVariables());
} else {
throw new AssertionError();
}
}
// private boolean isApplicableRegardingPlusMinusSetPresence() {
// if (!hasPlus && !hasMinus && !hasZero && !MiscUtil.isAllNull(valuesTuple)) {
// throw new IllegalStateException("Internal error! The impossible has happened! tuple=" + valuesTuple + "; source triples: " + sourceTripleList + "; in " + context.getContextDescription());
// }
//
// if (hasPlus && hasMinus) {
// // The combination of values that are both in plus and minus. Evaluating this combination does not make sense.
// // Just skip it.
// //
// // Note: There will NOT be a single value that is in both plus and minus (e.g. "replace with itself" case).
// // That case is handled when setting hasPlus/hasMinus/hasZero in prepareStaticVariables() method.
// //
// // This case strictly applies to combination of different values from the plus and minus sets.
// setTraceComment("The combination of values that are both in plus and minus. Evaluating this combination does not make sense. Just skip it.");
// return false;
// } else if (hasPlus && context.isSkipEvaluationPlus()) {
// setTraceComment("The results will end up in the plus set and skipEvaluationPlus is true, therefore we can skip them.");
// return false;
// } else if (hasMinus && context.isSkipEvaluationMinus()) {
// setTraceComment("The results will end up in the minus set and skipEvaluationMinus is true, therefore we can skip them.");
// return false;
// } else {
// return true;
// }
// }
// private void determineInputStateAndOutputSet() {
// if (hasPlus) {
// // Pluses and zeroes: Result goes to plus set, use NEW values for variables
// // (No minus! This has been checked earlier)
// outputSet = PlusMinusZero.PLUS;
// inputVariableState = InputVariableState.NEW;
// } else if (hasMinus) {
// // Minuses and zeroes: Result goes to minus set, use OLD values for variables
// outputSet = PlusMinusZero.MINUS;
// inputVariableState = InputVariableState.OLD;
// } else {
// // All zeros: Result goes to zero set, use NEW values for variables
// outputSet = PlusMinusZero.ZERO;
// inputVariableState = InputVariableState.NEW;
// }
// }
private void evaluateConditionAndTransformation(ExpressionVariables staticVariables) {
try {
conditionResult = evaluateCondition(staticVariables);
if (conditionResult) {
transformationResult = evaluateTransformation(staticVariables);
} else {
setTraceComment("Skipping value transformation because condition evaluated to false.");
transformationResult = emptySet();
}
} catch (ExpressionEvaluationException e) {
ExpressionEvaluationException exEx = new ExpressionEvaluationException(
e.getMessage() + "(" + staticVariables.dumpSingleLine() + ") in " + context.getContextDescription(),
e,
ExceptionUtil.getUserFriendlyMessage(e));
if (combinatorialEvaluation.evaluator.localizationService != null) {
combinatorialEvaluation.evaluator.localizationService.translate(exEx);
}
throw new TunnelException(exEx);
} catch (Throwable e) {
String msg = e.getMessage() + "(" + staticVariables.dumpSingleLine() + ") in " + context.getContextDescription();
throw new TunnelException(MiscUtil.createSame(e, msg));
}
}
private boolean evaluateCondition(ExpressionVariables staticVariables)
throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException,
ConfigurationException, SecurityViolationException {
if (combinatorialEvaluation.conditionExpression != null) {
ExpressionEvaluationContext conditionCtx = new ExpressionEvaluationContext(null, staticVariables,
"condition in " + context.getContextDescription(), context.getTask());
PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> triple = combinatorialEvaluation.conditionExpression
.evaluate(conditionCtx, result);
return ExpressionUtil.computeConditionResult(triple.getNonNegativeValues());
} else {
return true;
}
}
@NotNull
private List<V> evaluateTransformation(ExpressionVariables staticVariables) throws ExpressionEvaluationException,
ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
List<V> transformationOutput = combinatorialEvaluation.evaluator.transformSingleValue(staticVariables, outputSet,
inputVariableState == InputVariableState.NEW, context,
context.getContextDescription(), context.getTask(), result);
computeAndApplyOutputValueMetadata(transformationOutput);
return transformationOutput;
}
private void computeAndApplyOutputValueMetadata(List<V> output) throws CommunicationException, ObjectNotFoundException,
SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException {
TransformationValueMetadataComputer valueMetadataComputer = context.getValueMetadataComputer();
if (valueMetadataComputer == null) {
// TODO clear existing metadata?
LOGGER.trace("No value metadata computer present, skipping metadata computation.");
} else if (outputSet == PlusMinusZero.MINUS) {
// TODO clear existing metadata?
LOGGER.trace("Transforming for minus set, skipping metadata computation.");
} else {
ValueMetadataType outputValueMetadata = valueMetadataComputer.compute(valuesTuple, result);
if (outputValueMetadata != null) {
ValueMetadata metadata = combinatorialEvaluation.prismContext.getValueMetadataFactory().createEmpty();
metadata.addMetadataValue(outputValueMetadata.asPrismContainerValue());
for (int i = 0; i < output.size(); i++) {
V oVal = output.get(i);
if (oVal != null) {
if (i < output.size() - 1) {
oVal.setValueMetadata(metadata.clone());
} else {
oVal.setValueMetadata(metadata);
}
}
}
} else {
// TODO clear existing metadata?
}
}
}
private void setTraceComment(String comment) {
LOGGER.trace("{} In {}.", comment, context.getContextDescription());
if (trace != null) {
trace.setComment(comment);
}
}
private Object dumpValueTupleLazily() {
return new Object() {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Iterator<SourceTriple<?, ?>> sourceTriplesIterator = combinatorialEvaluation.sourceTripleList.iterator();
for (PrismValue value : valuesTuple) {
SourceTriple<?, ?> sourceTriple = sourceTriplesIterator.next();
sb.append(sourceTriple.getName().getLocalPart()).append('=');
sb.append(value == null ? null : value.getRealValueOrRawType(combinatorialEvaluation.prismContext));
if (sourceTriplesIterator.hasNext()) {
sb.append(", ");
}
}
return sb.toString();
}
};
}
private void dumpValueCombinationToTrace() {
Iterator<SourceTriple<?, ?>> sourceTriplesIterator = combinatorialEvaluation.sourceTripleList.iterator();
for (PrismValue pval : valuesTuple) {
SourceTriple<?, ?> sourceTriple = sourceTriplesIterator.next();
trace.getInput().add(TraceUtil.toNamedValueType(pval, sourceTriple.getName(), combinatorialEvaluation.prismContext));
}
trace.setInputOrigin(
sets.stream()
.map(this::toChar)
.collect(Collectors.joining()));
}
private String toChar(PlusMinusZero set) {
switch (set) {
case PLUS:
return "P";
case MINUS:
return "M";
case ZERO:
return "Z";
default:
throw new AssertionError(set);
}
}
private void recordBeforeTransformation() {
LOGGER.trace("Processing value combination {} in {}\n skipEvaluationPlus={}, skipEvaluationMinus={}, outputSet={}, inputVariablesState={}",
dumpValueTupleLazily(), context.getContextDescription(),
context.isSkipEvaluationPlus(), context.isSkipEvaluationMinus(),
outputSet, inputVariableState);
if (trace != null) {
trace.setLocalContextDescription(context.getLocalContextDescription());
}
}
private void recordTransformationResult() {
LOGGER.trace("Processed value tuple {} in {}\n valueDestination: {}\n scriptResults:{}{}",
dumpValueTupleLazily(), context.getContextDescription(), outputSet, transformationResult,
conditionResult ? "" : " (condition evaluated to false)");
if (trace != null) {
trace.setDestination(PlusMinusZeroType.fromValue(outputSet));
trace.setConditionResult(conditionResult);
trace.getOutput().addAll(TraceUtil.toAnyValueTypeList(transformationResult, combinatorialEvaluation.prismContext));
}
}
@Override
public void close() {
result.computeStatusIfUnknown();
}
private enum InputVariableState {
OLD, NEW;
private static InputVariableState forOutputSet(@NotNull PlusMinusZero set) {
if (set == PlusMinusZero.MINUS) {
return OLD;
} else {
return NEW;
}
}
}
}