-
Notifications
You must be signed in to change notification settings - Fork 188
/
ExpressionUtil.java
922 lines (820 loc) · 35.4 KB
/
ExpressionUtil.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
/*
* Copyright (c) 2010-2016 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.expression;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.script.Bindings;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions;
import com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctionsXPath;
import com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary;
import com.evolveum.midpoint.model.common.expression.functions.LogExpressionFunctions;
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.ItemDelta;
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.prism.path.ItemPathSegment;
import com.evolveum.midpoint.prism.path.NameItemPathSegment;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.AllFilter;
import com.evolveum.midpoint.prism.query.ExpressionWrapper;
import com.evolveum.midpoint.prism.query.InOidFilter;
import com.evolveum.midpoint.prism.query.LogicalFilter;
import com.evolveum.midpoint.prism.query.NoneFilter;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.PropertyValueFilter;
import com.evolveum.midpoint.prism.query.UndefinedFilter;
import com.evolveum.midpoint.prism.query.ValueFilter;
import com.evolveum.midpoint.prism.util.JavaTypeConverter;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.schema.constants.ExpressionConstants;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.SecurityEnforcer;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
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.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.QueryInterpretationOfNoValueType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
* @author semancik
*
*/
public class ExpressionUtil {
private static final Trace LOGGER = TraceManager.getTrace(ExpressionUtil.class);
public static <V extends PrismValue> PrismValueDeltaSetTriple<V> toOutputTriple(
PrismValueDeltaSetTriple<V> resultTriple, ItemDefinition outputDefinition,
final ItemPath residualPath, final Protector protector, final PrismContext prismContext) {
PrismValueDeltaSetTriple<V> clonedTriple = resultTriple.clone();
final Class<?> resultTripleValueClass = resultTriple.getRealValueClass();
if (resultTripleValueClass == null) {
// triple is empty. type does not matter.
return clonedTriple;
}
Class<?> expectedJavaType = XsdTypeMapper.toJavaType(outputDefinition.getTypeName());
if (expectedJavaType == null) {
expectedJavaType = prismContext.getSchemaRegistry()
.getCompileTimeClass(outputDefinition.getTypeName());
}
if (resultTripleValueClass == expectedJavaType) {
return clonedTriple;
}
final Class<?> finalExpectedJavaType = expectedJavaType;
clonedTriple.accept(new Visitor() {
@Override
public void visit(Visitable visitable) {
if (visitable instanceof PrismPropertyValue<?>) {
PrismPropertyValue<Object> pval = (PrismPropertyValue<Object>) visitable;
Object realVal = pval.getValue();
if (realVal != null) {
if (Structured.class.isAssignableFrom(resultTripleValueClass)) {
if (residualPath != null && !residualPath.isEmpty()) {
realVal = ((Structured) realVal).resolve(residualPath);
}
}
if (finalExpectedJavaType != null) {
Object convertedVal = convertValue(finalExpectedJavaType, realVal, protector,
prismContext);
pval.setValue(convertedVal);
}
}
}
}
});
return clonedTriple;
}
/**
* Slightly more powerful version of "convert" as compared to
* JavaTypeConverter. This version can also encrypt/decrypt and also handles
* polystrings.
*/
public static <I, O> O convertValue(Class<O> finalExpectedJavaType, I inputVal, Protector protector,
PrismContext prismContext) {
if (inputVal == null) {
return null;
}
if (finalExpectedJavaType.isInstance(inputVal)) {
return (O) inputVal;
}
Object intermediateVal = inputVal;
if (finalExpectedJavaType == ProtectedStringType.class) {
String valueToEncrypt;
if (inputVal instanceof String) {
valueToEncrypt = (String) inputVal;
} else {
valueToEncrypt = JavaTypeConverter.convert(String.class, inputVal);
}
try {
intermediateVal = protector.encryptString(valueToEncrypt);
} catch (EncryptionException e) {
throw new SystemException(e.getMessage(), e);
}
} else {
if (inputVal instanceof ProtectedStringType) {
String decryptedString;
try {
intermediateVal = protector.decryptString((ProtectedStringType) inputVal);
} catch (EncryptionException e) {
throw new SystemException(e.getMessage(), e);
}
}
}
O convertedVal = JavaTypeConverter.convert(finalExpectedJavaType, intermediateVal);
PrismUtil.recomputeRealValue(convertedVal, prismContext);
return convertedVal;
}
public static Object resolvePath(ItemPath path, ExpressionVariables variables, Object defaultContext,
ObjectResolver objectResolver, String shortDesc, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException {
Object root = defaultContext;
ItemPath relativePath = path;
ItemPathSegment first = path.first();
String varDesc = "default context";
if (first instanceof NameItemPathSegment && ((NameItemPathSegment) first).isVariable()) {
QName varName = ((NameItemPathSegment) first).getName();
varDesc = "variable " + PrettyPrinter.prettyPrint(varName);
relativePath = path.rest();
if (variables.containsKey(varName)) {
root = variables.get(varName);
} else {
throw new SchemaException("No variable with name " + varName + " in " + shortDesc);
}
}
if (root == null) {
return null;
}
if (relativePath.isEmpty()) {
return root;
}
if (root instanceof ObjectReferenceType) {
root = resolveReference((ObjectReferenceType) root, objectResolver, varDesc, shortDesc, task,
result);
}
if (root instanceof Objectable) {
return (((Objectable) root).asPrismObject()).find(relativePath);
}
if (root instanceof PrismObject<?>) {
return ((PrismObject<?>) root).find(relativePath);
} else if (root instanceof PrismContainer<?>) {
return ((PrismContainer<?>) root).find(relativePath);
} else if (root instanceof PrismContainerValue<?>) {
return ((PrismContainerValue<?>) root).find(relativePath);
} else if (root instanceof Item<?, ?>) {
// Except for container (which is handled above)
throw new SchemaException(
"Cannot apply path " + relativePath + " to " + root + " in " + shortDesc);
} else if (root instanceof ObjectDeltaObject<?>) {
return ((ObjectDeltaObject<?>) root).findIdi(relativePath);
} else if (root instanceof ItemDeltaItem<?, ?>) {
return ((ItemDeltaItem<?, ?>) root).findIdi(relativePath);
} else {
throw new IllegalArgumentException(
"Unexpected root " + root + " (relative path:" + relativePath + ") in " + shortDesc);
}
}
public static Object convertVariableValue(Object originalValue, String variableName, ObjectResolver objectResolver,
String contextDescription, Task task, OperationResult result) throws ExpressionSyntaxException, ObjectNotFoundException {
if (originalValue instanceof ObjectReferenceType) {
try {
originalValue = resolveReference((ObjectReferenceType)originalValue, objectResolver, variableName,
contextDescription, task, result);
} catch (SchemaException e) {
throw new ExpressionSyntaxException("Schema error during variable "+variableName+" resolution in "+contextDescription+": "+e.getMessage(), e);
}
}
if (originalValue instanceof PrismObject<?>) {
return ((PrismObject<?>)originalValue).asObjectable();
}
if (originalValue instanceof PrismContainerValue<?>) {
return ((PrismContainerValue<?>)originalValue).asContainerable();
}
if (originalValue instanceof PrismPropertyValue<?>) {
return ((PrismPropertyValue<?>)originalValue).getValue();
}
if (originalValue instanceof PrismProperty<?>) {
PrismProperty<?> prop = (PrismProperty<?>)originalValue;
PrismPropertyDefinition<?> def = prop.getDefinition();
if (def != null) {
if (def.isSingleValue()) {
return prop.getRealValue();
} else {
return prop.getRealValues();
}
} else {
return prop.getValues();
}
}
if (originalValue instanceof PrismReference) {
PrismReference prop = (PrismReference)originalValue;
PrismReferenceDefinition def = prop.getDefinition();
if (def != null) {
if (def.isSingleValue()) {
return prop.getRealValue();
} else {
return prop.getRealValues();
}
} else {
return prop.getValues();
}
}
if (originalValue instanceof PrismContainer<?>) {
PrismContainer<?> container = (PrismContainer<?>)originalValue;
PrismContainerDefinition<?> def = container.getDefinition();
if (def != null) {
if (def.isSingleValue()) {
return container.getRealValue();
} else {
return container.getRealValues();
}
} else {
return container.getValues();
}
}
return originalValue;
}
public static Map<String,Object> prepareScriptVariables(ExpressionVariables variables, ObjectResolver objectResolver,
Collection<FunctionLibrary> functions,
String contextDescription, Task task, OperationResult result) throws ExpressionSyntaxException, ObjectNotFoundException {
Map<String,Object> scriptVariables = new HashMap<>();
// Functions
if (functions != null) {
for (FunctionLibrary funcLib: functions) {
scriptVariables.put(funcLib.getVariableName(), funcLib.getGenericFunctions());
}
}
// Variables
if (variables != null) {
for (Entry<QName, Object> variableEntry: variables.entrySet()) {
if (variableEntry.getKey() == null) {
// This is the "root" node. We have no use for it in JSR223, just skip it
continue;
}
String variableName = variableEntry.getKey().getLocalPart();
Object variableValue = ExpressionUtil.convertVariableValue(variableEntry.getValue(), variableName, objectResolver, contextDescription, task, result);
scriptVariables.put(variableName, variableValue);
}
}
return scriptVariables;
}
private static PrismObject<?> resolveReference(ObjectReferenceType ref, ObjectResolver objectResolver,
String varDesc, String contextDescription, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException {
if (ref.getOid() == null) {
throw new SchemaException(
"Null OID in reference in variable " + varDesc + " in " + contextDescription);
} else {
try {
ObjectType objectType = objectResolver.resolve(ref, ObjectType.class, null,
contextDescription, task, result);
if (objectType == null) {
throw new IllegalArgumentException(
"Resolve returned null for " + ref + " in " + contextDescription);
}
return objectType.asPrismObject();
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException("Object not found during variable " + varDesc
+ " resolution in " + contextDescription + ": " + e.getMessage(), e, ref.getOid());
} catch (SchemaException e) {
throw new SchemaException("Schema error during variable " + varDesc + " resolution in "
+ contextDescription + ": " + e.getMessage(), e);
}
}
}
public static <ID extends ItemDefinition> ID resolveDefinitionPath(ItemPath path,
ExpressionVariables variables, PrismObjectDefinition<?> defaultContext, String shortDesc)
throws SchemaException {
while (path != null && !path.isEmpty() && !(path.first() instanceof NameItemPathSegment)) {
path = path.rest();
}
Object root = defaultContext;
ItemPath relativePath = path;
NameItemPathSegment first = (NameItemPathSegment) path.first();
if (first.isVariable()) {
relativePath = path.rest();
QName varName = first.getName();
if (variables.containsKey(varName)) {
Object varValue = variables.get(varName);
if (varValue instanceof ItemDeltaItem<?, ?>) {
root = ((ItemDeltaItem<?, ?>) varValue).getDefinition();
} else if (varValue instanceof Item<?, ?>) {
root = ((Item<?, ?>) varValue).getDefinition();
} else if (varValue instanceof Objectable) {
root = ((Objectable) varValue).asPrismObject().getDefinition();
} else if (varValue instanceof ItemDefinition) {
root = varValue;
} else {
throw new IllegalStateException("Unexpected content of variable " + varName + ": "
+ varValue + " (" + varValue.getClass() + ")");
}
if (root == null) {
throw new IllegalStateException(
"Null definition in content of variable " + varName + ": " + varValue);
}
} else {
throw new SchemaException("No variable with name " + varName + " in " + shortDesc);
}
}
if (root == null) {
return null;
}
if (relativePath.isEmpty()) {
return (ID) root;
}
ItemDefinition result = null;
if (root instanceof PrismObjectDefinition<?>) {
return ((PrismObjectDefinition<?>) root).findItemDefinition(relativePath);
} else if (root instanceof PrismContainerDefinition<?>) {
return ((PrismContainerDefinition<?>) root).findItemDefinition(relativePath);
} else if (root instanceof ItemDefinition) {
// Except for container (which is handled above)
throw new SchemaException(
"Cannot apply path " + relativePath + " to " + root + " in " + shortDesc);
} else {
throw new IllegalArgumentException("Unexpected root " + root + " in " + shortDesc);
}
}
public static <IV extends PrismValue, ID extends ItemDefinition> ItemDeltaItem<IV, ID> toItemDeltaItem(
Object object, ObjectResolver objectResolver, String string, OperationResult result) {
if (object == null) {
return null;
}
if (object instanceof ItemDeltaItem<?, ?>) {
return (ItemDeltaItem<IV, ID>) object;
}
if (object instanceof PrismObject<?>) {
return (ItemDeltaItem<IV, ID>) new ObjectDeltaObject((PrismObject<?>) object, null,
(PrismObject<?>) object);
} else if (object instanceof Item<?, ?>) {
return new ItemDeltaItem<IV, ID>((Item<IV, ID>) object, null, (Item<IV, ID>) object);
} else if (object instanceof ItemDelta<?, ?>) {
return new ItemDeltaItem<IV, ID>(null, (ItemDelta<IV, ID>) object, null);
} else {
throw new IllegalArgumentException("Unexpected object " + object + " " + object.getClass());
}
}
public static FunctionLibrary createBasicFunctionLibrary(PrismContext prismContext, Protector protector) {
FunctionLibrary lib = new FunctionLibrary();
lib.setVariableName(MidPointConstants.FUNCTION_LIBRARY_BASIC_VARIABLE_NAME);
lib.setNamespace(MidPointConstants.NS_FUNC_BASIC);
BasicExpressionFunctions func = new BasicExpressionFunctions(prismContext, protector);
lib.setGenericFunctions(func);
BasicExpressionFunctionsXPath funcXPath = new BasicExpressionFunctionsXPath(func);
lib.setXmlFunctions(funcXPath);
return lib;
}
public static FunctionLibrary createLogFunctionLibrary(PrismContext prismContext) {
FunctionLibrary lib = new FunctionLibrary();
lib.setVariableName(MidPointConstants.FUNCTION_LIBRARY_LOG_VARIABLE_NAME);
lib.setNamespace(MidPointConstants.NS_FUNC_LOG);
LogExpressionFunctions func = new LogExpressionFunctions(prismContext);
lib.setGenericFunctions(func);
return lib;
}
public static ObjectQuery evaluateQueryExpressions(ObjectQuery origQuery, ExpressionVariables variables,
ExpressionFactory expressionFactory, PrismContext prismContext, String shortDesc, Task task,
OperationResult result)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
if (origQuery == null) {
return null;
}
ObjectQuery query = origQuery.clone();
ObjectFilter evaluatedFilter = evaluateFilterExpressionsInternal(query.getFilter(), variables,
expressionFactory, prismContext, shortDesc, task, result);
query.setFilter(evaluatedFilter);
return query;
}
public static ObjectFilter evaluateFilterExpressions(ObjectFilter origFilter,
ExpressionVariables variables, ExpressionFactory expressionFactory, PrismContext prismContext,
String shortDesc, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
if (origFilter == null) {
return null;
}
return evaluateFilterExpressionsInternal(origFilter, variables, expressionFactory, prismContext,
shortDesc, task, result);
}
private static ObjectFilter evaluateFilterExpressionsInternal(ObjectFilter filter,
ExpressionVariables variables, ExpressionFactory expressionFactory, PrismContext prismContext,
String shortDesc, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
if (filter == null) {
return null;
}
if (filter instanceof InOidFilter) {
// InOidFilter inOidFilter = (InOidFilter) filter;
// if (inOidFilter.getOids() != null && !inOidFilter.getOids().isEmpty()) {
// return inOidFilter.clone();
// }
ExpressionWrapper expressionWrapper = ((InOidFilter) filter).getExpression();
if (expressionWrapper == null || expressionWrapper.getExpression() == null) {
LOGGER.warn("No valueExpression in filter in {}. Returning original filter", shortDesc);
InOidFilter inOidFilter = (InOidFilter) filter;
if (inOidFilter.getOids() != null && !inOidFilter.getOids().isEmpty()){
return filter.clone();
}
return NoneFilter.createNone();
}
if (!(expressionWrapper.getExpression() instanceof ExpressionType)) {
throw new SchemaException("Unexpected expression type "
+ expressionWrapper.getExpression().getClass() + " in filter in " + shortDesc);
}
ExpressionType valueExpression = (ExpressionType) expressionWrapper.getExpression();
try {
Collection<String> expressionResult = evaluateStringExpression(variables, prismContext,
valueExpression, expressionFactory, shortDesc, task, result);
if (expressionResult == null || expressionResult.isEmpty()) {
LOGGER.debug("Result of search filter expression was null or empty. Expression: {}",
valueExpression);
return createFilterForNoValue(filter, valueExpression);
}
// TODO: log more context
LOGGER.trace("Search filter expression in the rule for {} evaluated to {}.",
new Object[] { shortDesc, expressionResult });
InOidFilter evaluatedFilter = (InOidFilter) filter.clone();
evaluatedFilter.setOids(expressionResult);
evaluatedFilter.setExpression(null);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Transformed filter to:\n{}", evaluatedFilter.debugDump());
}
return evaluatedFilter;
} catch (Exception ex) {
throw new ExpressionEvaluationException(ex);
}
} else if (filter instanceof LogicalFilter) {
List<ObjectFilter> conditions = ((LogicalFilter) filter).getConditions();
LogicalFilter evaluatedFilter = ((LogicalFilter) filter).cloneEmpty();
for (ObjectFilter condition : conditions) {
ObjectFilter evaluatedSubFilter = evaluateFilterExpressionsInternal(condition, variables,
expressionFactory, prismContext, shortDesc, task, result);
evaluatedFilter.addCondition(evaluatedSubFilter);
}
return evaluatedFilter;
} else if (filter instanceof PropertyValueFilter) {
PropertyValueFilter pvfilter = (PropertyValueFilter) filter;
if (pvfilter.getValues() != null && !pvfilter.getValues().isEmpty()) {
// We have value. Nothing to evaluate.
return pvfilter.clone();
}
ExpressionWrapper expressionWrapper = pvfilter.getExpression();
if (expressionWrapper == null || expressionWrapper.getExpression() == null) {
LOGGER.warn("No valueExpression in filter in {}. Returning original filter", shortDesc);
return pvfilter.clone();
}
if (!(expressionWrapper.getExpression() instanceof ExpressionType)) {
throw new SchemaException("Unexpected expression type "
+ expressionWrapper.getExpression().getClass() + " in filter in " + shortDesc);
}
ExpressionType valueExpression = (ExpressionType) expressionWrapper.getExpression();
try {
PrismValue expressionResult = evaluateExpression(variables, prismContext, valueExpression,
filter, expressionFactory, shortDesc, task, result);
if (expressionResult == null || expressionResult.isEmpty()) {
LOGGER.debug("Result of search filter expression was null or empty. Expression: {}",
valueExpression);
return createFilterForNoValue(pvfilter, valueExpression);
}
// TODO: log more context
LOGGER.trace("Search filter expression in the rule for {} evaluated to {}.",
new Object[] { shortDesc, expressionResult });
PropertyValueFilter evaluatedFilter = (PropertyValueFilter) pvfilter.clone();
evaluatedFilter.setValue(expressionResult);
evaluatedFilter.setExpression(null);
// }
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Transformed filter to:\n{}", evaluatedFilter.debugDump());
}
return evaluatedFilter;
} catch (RuntimeException ex) {
LoggingUtils.logException(LOGGER, "Couldn't evaluate expression " + valueExpression + ".",
ex);
throw new SystemException(
"Couldn't evaluate expression" + valueExpression + ": " + ex.getMessage(), ex);
} catch (SchemaException ex) {
LoggingUtils.logException(LOGGER, "Couldn't evaluate expression " + valueExpression + ".",
ex);
throw new SchemaException(
"Couldn't evaluate expression" + valueExpression + ": " + ex.getMessage(), ex);
} catch (ObjectNotFoundException ex) {
LoggingUtils.logException(LOGGER, "Couldn't evaluate expression " + valueExpression + ".",
ex);
throw new ObjectNotFoundException(
"Couldn't evaluate expression" + valueExpression + ": " + ex.getMessage(), ex);
} catch (ExpressionEvaluationException ex) {
LoggingUtils.logException(LOGGER, "Couldn't evaluate expression " + valueExpression + ".",
ex);
throw new ExpressionEvaluationException(
"Couldn't evaluate expression" + valueExpression + ": " + ex.getMessage(), ex);
}
} else {
throw new IllegalStateException("Unsupported filter type: " + filter.getClass());
}
}
private static ObjectFilter createFilterForNoValue(ObjectFilter filter, ExpressionType valueExpression) throws ExpressionEvaluationException {
QueryInterpretationOfNoValueType queryInterpretationOfNoValue = valueExpression.getQueryInterpretationOfNoValue();
if (queryInterpretationOfNoValue == null) {
queryInterpretationOfNoValue = QueryInterpretationOfNoValueType.FILTER_EQUAL_NULL;
}
switch (queryInterpretationOfNoValue) {
case FILTER_UNDEFINED:
return UndefinedFilter.createUndefined();
case FILTER_NONE:
return NoneFilter.createNone();
case FILTER_ALL:
return AllFilter.createAll();
case FILTER_EQUAL_NULL:
if (filter instanceof PropertyValueFilter) {
PropertyValueFilter evaluatedFilter = (PropertyValueFilter) filter.clone();
evaluatedFilter.setExpression(null);
return evaluatedFilter;
} else if (filter instanceof InOidFilter) {
return NoneFilter.createNone();
} else {
throw new IllegalArgumentException("Unknow filter to evaluate: " + filter);
}
case ERROR:
throw new ExpressionEvaluationException("Expression "+valueExpression+" evaluated to no value");
default:
throw new IllegalArgumentException("Unknown value "+queryInterpretationOfNoValue+" in queryInterpretationOfNoValue in "+valueExpression);
}
}
private static <V extends PrismValue> V evaluateExpression(ExpressionVariables variables,
PrismContext prismContext, ExpressionType expressionType, ObjectFilter filter,
ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
// TODO refactor after new query engine is implemented
ItemDefinition outputDefinition = null;
if (filter instanceof ValueFilter) {
outputDefinition = ((ValueFilter) filter).getDefinition();
}
if (outputDefinition == null) {
outputDefinition = new PrismPropertyDefinition(ExpressionConstants.OUTPUT_ELMENT_NAME,
DOMUtil.XSD_STRING, prismContext);
}
return evaluateExpression(variables, outputDefinition, expressionType, expressionFactory, shortDesc,
task, parentResult);
// String expressionResult =
// expressionHandler.evaluateExpression(currentShadow, valueExpression,
// shortDesc, result);
}
public static <V extends PrismValue, D extends ItemDefinition> V evaluateExpression(
ExpressionVariables variables, D outputDefinition, ExpressionType expressionType,
ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult)
throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
Expression<V, D> expression = expressionFactory.makeExpression(expressionType, outputDefinition,
shortDesc, task, parentResult);
ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, variables, shortDesc, task,
parentResult);
PrismValueDeltaSetTriple<V> outputTriple = expression.evaluate(params);
LOGGER.trace("Result of the expression evaluation: {}", outputTriple);
if (outputTriple == null) {
return null;
}
Collection<V> nonNegativeValues = outputTriple.getNonNegativeValues();
if (nonNegativeValues == null || nonNegativeValues.isEmpty()) {
return null;
}
if (nonNegativeValues.size() > 1) {
throw new ExpressionEvaluationException("Expression returned more than one value ("
+ nonNegativeValues.size() + ") in " + shortDesc);
}
return (V) nonNegativeValues.iterator().next();
}
private static Collection<String> evaluateStringExpression(ExpressionVariables variables,
PrismContext prismContext, ExpressionType expressionType, ExpressionFactory expressionFactory,
String shortDesc, Task task, OperationResult parentResult)
throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
PrismPropertyDefinition<String> outputDefinition = new PrismPropertyDefinition(
ExpressionConstants.OUTPUT_ELMENT_NAME, DOMUtil.XSD_STRING, prismContext);
outputDefinition.setMaxOccurs(-1);
Expression<PrismPropertyValue<String>, PrismPropertyDefinition<String>> expression = expressionFactory
.makeExpression(expressionType, outputDefinition, shortDesc, task, parentResult);
ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, variables, shortDesc, task,
parentResult);
PrismValueDeltaSetTriple<PrismPropertyValue<String>> outputTriple = expression.evaluate(params);
LOGGER.trace("Result of the expression evaluation: {}", outputTriple);
if (outputTriple == null) {
return null;
}
Collection<PrismPropertyValue<String>> nonNegativeValues = outputTriple.getNonNegativeValues();
if (nonNegativeValues == null || nonNegativeValues.isEmpty()) {
return null;
}
return PrismValue.getRealValuesOfCollection((Collection) nonNegativeValues);
// return nonNegativeValues.iterator().next();
}
public static PrismPropertyValue<Boolean> evaluateCondition(ExpressionVariables variables,
ExpressionType expressionType, ExpressionFactory expressionFactory, String shortDesc, Task task,
OperationResult parentResult)
throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
ItemDefinition outputDefinition = new PrismPropertyDefinition<Boolean>(
ExpressionConstants.OUTPUT_ELMENT_NAME, DOMUtil.XSD_BOOLEAN,
expressionFactory.getPrismContext());
return (PrismPropertyValue<Boolean>) evaluateExpression(variables, outputDefinition, expressionType,
expressionFactory, shortDesc, task, parentResult);
}
public static Map<QName, Object> compileVariablesAndSources(ExpressionEvaluationContext params) {
Map<QName, Object> variablesAndSources = new HashMap<QName, Object>();
if (params.getVariables() != null) {
for (Entry<QName, Object> entry : params.getVariables().entrySet()) {
variablesAndSources.put(entry.getKey(), entry.getValue());
}
}
if (params.getSources() != null) {
for (Source<?, ?> source : params.getSources()) {
variablesAndSources.put(source.getName(), source);
}
}
return variablesAndSources;
}
public static boolean hasExplicitTarget(List<MappingType> mappingTypes) {
for (MappingType mappingType : mappingTypes) {
if (hasExplicitTarget(mappingType)) {
return true;
}
}
return false;
}
private static boolean hasExplicitTarget(MappingType mappingType) {
return mappingType.getTarget() != null;
}
public static boolean computeConditionResult(
Collection<PrismPropertyValue<Boolean>> booleanPropertyValues) {
if (booleanPropertyValues == null || booleanPropertyValues.isEmpty()) {
// No value means false
return false;
}
boolean hasFalse = false;
for (PrismPropertyValue<Boolean> pval : booleanPropertyValues) {
Boolean value = pval.getValue();
if (Boolean.TRUE.equals(value)) {
return true;
}
if (Boolean.FALSE.equals(value)) {
hasFalse = true;
}
}
if (hasFalse) {
return false;
}
// No value or all values null. Return default.
return true;
}
public static PlusMinusZero computeConditionResultMode(boolean condOld, boolean condNew) {
if (condOld && condNew) {
return PlusMinusZero.ZERO;
}
if (!condOld && !condNew) {
return null;
}
if (condOld && !condNew) {
return PlusMinusZero.MINUS;
}
if (!condOld && condNew) {
return PlusMinusZero.PLUS;
}
throw new IllegalStateException("notreached");
}
public static void addActorVariable(ExpressionVariables scriptVariables,
SecurityEnforcer securityEnforcer) {
// There can already be a value, because for mappings, we create the
// variable before parsing sources.
// For other scripts we do it just before the execution, to catch all
// possible places where scripts can be executed.
UserType oldActor = (UserType) scriptVariables.get(ExpressionConstants.VAR_ACTOR);
if (oldActor != null) {
return;
}
UserType actor = null;
try {
if (securityEnforcer != null) {
if (!securityEnforcer.isAuthenticated()) {
// Nothing to set up. This is most likely evaluation of role
// condition before
// the authentication is complete.
return;
}
MidPointPrincipal principal = securityEnforcer.getPrincipal();
if (principal != null) {
actor = principal.getUser();
}
}
if (actor == null) {
LOGGER.debug("Couldn't get principal information - the 'actor' variable is set to null");
}
} catch (SecurityViolationException e) {
LoggingUtils.logUnexpectedException(LOGGER,
"Couldn't get principal information - the 'actor' variable is set to null", e);
}
scriptVariables.addVariableDefinition(ExpressionConstants.VAR_ACTOR, actor);
}
public static <D extends ItemDefinition> Object convertToOutputValue(Long longValue, D outputDefinition,
Protector protector) throws ExpressionEvaluationException, SchemaException {
if (longValue == null) {
return null;
}
QName outputType = outputDefinition.getTypeName();
if (outputType.equals(DOMUtil.XSD_INT)) {
return longValue.intValue();
} else if (outputType.equals(DOMUtil.XSD_LONG)) {
return longValue;
} else {
return convertToOutputValue(longValue.toString(), outputDefinition, protector);
}
}
public static <D extends ItemDefinition> Object convertToOutputValue(String stringValue,
D outputDefinition, Protector protector) throws ExpressionEvaluationException, SchemaException {
if (stringValue == null) {
return null;
}
QName outputType = outputDefinition.getTypeName();
if (outputType.equals(DOMUtil.XSD_STRING)) {
return stringValue;
} else if (outputType.equals(ProtectedStringType.COMPLEX_TYPE)) {
try {
return protector.encryptString(stringValue);
} catch (EncryptionException e) {
throw new ExpressionEvaluationException("Crypto error: " + e.getMessage(), e);
}
} else if (XmlTypeConverter.canConvert(outputType)) {
Class<?> outputJavaType = XsdTypeMapper.toJavaType(outputType);
try {
return XmlTypeConverter.toJavaValue(stringValue, outputJavaType, true);
} catch (NumberFormatException e) {
throw new SchemaException("Cannot convert string '" + stringValue + "' to data type "
+ outputType + ": invalid number format", e);
} catch (IllegalArgumentException e) {
throw new SchemaException("Cannot convert string '" + stringValue + "' to data type "
+ outputType + ": " + e.getMessage(), e);
}
} else {
throw new IllegalArgumentException(
"Expression cannot generate values for properties of type " + outputType);
}
}
public static <T> boolean isEmpty(T val) {
if (val == null) {
return true;
}
if (val instanceof String && ((String)val).isEmpty()) {
return true;
}
if (val instanceof PolyString && ((PolyString)val).isEmpty()) {
return true;
}
return false;
}
public static <T, V extends PrismValue> V convertToPrismValue(T value, ItemDefinition definition, String contextDescription, PrismContext prismContext) throws ExpressionEvaluationException {
if (definition instanceof PrismReferenceDefinition) {
return (V) ((ObjectReferenceType) value).asReferenceValue();
} else if (definition instanceof PrismContainerDefinition) {
try {
prismContext.adopt((Containerable) value);
((Containerable) value).asPrismContainerValue().applyDefinition(definition);
} catch (SchemaException e) {
throw new ExpressionEvaluationException(e.getMessage() + " " + contextDescription, e);
}
return (V) ((Containerable) value).asPrismContainerValue();
} else {
return (V) new PrismPropertyValue<>(value);
}
}
}