-
Notifications
You must be signed in to change notification settings - Fork 188
/
ScriptExpressionFactory.java
252 lines (219 loc) · 11.6 KB
/
ScriptExpressionFactory.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
/*
* Copyright (c) 2010-2019 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.script;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.jetbrains.annotations.NotNull;
import com.evolveum.midpoint.CacheInvalidationContext;
import com.evolveum.midpoint.model.common.expression.functions.CustomFunctions;
import com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.repo.api.Cacheable;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.repo.api.CacheRegistry;
import com.evolveum.midpoint.repo.common.ObjectResolver;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.repo.common.expression.ExpressionSyntaxException;
import com.evolveum.midpoint.schema.AccessDecision;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.expression.ExpressionEvaluatorProfile;
import com.evolveum.midpoint.schema.expression.ExpressionProfile;
import com.evolveum.midpoint.schema.expression.ScriptExpressionProfile;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FunctionLibraryType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType;
/**
* @author Radovan Semancik
*/
public class ScriptExpressionFactory implements Cacheable {
private static final Trace LOGGER = TraceManager.getTrace(ScriptExpressionFactory.class);
private static final Trace LOGGER_CONTENT = TraceManager.getTrace(ScriptExpressionFactory.class.getName() + ".content");
private static final String DEFAULT_LANGUAGE = "http://midpoint.evolveum.com/xml/ns/public/expression/language#Groovy";
private final Map<String, ScriptEvaluator> evaluatorMap = new HashMap<>();
private ObjectResolver objectResolver;
private final PrismContext prismContext;
private Collection<FunctionLibrary> functions;
private final RepositoryService repositoryService; // might be null during low-level testing
@NotNull private final Map<String, FunctionLibrary> customFunctionLibraryCache = new ConcurrentHashMap<>();
private final AtomicBoolean initialized = new AtomicBoolean(false);
private CacheRegistry cacheRegistry;
@PostConstruct
public void register() {
cacheRegistry.registerCacheableService(this);
}
@PreDestroy
public void unregister() {
cacheRegistry.unregisterCacheableService(this);
}
public ScriptExpressionFactory(PrismContext prismContext, RepositoryService repositoryService) {
this.prismContext = prismContext;
this.repositoryService = repositoryService;
}
public ObjectResolver getObjectResolver() {
return objectResolver;
}
public void setObjectResolver(ObjectResolver objectResolver) {
this.objectResolver = objectResolver;
}
public void setEvaluators(Collection<ScriptEvaluator> evaluators) {
for (ScriptEvaluator evaluator : evaluators) {
registerEvaluator(evaluator.getLanguageUrl(), evaluator);
}
}
public Collection<FunctionLibrary> getFunctions() {
return Collections.unmodifiableCollection(functions); // MID-4396
}
public void setFunctions(Collection<FunctionLibrary> functions) {
this.functions = functions;
}
public Map<String, ScriptEvaluator> getEvaluators() {
return evaluatorMap;
}
public void setCacheRegistry(CacheRegistry registry) {
this.cacheRegistry = registry;
}
public ScriptExpression createScriptExpression(
ScriptExpressionEvaluatorType expressionType, ItemDefinition outputDefinition,
ExpressionProfile expressionProfile, ExpressionFactory expressionFactory,
String shortDesc, OperationResult result)
throws ExpressionSyntaxException, SecurityViolationException {
initializeCustomFunctionsLibraryCacheIfNeeded(expressionFactory, result);
//cache cleanup method
String language = getLanguage(expressionType);
ScriptExpression expression = new ScriptExpression(getEvaluator(language, shortDesc), expressionType);
expression.setPrismContext(prismContext);
expression.setOutputDefinition(outputDefinition);
expression.setObjectResolver(objectResolver);
Collection<FunctionLibrary> functionsToUse = new ArrayList<>(functions);
functionsToUse.addAll(customFunctionLibraryCache.values());
expression.setFunctions(functionsToUse);
// It is not very elegant to process expression profile and script expression profile here.
// It is somehow redundant, as it was already pre-processed in the expression evaluator/factory
// We are throwing that out and we are processing it again. But maybe this is consequence of having
// the duality of Expression and ScriptExpression ... maybe the ScriptExpression is unnecessary abstraction
// and it should be removed.
expression.setExpressionProfile(expressionProfile);
expression.setScriptExpressionProfile(processScriptExpressionProfile(expressionProfile, language, shortDesc));
return expression;
}
private ScriptExpressionProfile processScriptExpressionProfile(ExpressionProfile expressionProfile, String language, String shortDesc) throws SecurityViolationException {
if (expressionProfile == null) {
return null;
}
ExpressionEvaluatorProfile evaluatorProfile = expressionProfile.getEvaluatorProfile(ScriptExpressionEvaluatorFactory.ELEMENT_NAME);
if (evaluatorProfile == null) {
if (expressionProfile.getDecision() == AccessDecision.ALLOW) {
return null;
} else {
throw new SecurityViolationException("Access to script expression evaluator " +
" not allowed (expression profile: " + expressionProfile.getIdentifier() + ") in " + shortDesc);
}
}
ScriptExpressionProfile scriptProfile = evaluatorProfile.getScriptExpressionProfile(language);
if (scriptProfile == null) {
if (evaluatorProfile.getDecision() == AccessDecision.ALLOW) {
return null;
} else {
throw new SecurityViolationException("Access to script language " + language +
" not allowed (expression profile: " + expressionProfile.getIdentifier() + ") in " + shortDesc);
}
}
return scriptProfile;
}
private void initializeCustomFunctionsLibraryCacheIfNeeded(ExpressionFactory expressionFactory, OperationResult result)
throws ExpressionSyntaxException {
if (initialized.compareAndSet(false, true)) {
initializeCustomFunctionsLibraryCache(expressionFactory, result);
}
}
private void initializeCustomFunctionsLibraryCache(ExpressionFactory expressionFactory, OperationResult result)
throws ExpressionSyntaxException {
if (repositoryService != null) {
OperationResult subResult = result
.createMinorSubresult(ScriptExpressionFactory.class.getName() + ".searchCustomFunctions");
ResultHandler<FunctionLibraryType> functionLibraryHandler = (object, parentResult) -> {
// TODO: determine profile from function library archetype
ExpressionProfile expressionProfile = MiscSchemaUtil.getExpressionProfile();
FunctionLibrary customLibrary = new FunctionLibrary();
customLibrary.setVariableName(object.getName().getOrig());
customLibrary.setGenericFunctions(
new CustomFunctions(object.asObjectable(), expressionFactory, expressionProfile));
customLibrary.setNamespace(MidPointConstants.NS_FUNC_CUSTOM);
customFunctionLibraryCache.put(object.getName().getOrig(), customLibrary);
return true;
};
try {
repositoryService.searchObjectsIterative(FunctionLibraryType.class, null, functionLibraryHandler,
SelectorOptions.createCollection(GetOperationOptions.createReadOnly()), true, subResult);
subResult.recordSuccessIfUnknown();
} catch (SchemaException | RuntimeException e) {
subResult.recordFatalError("Failed to initialize custom functions", e);
throw new ExpressionSyntaxException(
"An error occurred during custom libraries initialization. " + e.getMessage(), e);
}
} else {
LOGGER.warn("No repository service set for ScriptExpressionFactory; custom functions will not be loaded. This"
+ " can occur during low-level testing; never during standard system execution.");
}
}
public void registerEvaluator(String language, ScriptEvaluator evaluator) {
if (evaluatorMap.containsKey(language)) {
throw new IllegalArgumentException("Evaluator for language " + language + " already registered");
}
evaluatorMap.put(language, evaluator);
}
private ScriptEvaluator getEvaluator(String language, String shortDesc) throws ExpressionSyntaxException {
ScriptEvaluator evaluator = evaluatorMap.get(language);
if (evaluator == null) {
throw new ExpressionSyntaxException("Unsupported language " + language + " used in script in " + shortDesc);
}
return evaluator;
}
private String getLanguage(ScriptExpressionEvaluatorType expressionType) {
if (expressionType.getLanguage() != null) {
return expressionType.getLanguage();
}
return DEFAULT_LANGUAGE;
}
@Override
public void invalidate(Class<?> type, String oid, CacheInvalidationContext context) {
if (type == null || type.isAssignableFrom(FunctionLibraryType.class)) {
// Currently we don't try to select entries to be cleared based on OID
customFunctionLibraryCache.clear();
}
}
@NotNull
@Override
public Collection<SingleCacheStateInformationType> getStateInformation() {
return Collections.singleton(new SingleCacheStateInformationType(prismContext)
.name(ScriptExpressionFactory.class.getName())
.size(customFunctionLibraryCache.size()));
}
@Override
public void dumpContent() {
if (LOGGER_CONTENT.isInfoEnabled()) {
if (initialized.get()) {
customFunctionLibraryCache.forEach((k, v) -> LOGGER_CONTENT.info("Cached function library: {}: {}", k, v));
} else {
LOGGER_CONTENT.info("Custom function library cache is not yet initialized");
}
}
}
}