-
Notifications
You must be signed in to change notification settings - Fork 492
/
UelUtil.java
561 lines (527 loc) · 22.1 KB
/
UelUtil.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
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.ofbiz.base.util.string;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.el.ArrayELResolver;
import javax.el.BeanELResolver;
import javax.el.CompositeELResolver;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.ExpressionFactory;
import javax.el.FunctionMapper;
import javax.el.ListELResolver;
import javax.el.MapELResolver;
import javax.el.PropertyNotFoundException;
import javax.el.PropertyNotWritableException;
import javax.el.ResourceBundleELResolver;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.collections.LocalizedMap;
/** Implements the Unified Expression Language (JSR-245). */
public final class UelUtil {
private static final String MODULE = UelUtil.class.getName();
private static final String LOCALIZED_MAP_LOCALE_KEY = LocalizedMap.class.getName() + "_locale".replace(".", "_");
private static final ExpressionFactory EXPR_FACTORY = JuelConnector.newExpressionFactory();
private static final ELResolver DEFAULT_RESOLVER = new ExtendedCompositeResolver() {
{
add(new ExtendedMapResolver(false));
add(new ExtendedListResolver(false));
add(new ArrayELResolver(false));
add(new NodeELResolver()); // Below the most common but must be kept above BeanELResolver
add(new ResourceBundleELResolver());
add(new BeanELResolver(false));
}
};
private UelUtil() { }
public static String getLocalizedMapLocaleKey() {
return LOCALIZED_MAP_LOCALE_KEY;
}
/** Evaluates a Unified Expression Language expression and returns the result.
* @param context Evaluation context (variables)
* @param expression UEL expression
* @return Result object
*/
public static Object evaluate(Map<String, ? extends Object> context, String expression) {
return evaluate(context, expression, Object.class);
}
/** Evaluates a Unified Expression Language expression and returns the result.
* @param context Evaluation context (variables)
* @param expression UEL expression
* @param expectedType The expected object Class to return
* @return Result object
*/
public static Object evaluate(Map<String, ? extends Object> context, String expression, Class<?> expectedType) {
ELContext elContext = new ReadOnlyContext(context);
ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, expectedType);
return ve.getValue(elContext);
}
/** Evaluates a Unified Expression Language expression and sets the resulting object
* to the specified value.
* @param context Evaluation context (variables)
* @param expression UEL expression
* @param expectedType The expected object Class to set
*/
public static void setValue(Map<String, Object> context, String expression, Class<?> expectedType, Object value) {
if (Debug.verboseOn()) {
Debug.logVerbose("UelUtil.setValue invoked, expression = " + expression + ", value = " + value, MODULE);
}
ELContext elContext = new BasicContext(context);
ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, expectedType);
ve.setValue(elContext, value);
}
/** Evaluates a Unified Expression Language expression and sets the resulting object
* to null.
* @param context Evaluation context (variables)
* @param expression UEL expression
*/
public static void removeValue(Map<String, Object> context, String expression) {
if (Debug.verboseOn()) {
Debug.logVerbose("UelUtil.removeValue invoked, expression = " + expression, MODULE);
}
ELContext elContext = new BasicContext(context);
ValueExpression ve = EXPR_FACTORY.createValueExpression(elContext, expression, Object.class);
ve.setValue(elContext, null);
}
private static final class BasicContext extends ELContext {
private final Map<String, Object> variables;
private final VariableMapper variableMapper;
private BasicContext(Map<String, Object> context) {
this.variableMapper = new BasicVariableMapper(this);
this.variables = context;
}
@Override
public ELResolver getELResolver() {
return DEFAULT_RESOLVER;
}
@Override
public FunctionMapper getFunctionMapper() {
return UelFunctions.getFunctionMapper();
}
@Override
public VariableMapper getVariableMapper() {
return this.variableMapper;
}
}
private static final class ReadOnlyContext extends ELContext {
private final Map<String, ? extends Object> variables;
private final VariableMapper variableMapper;
private ReadOnlyContext(Map<String, ? extends Object> context) {
this.variableMapper = new ReadOnlyVariableMapper(this);
this.variables = UtilGenerics.cast(context);
}
@Override
public ELResolver getELResolver() {
return DEFAULT_RESOLVER;
}
@Override
public FunctionMapper getFunctionMapper() {
return UelFunctions.getFunctionMapper();
}
@Override
public VariableMapper getVariableMapper() {
return this.variableMapper;
}
private static final class ReadOnlyVariableMapper extends VariableMapper {
private final ReadOnlyContext elContext;
private ReadOnlyVariableMapper(ReadOnlyContext elContext) {
this.elContext = elContext;
}
@Override
public ValueExpression resolveVariable(String variable) {
Object obj = UelUtil.resolveVariable(variable, this.elContext.variables, null);
if (obj != null) {
return new ReadOnlyExpression(obj);
}
return null;
}
@Override
public ValueExpression setVariable(String variable, ValueExpression expression) {
throw new PropertyNotWritableException();
}
}
}
private static final class BasicVariableMapper extends VariableMapper {
private final BasicContext elContext;
private BasicVariableMapper(BasicContext elContext) {
this.elContext = elContext;
}
/**
* Returns a BasicValueExpression containing the value of the named variable.
* Resolves against LocalizedMap if available.
* @param variable the variable's name
* @return a BasicValueExpression containing the variable's value or null if the variable is unknown
*/
@Override
public ValueExpression resolveVariable(String variable) {
Object obj = UelUtil.resolveVariable(variable, this.elContext.variables, null);
if (obj != null) {
return new BasicValueExpression(variable, this.elContext);
}
return null;
}
@Override
public ValueExpression setVariable(String variable, ValueExpression expression) {
Object originalObj = this.elContext.variables.put(variable, expression.getValue(this.elContext));
if (originalObj == null) {
return null;
}
return new ReadOnlyExpression(originalObj);
}
}
@SuppressWarnings("serial")
private static final class ReadOnlyExpression extends ValueExpression {
private final Object object;
private ReadOnlyExpression(Object object) {
this.object = object;
}
@Override
public Class<?> getExpectedType() {
return this.object.getClass();
}
@Override
public Class<?> getType(ELContext context) {
return this.getExpectedType();
}
@Override
public Object getValue(ELContext context) {
return this.object;
}
@Override
public boolean isReadOnly(ELContext context) {
return true;
}
@Override
public void setValue(ELContext context, Object value) {
throw new PropertyNotWritableException();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ReadOnlyExpression) {
ReadOnlyExpression other = (ReadOnlyExpression) obj;
return this.object.equals(other.object);
}
return false;
}
@Override
public String getExpressionString() {
return null;
}
@Override
public int hashCode() {
return this.object.hashCode();
}
@Override
public boolean isLiteralText() {
return false;
}
}
@SuppressWarnings("serial")
private static final class BasicValueExpression extends ValueExpression {
private final BasicContext elContext;
private final String varName;
private BasicValueExpression(String varName, BasicContext elContext) {
this.elContext = elContext;
this.varName = varName;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof BasicValueExpression) {
BasicValueExpression other = (BasicValueExpression) obj;
return this.varName.equals(other.varName);
}
return false;
}
@Override
public int hashCode() {
return this.varName.hashCode();
}
@Override
public Object getValue(ELContext context) {
return this.elContext.variables.get(this.varName);
}
@Override
public String getExpressionString() {
return null;
}
@Override
public boolean isLiteralText() {
return false;
}
@Override
public Class<?> getType(ELContext context) {
return this.getExpectedType();
}
@Override
public boolean isReadOnly(ELContext context) {
return false;
}
@Override
public void setValue(ELContext context, Object value) {
this.elContext.variables.put(this.varName, value);
}
@Override
public String toString() {
return "ValueExpression(" + this.varName + ")";
}
@Override
public Class<?> getExpectedType() {
Object obj = this.elContext.variables.get(this.varName);
return obj == null ? null : obj.getClass();
}
}
/** Custom <code>CompositeELResolver</code> used to handle variable
* auto-vivify.
*/
private static class ExtendedCompositeResolver extends CompositeELResolver {
@Override
public void setValue(ELContext context, Object base, Object property, Object val) {
super.setValue(context, base, property, val);
if (!context.isPropertyResolved() && base == null) {
if (Debug.verboseOn()) {
Debug.logVerbose("ExtendedCompositeResolver.setValue: base = " + base + ", property = " + property + ", value = " + val, MODULE);
}
try {
BasicContext elContext = (BasicContext) context;
elContext.variables.put(property.toString(), val);
context.setPropertyResolved(true);
} catch (ClassCastException e) {
Debug.logInfo(e.getMessage(), MODULE);
}
}
}
}
/** Custom <code>ListELResolver</code> used to handle OFBiz
* <code>List</code> syntax.
*/
private static final class ExtendedListResolver extends ListELResolver {
private boolean isReadOnly;
private ExtendedListResolver(boolean isReadOnly) {
super(isReadOnly);
this.isReadOnly = isReadOnly;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object val) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base instanceof List) {
if (isReadOnly) {
throw new PropertyNotWritableException();
}
String str = property.toString();
if ("add".equals(str)) {
if (Debug.verboseOn()) {
Debug.logVerbose("ExtendedListResolver.setValue adding List element: base = " + base + ", property = "
+ property + ", value = " + val, MODULE);
}
context.setPropertyResolved(true);
List<Object> list = UtilGenerics.cast(base);
list.add(val);
} else if (str.startsWith("insert@")) {
if (Debug.verboseOn()) {
Debug.logVerbose("ExtendedListResolver.setValue inserting List element: base = " + base + ", property = "
+ property + ", value = " + val, MODULE);
}
context.setPropertyResolved(true);
String indexStr = str.replace("insert@", "");
int index = Integer.parseInt(indexStr);
List<Object> list = UtilGenerics.cast(base);
try {
list.add(index, val);
} catch (UnsupportedOperationException ex) {
throw new PropertyNotWritableException();
} catch (IndexOutOfBoundsException ex) {
throw new PropertyNotFoundException();
}
} else {
super.setValue(context, base, property, val);
}
}
}
}
/** Custom <code>MapELResolver</code> class used to accommodate
* <code>LocalizedMap</code> instances.
*/
private static final class ExtendedMapResolver extends MapELResolver {
private ExtendedMapResolver(boolean isReadOnly) {
super(isReadOnly);
}
@Override
@SuppressWarnings("unchecked")
public Object getValue(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base instanceof LocalizedMap) {
context.setPropertyResolved(true);
LocalizedMap<Object> map = (LocalizedMap<Object>) base;
Locale locale = null;
try {
VariableMapper vm = context.getVariableMapper();
ValueExpression ve = vm.resolveVariable(LOCALIZED_MAP_LOCALE_KEY);
if (ve != null) {
locale = (Locale) ve.getValue(context);
}
if (locale == null) {
ve = vm.resolveVariable("locale");
if (ve != null) {
locale = (Locale) ve.getValue(context);
}
}
} catch (Exception e) {
Debug.logWarning("Exception thrown while getting LocalizedMap element, locale = " + locale + ", exception " + e, MODULE);
}
if (locale == null) {
if (Debug.verboseOn()) {
Debug.logVerbose("ExtendedMapResolver.getValue: unable to find Locale for LocalizedMap element, using default locale",
MODULE);
}
locale = Locale.getDefault();
}
return resolveVariable(property.toString(), (Map<String, Object>) map, locale);
}
if (base != null && base instanceof Map && property instanceof String) {
context.setPropertyResolved(true);
return resolveVariable(property.toString(), (Map<String, Object>) base, null);
}
return super.getValue(context, base, property);
}
}
/** Evaluates a property <code>Object</code> and returns a new
* <code>List</code> or <code>Map</code>. If <code>property</code>
* is not a String object type and it evaluates to an integer value,
* a new <code>List</code> instance is returned, otherwise a new
* <code>Map</code> instance is returned.
* @param property Property <code>Object</code> to be evaluated
* @return New <code>List</code> or <code>Map</code>
*/
@SuppressWarnings("rawtypes")
static Object autoVivifyListOrMap(Object property) {
String str = property.toString();
boolean isList = ("add".equals(str) || str.startsWith("insert@"));
if (!isList && !"java.lang.String".equals(property.getClass().getName())) {
Integer index = UtilMisc.toIntegerObject(property);
isList = (index != null);
}
if (isList) {
return new LinkedList();
} else {
return new HashMap();
}
}
/** Prepares an expression for evaluation by UEL.<p>The OFBiz syntax is
* converted to UEL-compatible syntax and the resulting expression is
* returned.</p>
* @see <a href="StringUtil.html#convertOperatorSubstitutions(java.lang.String)">StringUtil.convertOperatorSubstitutions(java.lang.String)</a>
* @param expression Expression to be converted
* @return Converted expression
*/
public static String prepareExpression(String expression) {
String result = StringUtil.convertOperatorSubstitutions(expression);
result = result.replace("[]", "['add']");
int openBrace = result.indexOf("[+");
int closeBrace = (openBrace == -1 ? -1 : result.indexOf(']', openBrace));
if (closeBrace != -1) {
String base = result.substring(0, openBrace);
String property = result.substring(openBrace + 2, closeBrace).trim();
String end = result.substring(closeBrace + 1);
result = base + "['insert@" + property + "']" + end;
}
return result;
}
private static Object resolveVariable(String variable, Map<String, ? extends Object> variables, Locale locale) {
Object obj = null;
String createObjectType = null;
String name = variable;
if (variable.contains("$")) {
if (variable.endsWith("$string")) {
name = variable.substring(0, variable.length() - 7);
createObjectType = "string";
} else if (variable.endsWith("$null")) {
name = variable.substring(0, variable.length() - 5);
createObjectType = "null";
} else if (variable.endsWith("$boolean")) {
name = variable.substring(0, variable.length() - 8);
createObjectType = "boolean";
} else if (variable.endsWith("$integer")) {
name = variable.substring(0, variable.length() - 8);
createObjectType = "integer";
} else if (variable.endsWith("$long")) {
name = variable.substring(0, variable.length() - 5);
createObjectType = "long";
} else if (variable.endsWith("$double")) {
name = variable.substring(0, variable.length() - 7);
createObjectType = "double";
} else if (variable.endsWith("$bigDecimal")) {
name = variable.substring(0, variable.length() - 11);
createObjectType = "bigDecimal";
}
}
if (variables instanceof LocalizedMap<?>) {
if (locale == null) {
locale = (Locale) variables.get(LOCALIZED_MAP_LOCALE_KEY);
if (locale == null) {
locale = (Locale) variables.get("locale");
if (locale == null) {
locale = Locale.getDefault();
}
}
}
obj = ((LocalizedMap<?>) variables).get(name, locale);
} else {
obj = variables.get(name);
}
if (obj != null) {
return obj;
}
if (createObjectType != null) {
if ("string".equals(createObjectType)) {
return "";
} else if ("null".equals(createObjectType)) {
return null;
} else if ("boolean".equals(createObjectType)) {
return Boolean.FALSE;
} else if ("integer".equals(createObjectType)) {
return 0;
} else if ("long".equals(createObjectType)) {
return 0L;
} else if ("double".equals(createObjectType)) {
return (double) 0;
} else if ("bigDecimal".equals(createObjectType)) {
return BigDecimal.ZERO;
}
}
return null;
}
}