Java Examples for org.mvel2.MVEL
The following java examples will help you to understand the usage of org.mvel2.MVEL. These source code samples are taken from different open source projects.
Example 1
| Project: JavaStudy-master File: TestRPN.java View source code |
/**
* 测试表达�效率
*/
private static void speed() {
System.out.println("2.计算速度:");
int times = 10_0000;
String exp = "1000+100.0*99-(600.0-3*15)/(((68-9)-3)*2-100)+10000.0/7*71";
System.out.println("Answer:" + (1000 + 100.0 * 99 - (600.0 - 3 * 15) / (((68 - 9) - 3) * 2 - 100) + 10000.0 / 7 * 71));
System.out.println("RPN:" + ReversePolishNotation.calculate(exp));
System.out.println("MVEL:" + MVEL.eval(exp));
System.out.println("Fast-EL:" + FelEngine.instance.eval(exp));
System.out.println("Aviator:" + AviatorEvaluator.execute(exp));
long time = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
ReversePolishNotation.calculate(exp);
}
System.out.println("逆波兰表达�耗时:" + (System.currentTimeMillis() - time) + "ms");
long time1 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
MVEL.eval(exp);
}
long time2 = System.currentTimeMillis();
System.out.println("MVEL耗时: " + (time2 - time1) + " ms");
for (int i = 0; i < times; i++) {
FelEngine.instance.eval(exp);
}
long time3 = System.currentTimeMillis();
System.out.println("Fast-EL耗时: " + (time3 - time2) + " ms");
for (int i = 0; i < times; i++) {
AviatorEvaluator.execute(exp);
}
long time4 = System.currentTimeMillis();
System.out.println("Aviator耗时: " + (time4 - time3) + " ms");
}Example 2
| Project: mvel-master File: TemplateTests.java View source code |
public void testEvalMVEL220() {
Map<String, Object> vars = setupVarsMVEL220();
System.out.println("Evaluation=====================");
for (String expr : testCasesMVEL220) {
System.out.println("Evaluating '" + expr + "': ......");
Object ret = MVEL.eval(expr, vars);
System.out.println("'" + expr + " ' = " + ret.toString());
assertNotNull(ret);
}
System.out.println("Evaluation=====================");
}Example 3
| Project: rife-master File: FilteredTagProcessorMvel.java View source code |
public Object processExpression(Template template, Class rootType, String rootName, Object rootValue, String expression, Map<String, Object> context) throws Exception {
Serializable compiled = (Serializable) template.getCacheObject(expression);
if (null == compiled) {
compiled = MVEL.compileExpression(expression);
template.cacheObject(expression, compiled);
}
return MVEL.executeExpression(compiled, rootValue, context, Boolean.class);
}Example 4
| Project: JustAnotherSpawner-master File: ReflectiveAccessorOptimizer.java View source code |
public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType) {
this.rootNode = this.currNode = null;
this.expr = property;
this.start = start;
this.first = true;
this.length = start + offset;
this.ctx = ctx;
this.thisRef = thisRef;
this.variableFactory = factory;
this.ingressType = ingressType;
char[] root = null;
int split = findLastUnion();
PropertyVerifier verifier = new PropertyVerifier(property, this.pCtx = pCtx);
if (split != -1) {
root = subset(property, 0, split++);
//todo: must use the property verifier.
property = subset(property, split, property.length - split);
}
if (root != null) {
this.length = end = (this.expr = root).length;
compileGetChain();
ctx = this.val;
}
if (ctx == null) {
throw new PropertyAccessException("could not access property: " + new String(property, this.start, Math.min(length, property.length)) + "; parent is null: " + new String(expr), expr, this.start);
}
try {
this.length = end = (this.expr = property).length;
int st;
this.cursor = st = 0;
skipWhitespace();
if (collection) {
st = cursor;
if (cursor == end)
throw new PropertyAccessException("unterminated '['", expr, this.start);
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['", expr, this.start);
String ex = new String(property, st, cursor - st);
if (ctx instanceof Map) {
if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Map.class)) {
propHandlerSet(ex, ctx, Map.class, value);
} else {
//noinspection unchecked
((Map) ctx).put(eval(ex, ctx, variableFactory), convert(value, returnType = verifier.analyze()));
addAccessorNode(new MapAccessorNest(ex, returnType));
}
return rootNode;
} else if (ctx instanceof List) {
if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(List.class)) {
propHandlerSet(ex, ctx, List.class, value);
} else {
//noinspection unchecked
((List) ctx).set(eval(ex, ctx, variableFactory, Integer.class), convert(value, returnType = verifier.analyze()));
addAccessorNode(new ListAccessorNest(ex, returnType));
}
return rootNode;
} else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) {
propHandlerSet(ex, ctx, ctx.getClass(), value);
return rootNode;
} else if (ctx.getClass().isArray()) {
if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Array.class)) {
propHandlerSet(ex, ctx, Array.class, value);
} else {
//noinspection unchecked
Array.set(ctx, eval(ex, ctx, variableFactory, Integer.class), convert(value, getBaseComponentType(ctx.getClass())));
addAccessorNode(new ArrayAccessorNest(ex));
}
return rootNode;
} else {
throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass(), expr, this.st);
}
} else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) {
propHandlerSet(new String(property), ctx, ctx.getClass(), value);
return rootNode;
}
String tk = new String(property, 0, length).trim();
if (hasSetListeners()) {
notifySetListeners(ctx, tk, variableFactory, value);
addAccessorNode(new Notify(tk));
}
Member member = getFieldOrWriteAccessor(ctx.getClass(), tk, value == null ? null : ingressType);
if (member instanceof Field) {
Field fld = (Field) member;
if (value != null && !fld.getType().isAssignableFrom(value.getClass())) {
if (!canConvert(fld.getType(), value.getClass())) {
throw new CompileException("cannot convert type: " + value.getClass() + ": to " + fld.getType(), this.expr, this.start);
}
fld.set(ctx, convert(value, fld.getType()));
addAccessorNode(new DynamicFieldAccessor(fld));
} else if (value == null && fld.getType().isPrimitive()) {
fld.set(ctx, PropertyTools.getPrimitiveInitialValue(fld.getType()));
addAccessorNode(new FieldAccessor(fld));
} else {
fld.set(ctx, value);
addAccessorNode(new FieldAccessor(fld));
}
} else if (member != null) {
Method meth = (Method) member;
if (value != null && !meth.getParameterTypes()[0].isAssignableFrom(value.getClass())) {
if (!canConvert(meth.getParameterTypes()[0], value.getClass())) {
throw new CompileException("cannot convert type: " + value.getClass() + ": to " + meth.getParameterTypes()[0], this.expr, this.start);
}
meth.invoke(ctx, convert(value, meth.getParameterTypes()[0]));
} else if (value == null && meth.getParameterTypes()[0].isPrimitive()) {
meth.invoke(ctx, PropertyTools.getPrimitiveInitialValue(meth.getParameterTypes()[0]));
} else {
meth.invoke(ctx, value);
}
addAccessorNode(new SetterAccessor(meth));
} else if (ctx instanceof Map) {
//noinspection unchecked
((Map) ctx).put(tk, value);
addAccessorNode(new MapAccessor(tk));
} else {
throw new PropertyAccessException("could not access property (" + tk + ") in: " + ingressType.getName(), this.expr, this.start);
}
} catch (InvocationTargetException e) {
throw new PropertyAccessException("could not access property: " + new String(property), this.expr, st, e);
} catch (IllegalAccessException e) {
throw new PropertyAccessException("could not access property: " + new String(property), this.expr, st, e);
} catch (IllegalArgumentException e) {
throw new PropertyAccessException("error binding property: " + new String(property) + " (value <<" + value + ">>::" + (value == null ? "null" : value.getClass().getCanonicalName()) + ")", this.expr, st, e);
}
return rootNode;
}Example 5
| Project: squirrel-master File: MvelScriptManagerImpl.java View source code |
@Override
public <T> T eval(String script, Object context, Class<T> returnType) {
Object evaluateResult = null;
if (getCompiledExpression().containsKey(script)) {
Object exp = getCompiledExpression().get(script);
evaluateResult = MVEL.executeExpression(exp, context);
} else {
evaluateResult = MVEL.eval(script, context);
}
return returnType.cast(evaluateResult);
}Example 6
| Project: Asper-master File: MVELInvoker.java View source code |
public static void analysisCompile(String expression, Object parserContext) throws InvocationTargetException {
assertClasspath();
Method method;
try {
method = mvelClass.getMethod("analysisCompile", new Class[] { String.class, parserContextClass });
} catch (Exception e) {
throw new EPException("Failed to find MVEL method: " + e.getMessage(), e);
}
try {
method.invoke(null, new Object[] { expression, parserContext });
} catch (IllegalAccessException e) {
throw new EPException("Failed to access MVEL method: " + e.getMessage(), e);
}
}Example 7
| Project: drools-chance-master File: HumanTaskServiceFactory.java View source code |
public static Object eval(String str, Map vars) {
ExpressionCompiler compiler = new ExpressionCompiler(str.trim());
ParserContext context = new ParserContext();
context.addPackageImport("org.jbpm.task");
context.addPackageImport("java.util");
context.addImport("AccessType", AccessType.class);
context.addImport("AllowedToDelegate", AllowedToDelegate.class);
context.addImport("Attachment", Attachment.class);
context.addImport("BooleanExpression", BooleanExpression.class);
context.addImport("Comment", Comment.class);
context.addImport("Deadline", Deadline.class);
context.addImport("Deadlines", Deadlines.class);
context.addImport("Delegation", Delegation.class);
context.addImport("Escalation", Escalation.class);
context.addImport("Group", Group.class);
context.addImport("I18NText", I18NText.class);
context.addImport("Notification", Notification.class);
context.addImport("OrganizationalEntity", OrganizationalEntity.class);
context.addImport("PeopleAssignments", PeopleAssignments.class);
context.addImport("Reassignment", Reassignment.class);
context.addImport("Status", Status.class);
context.addImport("Task", Task.class);
context.addImport("TaskData", TaskData.class);
context.addImport("TaskSummary", TaskSummary.class);
context.addImport("User", User.class);
return MVEL.executeExpression(compiler.compile(context), vars);
}Example 8
| Project: drools-core-master File: ReteDslTestEngine.java View source code |
private void betaNode(DslStep step, BetaNode node, Map<String, Object> context, InternalWorkingMemory wm) {
try {
List<String[]> cmds = step.getCommands();
List<InternalFactHandle> handles = (List<InternalFactHandle>) context.get("Handles");
BetaMemory memory = null;
if (node instanceof AccumulateNode) {
AccumulateMemory accmem = (AccumulateMemory) wm.getNodeMemory(node);
memory = accmem.betaMemory;
} else {
memory = (BetaMemory) wm.getNodeMemory(node);
}
for (String[] cmd : cmds) {
if (cmd[0].equals("leftMemory")) {
String args = cmd[1];
String listString = args.replaceAll("h(\\d+)", "h[$1]");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("h", handles);
List<?> expectedLeftTuples = (List<?>) MVEL.eval(listString, vars);
LeftTupleMemory leftMemory = memory.getLeftTupleMemory();
if (expectedLeftTuples.isEmpty() && leftMemory.size() != 0) {
throw new AssertionFailedError("line " + step.getLine() + ": left Memory expected [] actually " + print(leftMemory));
} else if (expectedLeftTuples.isEmpty() && leftMemory.size() == 0) {
return;
}
// we always lookup from the first element, in case it's
// indexed
List<InternalFactHandle> first = (List<InternalFactHandle>) expectedLeftTuples.get(0);
LeftTuple firstTuple = new LeftTuple(first.get(0), null, false);
for (int i = 1; i < first.size(); i++) {
firstTuple = new LeftTuple(firstTuple, null, false);
}
List<LeftTuple> leftTuples = new ArrayList<LeftTuple>();
for (LeftTuple leftTuple = memory.getLeftTupleMemory().getFirst(firstTuple); leftTuple != null; leftTuple = (LeftTuple) leftTuple.getNext()) {
leftTuples.add(leftTuple);
}
// lgomes: Need to sort the tuples here, because we might have asserted things
// in the wrong order, because linking a node's side means populating its memory
// from the OTN which stores things in a hash-set, so insertion order is not kept.
Collections.sort(leftTuples, new LeftTupleComparator());
List<List<InternalFactHandle>> actualLeftTuples = getHandlesList(leftTuples);
if (!expectedLeftTuples.equals(actualLeftTuples)) {
throw new AssertionFailedError("line " + step.getLine() + ": left Memory expected " + print(expectedLeftTuples) + " actually " + print(actualLeftTuples));
}
} else if (cmd[0].equals("rightMemory")) {
String args = cmd[1];
String listString = args.replaceAll("h(\\d+)", "h[$1]");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("h", handles);
List<?> expectedFactHandles = (List<?>) MVEL.eval(listString, vars);
RightTupleMemory rightMemory = memory.getRightTupleMemory();
if (expectedFactHandles.isEmpty() && rightMemory.size() != 0) {
throw new AssertionFailedError("line " + step.getLine() + ": right Memory expected [] actually " + rightMemory);
} else if (expectedFactHandles.isEmpty() && rightMemory.size() == 0) {
return;
}
RightTuple first = new RightTuple((InternalFactHandle) expectedFactHandles.get(0));
List<RightTuple> actualRightTuples = new ArrayList<RightTuple>();
for (RightTuple rightTuple = memory.getRightTupleMemory().getFirst(first); rightTuple != null; rightTuple = (RightTuple) rightTuple.getNext()) {
actualRightTuples.add(rightTuple);
}
if (expectedFactHandles.size() != actualRightTuples.size()) {
throw new AssertionFailedError("line " + step.getLine() + ": right Memory expected " + print(expectedFactHandles) + " actually " + print(actualRightTuples));
}
for (int i = 0, length = actualRightTuples.size(); i < length; i++) {
if (expectedFactHandles.get(i) != actualRightTuples.get(i).getFactHandle()) {
throw new AssertionFailedError("line " + step.getLine() + ": right Memory expected [" + print(expectedFactHandles) + "] actually [" + print(actualRightTuples) + "]");
}
}
} else {
throw new IllegalArgumentException("line " + step.getLine() + ": command does not exist " + Arrays.toString(cmd));
}
}
} catch (Exception e) {
throw new IllegalArgumentException("line " + step.getLine() + ": unable to execute step " + step, e);
}
}Example 9
| Project: drools-master File: MiscTest.java View source code |
@Test
public void testJBRULES3111() {
String str = "package org.drools.compiler\n" + "declare Bool123\n" + " bool1 : boolean\n" + " bool2 : boolean\n" + " bool3 : boolean\n" + "end\n" + "declare Thing\n" + " name : String\n" + " bool123 : Bool123\n" + "end\n" + "rule kickOff\n" + "when\n" + "then\n" + " insert( new Thing( \"one\", new Bool123( true, false, false ) ) );\n" + " insert( new Thing( \"two\", new Bool123( false, false, false ) ) );\n" + " insert( new Thing( \"three\", new Bool123( false, false, false ) ) );\n" + "end\n" + "rule r1\n" + "when\n" + " $t: Thing( bool123.bool1 == true )\n" + "then\n" + "end\n" + "rule r2\n" + "when\n" + " $t: Thing( bool123.bool2 == true )\n" + "then\n" + "end\n" + "rule r3\n" + "when\n" + " $t: Thing( bool123.bool3 == true )\n" + "then\n" + "end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
ksession.addEventListener(ael);
int rulesFired = ksession.fireAllRules();
assertEquals(2, rulesFired);
ArgumentCaptor<org.kie.api.event.rule.AfterMatchFiredEvent> captor = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
verify(ael, times(2)).afterMatchFired(captor.capture());
List<org.kie.api.event.rule.AfterMatchFiredEvent> aafe = captor.getAllValues();
Assert.assertThat(aafe.get(0).getMatch().getRule().getName(), is("kickOff"));
Assert.assertThat(aafe.get(1).getMatch().getRule().getName(), is("r1"));
Object value = aafe.get(1).getMatch().getDeclarationValue("$t");
String name = (String) MVEL.eval("$t.name", Collections.singletonMap("$t", value));
Assert.assertThat(name, is("one"));
}Example 10
| Project: droolsjbpm-master File: ServiceImplementation.java View source code |
@WebRemote
@Restrict("#{identity.loggedIn}")
public String[] loadDropDownExpression(String[] valuePairs, String expression) {
Map<String, String> context = new HashMap<String, String>();
for (int i = 0; i < valuePairs.length; i++) {
if (valuePairs[i] == null) {
return new String[0];
}
String[] pair = valuePairs[i].split("=");
context.put(pair[0], pair[1]);
}
// first interpolate the pairs
expression = (String) TemplateRuntime.eval(expression, context);
// now we can eval it for real...
Object result = MVEL.eval(expression);
if (result instanceof String[]) {
return (String[]) result;
} else if (result instanceof List) {
List l = (List) result;
String[] xs = new String[l.size()];
for (int i = 0; i < xs.length; i++) {
Object el = l.get(i);
xs[i] = el.toString();
}
return xs;
} else {
return null;
}
}Example 11
| Project: esper-master File: MVELInvoker.java View source code |
public static void analysisCompile(String expression, Object parserContext, EngineImportService engineImportService) throws InvocationTargetException {
assertClasspath(engineImportService);
Method method;
try {
method = mvelClass.getMethod("analysisCompile", new Class[] { String.class, parserContextClass });
} catch (Exception e) {
throw new EPException("Failed to find MVEL method: " + e.getMessage(), e);
}
try {
method.invoke(null, new Object[] { expression, parserContext });
} catch (IllegalAccessException e) {
throw new EPException("Failed to access MVEL method: " + e.getMessage(), e);
}
}Example 12
| Project: javardices-master File: JptLoopNode.java View source code |
public void render(Map<String, Object> context, Writer out) throws IOException {
if (_compiled_exp == null) {
ParserContext parser_context = ParserContext.create();
Set<Entry<String, Object>> ctx_entries = context.entrySet();
for (Entry<String, Object> entry : ctx_entries) {
parser_context.addInput(entry.getKey(), entry.getValue().getClass());
}
// Compile the expression.
_compiled_exp = MVEL.compileExpression(_repeatElements.getLoopSourceExpression(), parser_context);
}
int child_count = getChildCount();
int increment = _repeatElements.getLoopIncrement();
String loopVar = _repeatElements.getLoopVar();
String pad = _repeatElements.getPadding();
try {
Object collection = MVEL.executeExpression(_compiled_exp, context);
if (collection == null) {
arrayLoop(context, out, new Object[0], child_count, increment, loopVar, pad);
return;
}
if (collection.getClass().isArray()) {
arrayLoop(context, out, (Object[]) collection, child_count, increment, loopVar, pad);
return;
}
if (collection instanceof Collection) {
collectionLoop(context, out, (Collection) collection, child_count, increment, loopVar, pad);
return;
}
if (collection instanceof Iterable) {
iterableLoop(context, out, (Iterable) collection, child_count, increment, loopVar, pad);
return;
}
if (collection instanceof Iterator) {
iteratorLoop(context, out, (Iterator) collection, child_count, increment, loopVar, pad);
return;
}
arrayLoop(context, out, new Object[0], child_count, increment, loopVar, pad);
} catch (Throwable t) {
Throwable r = ErrorAnalyser.findRootCause(t);
throw new RuntimeException(String.format("Error processing JptLoopNode:%nexpression: '%s';%ncontext: %s;%nmessage: '%s'", loopVar, context, r.getMessage()));
}
}Example 13
| Project: monitor-event-tap-master File: EventPredicate.java View source code |
@Override
public boolean apply(Event event) {
if (!event.getType().equals(eventType)) {
return false;
}
if (eventFilter == null) {
return true;
}
try {
// NOTE: null is considered false
return MVEL.executeExpression(expression, event.getData(), Boolean.class) == Boolean.TRUE;
} catch (Exception ignored) {
return false;
}
}Example 14
| Project: Moo-master File: MvelSourcePropertyFactory.java View source code |
@Override
public SourceProperty getSourceProperty(String expressionPrefix, String unprefixedExpression) {
// Because MVEL prefix was used, assume that a failure here is worth reporting right away.
try {
return compileAndReturnProperty(unprefixedExpression);
} catch (ArrayIndexOutOfBoundsException exception) {
throw new MissingSourcePropertyException(expressionPrefix + ":" + unprefixedExpression, exception);
} catch (CompileException exception) {
throw new MissingSourcePropertyException(expressionPrefix + ":" + unprefixedExpression, exception);
}
}Example 15
| Project: n_e_b_u_l_a-master File: TestGet__MVMGet.java View source code |
@Override
public long run() throws Exception {
for (int i = 0; i < max; i++) {
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
result = (Integer) MVEL.executeExpression(compiled, vars);
}
return max * 10;
}Example 16
| Project: rtgov-master File: ActiveCollectionSource.java View source code |
/**
* This method pre-initializes the active collection source
* in situations where it needs to be initialized before
* registration with the manager. This may be required
* where the registration is performed in a different
* contextual classloader than the source was loaded.
*
* @throws Exception Failed to pre-initialize
*/
protected void preInit() throws Exception {
if (!_preinitialized) {
_preinitialized = true;
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Pre-Initializing script=" + _aggregationScript + " compiled=" + _aggregationScriptCompiled);
}
// Only initialize if the script is specified, but not yet compiled
if (_aggregationScript != null && _aggregationScriptCompiled == null) {
java.io.InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(_aggregationScript);
if (is == null) {
LOG.severe(MessageFormat.format(java.util.PropertyResourceBundle.getBundle("active-collection.Messages").getString("ACTIVE-COLLECTION-1"), _aggregationScript));
} else {
byte[] b = new byte[is.available()];
is.read(b);
is.close();
// Compile expression
_aggregationScriptCompiled = MVEL.compileExpression(new String(b));
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Pre-Initializing maintenance script=" + _maintenanceScript + " compiled=" + _maintenanceScriptExpression);
}
// Only initialize if the script is specified, but not yet compiled
if (_maintenanceScript != null && _maintenanceScriptExpression == null) {
java.io.InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(_maintenanceScript);
if (is == null) {
LOG.severe(MessageFormat.format(java.util.PropertyResourceBundle.getBundle("active-collection.Messages").getString("ACTIVE-COLLECTION-1"), _maintenanceScript));
} else {
byte[] b = new byte[is.available()];
is.read(b);
is.close();
// Compile expression
_maintenanceScriptExpression = MVEL.compileExpression(new String(b));
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Pre-Initializing scheduled script=" + _scheduledScript + " compiled=" + _scheduledScriptExpression);
}
// Only initialize if the script is specified, but not yet compiled
if (_scheduledScript != null && _scheduledScriptExpression == null) {
java.io.InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(_scheduledScript);
if (is == null) {
LOG.severe(MessageFormat.format(java.util.PropertyResourceBundle.getBundle("active-collection.Messages").getString("ACTIVE-COLLECTION-1"), _scheduledScript));
} else {
byte[] b = new byte[is.available()];
is.read(b);
is.close();
// Compile expression
_scheduledScriptExpression = MVEL.compileExpression(new String(b));
}
}
// If active change listeners defined, then pre-init them
if (_listeners.size() > 0) {
for (AbstractActiveChangeListener l : _listeners) {
l.preInit();
}
}
}
}Example 17
| Project: sitebricks-master File: MvelEvaluatorCompiler.java View source code |
public Evaluator compile(String expression) throws ExpressionCompileException {
//do *not* inline
final CompiledExpression compiled = compileExpression(expression);
return new Evaluator() {
@Nullable
public Object evaluate(String expr, Object bean) {
return MVEL.executeExpression(compiled, bean);
}
public void write(String expr, Object bean, Object value) {
//lets use mvel to store an expression
MVEL.setProperty(bean, expr, value);
}
public Object read(String property, Object contextObject) {
return MVEL.getProperty(property, contextObject);
}
};
}Example 18
| Project: xlsmapper-master File: ExpressionLanguageMVELImpl.java View source code |
@Override
public Object evaluate(final String expression, final Map<String, ?> values) {
ArgUtils.notEmpty(expression, "expression");
ArgUtils.notNull(values, "values");
try {
if (logger.isDebugEnabled()) {
logger.debug("Evaluating MVEL expression: {}", expression);
}
Object expr = expressionCache.get(expression);
if (expr == null) {
expr = MVEL.compileExpression(expression, new ParserContext(parserConfiguration));
expressionCache.put(expression, expr);
}
return MVEL.executeExpression(expr, values);
} catch (Exception ex) {
throw new ExpressionEvaluationException(String.format("Evaluating [%s] script with MVEL failed.", expression), ex);
}
}Example 19
| Project: cobarclient-master File: IBatisSqlActionShardingRule.java View source code |
public boolean isDefinedAt(IBatisRoutingFact routingFact) {
Validate.notNull(routingFact);
boolean matches = StringUtils.equals(getTypePattern(), routingFact.getAction());
if (matches) {
try {
Map<String, Object> vrs = new HashMap<String, Object>();
vrs.putAll(getFunctionMap());
// add top object reference for expression
vrs.put("$ROOT", routingFact.getArgument());
VariableResolverFactory vrfactory = new MapVariableResolverFactory(vrs);
if (MVEL.evalToBoolean(getAttributePattern(), routingFact.getArgument(), vrfactory)) {
return true;
}
} catch (Throwable t) {
logger.info("failed to evaluate attribute expression:'{}' with context object:'{}'\n{}", new Object[] { getAttributePattern(), routingFact.getArgument(), t });
}
}
return false;
}Example 20
| Project: droolsjbpm-integration-master File: ReflectiveMatcherAssertImpl.java View source code |
public void eval(Context context) {
StringBuilder sbuilder = new StringBuilder();
for (String str : factory.getStaticImports()) {
sbuilder.append("import_static ");
sbuilder.append(str);
sbuilder.append(";\n");
}
sbuilder.append("assertThat(");
if (text != null) {
sbuilder.append(text);
} else {
sbuilder.append(actual);
sbuilder.append(", ");
matcher.build(sbuilder);
}
sbuilder.append(")");
sbuilder.append(";\n");
ParserContext pctx = new ParserContext();
//pctx.setStrongTyping( true );
String t = sbuilder.toString();
//System.out.println( t );
ParserContext parserCtx = new ParserContext();
MVEL.compileExpression(t, parserCtx);
Map<String, Class> inputs = parserCtx.getInputs();
Map<String, Object> vars = new HashMap<String, Object>();
for (String name : inputs.keySet()) {
vars.put(name, context.get(name));
}
try {
Object o = MVEL.compileExpression(sbuilder.toString(), pctx);
MVELSafeHelper.getEvaluator().executeExpression(o, vars);
} catch (Exception e) {
Throwable unwrapped = e.getCause();
if (unwrapped != null && unwrapped.getCause() != null) {
unwrapped = unwrapped.getCause();
}
if (unwrapped instanceof AssertionError) {
throw (AssertionError) e.getCause().getCause();
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
}
}Example 21
| Project: jboss-as7-jbpm-module-master File: TaskService.java View source code |
public Object eval(String str, Map vars) {
ParserConfiguration pconf = new ParserConfiguration();
pconf.addPackageImport("org.jbpm.task");
pconf.addPackageImport("org.jbpm.task.service");
pconf.addPackageImport("org.jbpm.task.query");
pconf.addPackageImport("java.util");
for (String entry : getInputs().keySet()) {
pconf.addImport(entry, getInputs().get(entry));
}
ParserContext context = new ParserContext(pconf);
Serializable s = MVEL.compileExpression(str.trim(), context);
return MVEL.executeExpression(s, vars);
}Example 22
| Project: jbpm-master File: JbpmBpmn2TestCase.java View source code |
public Object eval(String str, Map vars) {
ParserContext context = new ParserContext();
context.addPackageImport("org.jbpm.task");
context.addPackageImport("org.jbpm.task.service");
context.addPackageImport("org.jbpm.task.query");
context.addPackageImport("java.util");
vars.put("now", new Date());
return MVELSafeHelper.getEvaluator().executeExpression(MVEL.compileExpression(str, context), vars);
}Example 23
| Project: processFlowProvision-master File: BaseKnowledgeSessionBean.java View source code |
// TO-DO: somehow add ksession via mvel to workItemhandlers defined in session template
private SessionTemplate parseSessionTemplateString(StatefulKnowledgeSession ksession) {
ParserConfiguration pconf = new ParserConfiguration();
pconf.addImport("SessionTemplate", SessionTemplate.class);
ParserContext context = new ParserContext(pconf);
Serializable s = MVEL.compileExpression(templateString.trim(), context);
try {
Map vars = new HashMap();
vars.put(IKnowledgeSession.KSESSION, ksession);
SessionTemplate sTemplate = (SessionTemplate) MVEL.executeExpression(s, vars);
sessionTemplateInstantiationAttempts = 1;
return sTemplate;
} catch (Throwable x) {
sessionTemplateInstantiationAttempts = -1;
x.printStackTrace();
log.error("newSessionTemplate() following exception thrown \n\t" + x.getLocalizedMessage() + "\n : with session template string = \n\n" + templateString);
return null;
}
}Example 24
| Project: pummel-master File: Step.java View source code |
public Void call() throws Exception {
List<String> urls = Lists.newArrayList();
final BufferedReader in;
if (urlFile != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile)));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (maxRequests >= 0) {
if (maxRequests == 0) {
break;
} else if (maxRequests > 0) {
maxRequests--;
}
}
urls.add(line);
}
if (labels) {
System.out.printf("clients\ttp%.1f\tmean\treqs/sec\n", percentile);
}
int concurrency = start;
do {
DescriptiveStatistics stats = new Fight(concurrency, urls).call();
System.out.printf("%d\t%.2f\t%.2f\t%.2f\n", concurrency, stats.getPercentile(percentile), stats.getMean(), (1000 / stats.getMean()) * concurrency);
Map<String, Integer> vals = ImmutableMap.of("c", concurrency);
concurrency = (Integer) MVEL.eval(stepFunction, vals);
} while (concurrency < limit);
return null;
}Example 25
| Project: drools-wb-master File: WorkDefinitionsParser.java View source code |
/**
* Parse a MVEL String into WorkDefinitions
* @param workItemDefinitions
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, WorkDefinition> parse(final List<String> workItemDefinitions) {
final Map<String, WorkDefinition> workDefinitions = new HashMap<String, WorkDefinition>();
//Add Data-type imports, in-case they are missing from definition
final ParserContext context = new ParserContext();
//Compile expression and convert String
for (String workItemDefinition : workItemDefinitions) {
final Serializable compiled = MVEL.compileExpression(workItemDefinition, context);
final Object result = MVELSafeHelper.getEvaluator().executeExpression(compiled, new HashMap());
final List<Map<String, Object>> workDefinitionsMap = (List<Map<String, Object>>) result;
//Populate model
if (workDefinitionsMap != null) {
for (Map<String, Object> workDefinitionMap : workDefinitionsMap) {
if (workDefinitionMap != null) {
final WorkDefinitionImpl workDefinition = new WorkDefinitionImpl();
workDefinition.setName((String) workDefinitionMap.get("name"));
workDefinition.setDisplayName((String) workDefinitionMap.get("displayName"));
workDefinition.setIcon((String) workDefinitionMap.get("icon"));
workDefinition.setCustomEditor((String) workDefinitionMap.get("customEditor"));
final Set<ParameterDefinition> parameters = new HashSet<ParameterDefinition>();
if (workDefinitionMap.get("parameters") != null) {
final Map<String, DataType> parameterMap = (Map<String, DataType>) workDefinitionMap.get("parameters");
if (parameterMap != null) {
for (Map.Entry<String, DataType> entry : parameterMap.entrySet()) {
parameters.add(new ParameterDefinitionImpl(entry.getKey(), entry.getValue()));
}
}
workDefinition.setParameters(parameters);
}
if (workDefinitionMap.get("results") != null) {
final Set<ParameterDefinition> results = new HashSet<ParameterDefinition>();
final Map<String, DataType> resultMap = (Map<String, DataType>) workDefinitionMap.get("results");
if (resultMap != null) {
for (Map.Entry<String, DataType> entry : resultMap.entrySet()) {
results.add(new ParameterDefinitionImpl(entry.getKey(), entry.getValue()));
}
}
workDefinition.setResults(results);
}
if (workDefinitionMap.get("defaultHandler") != null) {
workDefinition.setDefaultHandler((String) workDefinitionMap.get("defaultHandler"));
}
if (workDefinitionMap.get("dependencies") != null) {
workDefinition.setDependencies(((List<String>) workDefinitionMap.get("dependencies")).toArray(new String[0]));
}
workDefinitions.put(workDefinition.getName(), workDefinition);
}
}
}
}
return workDefinitions;
}Example 26
| Project: funj-master File: ReflectionTools.java View source code |
/**
* get the value of a property
* @param obj container object
* @param propertyName name of property
* @param <OBJ> generic type of container object
* @param <PROP> generic type of property
* @return the value of the property
* @throws IllegalArgumentException if obj is null, or if propertyName is null,
* empty, blank, or does not exist.
*/
@SuppressWarnings("unchecked")
public static <OBJ, PROP> PROP getPropertyValue(OBJ obj, String propertyName) {
if (obj == null) {
throw new IllegalArgumentException("The container object cannot be null");
}
if (StringUtils.isBlank(propertyName)) {
throw new IllegalArgumentException("propertyName is required");
}
try {
return (PROP) MVEL.eval(propertyName, obj);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}Example 27
| Project: rewritehtml-master File: HtmlTranslationFilter.java View source code |
private String replace(String what, String value, List<Replacement> replacements, Object... args) {
String originalValue = value;
for (Replacement replacement : replacements) {
switch(replacement.getType()) {
case ReplaceAll:
value = value.replace(replacement.getFrom(), replacement.getEffectiveTo());
break;
case ReplaceFirst:
value = value.replaceFirst(Pattern.quote(replacement.getFrom()), replacement.getEffectiveTo());
break;
case ReplaceAllRegex:
value = value.replaceAll(replacement.getFrom(), replacement.getEffectiveTo());
break;
case ReplaceFirstRegex:
value = value.replaceFirst(replacement.getFrom(), replacement.getEffectiveTo());
break;
case MVEL:
try {
Map<String, Object> vars = new HashMap<String, Object>();
for (int i = 0; i < args.length; i += 2) {
vars.put((String) args[i], args[i + 1]);
}
if (this.context != null) {
vars.put("context", this.context);
}
vars.put("value", value);
Serializable expression = mvelExpressionCache.get(replacement);
if (expression == null) {
mvelExpressionCache.put(replacement, expression = MVEL.compileExpression(replacement.getEffectiveTo()));
}
log.debug("Evaluating {} for replacement using expression {} and vars {}: {} {}", replacement.getEffectiveTo(), expression, vars, what, value);
Object rvalue = MVEL.executeExpression(expression, vars);
if (rvalue == null) {
return null;
}
value = rvalue.toString();
} catch (Exception e) {
log.warn("Unexpected exception occurred while evaluating {} with replacement expression: {}", what, replacement.getEffectiveTo(), e);
}
break;
}
}
if (originalValue == null && value != null) {
log.debug("Provided initial value of {} as {}", what, value);
} else if (!originalValue.equals(value)) {
log.debug("Performed replacement of {} from {} to {}", what, originalValue, value);
}
return value;
}Example 28
| Project: seam-forge-master File: Parse.java View source code |
public static String executeScript(ScriptNode node, final FSHRuntime runtime) {
String toExec = queueToString(new AutoReducingQueue(node.getNest(), runtime));
//System.out.println("\n----\n" + toExec + "\n========\n");
Object r = MVEL.eval(toExec, runtime, runtime.getShell().getProperties());
if (r == null) {
return null;
} else {
return String.valueOf(r);
}
}Example 29
| Project: seam-mvc-master File: BindingNode.java View source code |
@Override
public Object eval(final TemplateRuntime runtime, final TemplateOutputStream appender, final Object ctx, final VariableResolverFactory factory) {
/*
* TODO this needs to be a compile time step that stores bindings, possibly with a Tree-visitor (See:
* template.getRoot())
*/
String line = new String(contents);
Queue<String> tokens = Tokenizer.tokenize(DELIM, line);
if (tokens.size() != 2) {
throw new CompileException("@" + getName() + "{ param " + DELIM + " bean.field } requires two parameters, instead received @bind{" + line + "}", new char[] {}, 0);
}
String name = tokens.remove().trim();
String el = tokens.remove().trim();
Object result = "";
try {
el = MVEL.eval(el, ctx, factory, String.class);
result = expressions.evaluateValueExpression(expressions.toExpression(el));
if (result == null) {
result = "";
}
} catch (PropertyNotFoundException e) {
}
bindings.put(name, el);
appender.append("name=\"" + name + "\" value=\"" + result.toString() + "\"");
return next != null ? next.eval(runtime, appender, ctx, factory) : null;
}Example 30
| Project: smooks-master File: MVELExpressionEvaluator.java View source code |
public Object exec(final Object contextObject, Map<String, Object> variableMap) throws ExpressionEvaluationException {
try {
if (containsVariablesVariable && contextObject instanceof Map<?, ?>) {
// We use the root ResolverFactories so that variables created in MVEL Scripts are put in the empty HashMap
// of the second VariableResolverFactory and not in the contextObject Map.
MapVariableResolverFactory rootResolverFactory = new MapVariableResolverFactory(variableMap);
MapVariableResolverFactory contextVariableResolverFactory = new MapVariableResolverFactory((Map<?, ?>) contextObject);
rootResolverFactory.setNextFactory(contextVariableResolverFactory);
// The VARS variable contains the MVELVariables object which get access to root ResolverFactory to be able to
// do look in the variables of the resolver factory
rootResolverFactory.createVariable(MVEL_VARIABLES_VARIABLE_NAME, new MVELVariables(rootResolverFactory));
if (toType != null) {
return DataConversion.convert(MVEL.executeExpression(compiled, rootResolverFactory), toType);
} else {
return MVEL.executeExpression(compiled, rootResolverFactory);
}
} else {
if (toType != null) {
return DataConversion.convert(MVEL.executeExpression(compiled, contextObject, new MapVariableResolverFactory(variableMap)), toType);
} else {
return MVEL.executeExpression(compiled, contextObject, new MapVariableResolverFactory(variableMap));
}
}
} catch (Exception e) {
String msg = "Error evaluating MVEL expression '" + expression + "' against object type '" + contextObject.getClass().getName() + "'. " + "Common issues include:" + "\n\t\t1. Referencing a variable that is not bound into the context." + " In this case use the 'isdef' operator to check if the variable is bound in the context." + "\n\t\t2. Invalid expression reference to a List/Array based variable token. Example List/Array referencing expression token: 'order.orderItems[0].productId'.";
throw new ExpressionEvaluationException(msg, e);
}
}Example 31
| Project: unomi-master File: ActionExecutorDispatcher.java View source code |
@SuppressWarnings("unchecked")
private Map<String, Object> parseMap(Event event, Map<String, Object> map) {
Map<String, Object> values = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
if (value instanceof String) {
String s = (String) value;
try {
if (s.startsWith("profileProperty::")) {
value = PropertyUtils.getProperty(event.getProfile(), "properties." + StringUtils.substringAfter(s, "profileProperty::"));
} else if (s.startsWith("simpleProfileProperty::")) {
value = event.getProfile().getProperty(StringUtils.substringAfter(s, "simpleProfileProperty::"));
} else if (s.startsWith("sessionProperty::")) {
value = PropertyUtils.getProperty(event.getSession(), "properties." + StringUtils.substringAfter(s, "sessionProperty::"));
} else if (s.startsWith("simpleSessionProperty::")) {
value = event.getSession().getProperty(StringUtils.substringAfter(s, "simpleSessionProperty::"));
} else if (s.startsWith("eventProperty::")) {
value = PropertyUtils.getProperty(event, StringUtils.substringAfter(s, "eventProperty::"));
} else if (s.startsWith("simpleEventProperty::")) {
value = event.getProperty(StringUtils.substringAfter(s, "simpleEventProperty::"));
} else if (s.startsWith("script::")) {
String script = StringUtils.substringAfter(s, "script::");
if (!mvelExpressions.containsKey(script)) {
mvelExpressions.put(script, MVEL.compileExpression(script));
}
Map<String, Object> ctx = new HashMap<String, Object>();
ctx.put("event", event);
ctx.put("session", event.getSession());
ctx.put("profile", event.getProfile());
value = MVEL.executeExpression(mvelExpressions.get(script), ctx);
}
} catch (UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
} else if (value instanceof Map) {
value = parseMap(event, (Map<String, Object>) value);
}
values.put(entry.getKey(), value);
}
return values;
}Example 32
| Project: wb-master File: WorkDefinitionsParser.java View source code |
/**
* Parse a MVEL String into WorkDefinitions
* @param workItemDefinitions
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, WorkDefinition> parse(final List<String> workItemDefinitions) {
final Map<String, WorkDefinition> workDefinitions = new HashMap<String, WorkDefinition>();
//Add Data-type imports, in-case they are missing from definition
final ParserContext context = new ParserContext();
//Compile expression and convert String
for (String workItemDefinition : workItemDefinitions) {
final Serializable compiled = MVEL.compileExpression(workItemDefinition, context);
final Object result = MVELSafeHelper.getEvaluator().executeExpression(compiled, new HashMap());
final List<Map<String, Object>> workDefinitionsMap = (List<Map<String, Object>>) result;
//Populate model
if (workDefinitionsMap != null) {
for (Map<String, Object> workDefinitionMap : workDefinitionsMap) {
if (workDefinitionMap != null) {
final WorkDefinitionImpl workDefinition = new WorkDefinitionImpl();
workDefinition.setName((String) workDefinitionMap.get("name"));
workDefinition.setDisplayName((String) workDefinitionMap.get("displayName"));
workDefinition.setIcon((String) workDefinitionMap.get("icon"));
workDefinition.setCustomEditor((String) workDefinitionMap.get("customEditor"));
final Set<ParameterDefinition> parameters = new HashSet<ParameterDefinition>();
if (workDefinitionMap.get("parameters") != null) {
final Map<String, DataType> parameterMap = (Map<String, DataType>) workDefinitionMap.get("parameters");
if (parameterMap != null) {
for (Map.Entry<String, DataType> entry : parameterMap.entrySet()) {
parameters.add(new ParameterDefinitionImpl(entry.getKey(), entry.getValue()));
}
}
workDefinition.setParameters(parameters);
}
if (workDefinitionMap.get("results") != null) {
final Set<ParameterDefinition> results = new HashSet<ParameterDefinition>();
final Map<String, DataType> resultMap = (Map<String, DataType>) workDefinitionMap.get("results");
if (resultMap != null) {
for (Map.Entry<String, DataType> entry : resultMap.entrySet()) {
results.add(new ParameterDefinitionImpl(entry.getKey(), entry.getValue()));
}
}
workDefinition.setResults(results);
}
if (workDefinitionMap.get("defaultHandler") != null) {
workDefinition.setDefaultHandler((String) workDefinitionMap.get("defaultHandler"));
}
if (workDefinitionMap.get("dependencies") != null) {
workDefinition.setDependencies(((List<String>) workDefinitionMap.get("dependencies")).toArray(new String[0]));
}
workDefinitions.put(workDefinition.getName(), workDefinition);
}
}
}
}
return workDefinitions;
}Example 33
| Project: webjavin-master File: SecureExpression.java View source code |
void compile() {
try {
ParserContext context = new ParserContext();
context.setStrongTyping(true);
context.addInput("user", UserDetails.class);
context.addInput("role", String.class);
int idx = 1;
for (String paramType : paramTypes) {
Class<?> type = PRIMITIVES.get(paramType);
if (type == null) {
type = Javin.getClasses().getClassLoader().loadClass(paramType);
}
context.addInput("param$" + idx, type);
idx++;
}
context.addImport("isAuth", JavinSecurityManager.class.getMethod("_isAuthenticated"));
context.addImport("hasRole", JavinSecurityManager.class.getMethod("_hasRole", String.class));
expression = (ExecutableStatement) MVEL.compileExpression(expressionStr, context);
if (expression.getKnownEgressType() != boolean.class && expression.getKnownEgressType() != Boolean.class) {
throw new JavinRuntimeException("Expression should return boolean");
}
} catch (Exception e) {
throw new JavinRuntimeException("Can't compile secure expression: " + expressionStr, e);
}
}Example 34
| Project: flamingo-mapreduce-master File: AccountingMapper.java View source code |
@Override
protected void setup(Context context) throws IOException, InterruptedException {
configuration = context.getConfiguration();
inputDelimiter = configuration.get("inputDelimiter", Delimiter.COMMA.getDelimiter());
outputDelimiter = configuration.get("outputDelimiter", Delimiter.COMMA.getDelimiter());
columnSize = configuration.getInt("columnSize", -1);
if (columnSize == -1) {
throw new IllegalArgumentException("column size를 ìž…ë ¥í•´ 주세요.");
}
expressionPath = new Path(configuration.get("expression", null));
validateInputFile();
readFromInputFile();
// FIXME validation
compliedExpression = MVEL.compileExpression(expression);
}Example 35
| Project: kie-wb-common-master File: DataEnumLoader.java View source code |
private Map<String, String[]> loadEnum(String mvelSource, ClassLoader classLoader) {
if (mvelSource == null || (mvelSource.trim().equals(""))) {
return Collections.emptyMap();
}
if (mvelSource.startsWith("=")) {
mvelSource = mvelSource.substring(1);
} else {
mvelSource = "[ " + addCommasForNewLines(mvelSource) + " ]";
}
final Object mvelData;
try {
final ParserConfiguration pconf = new ParserConfiguration();
final ParserContext pctx = new ParserContext(pconf);
pconf.setClassLoader(classLoader);
final Serializable compiled = MVEL.compileExpression(mvelSource, pctx);
mvelData = MVELSafeHelper.getEvaluator().executeExpression(compiled, new HashMap<String, Object>());
} catch (RuntimeException e) {
addError("Unable to load enumeration data.");
addError(e.getMessage());
addError("Error type: " + e.getClass().getName());
return Collections.emptyMap();
}
if (!(mvelData instanceof Map<?, ?>)) {
addError("The expression is not a map, it is a " + mvelData.getClass().getName());
return Collections.emptyMap();
}
@SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) mvelData;
Map<String, String[]> newMap = new HashMap<String, String[]>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = makeEnumKey(entry.getKey());
validateKey(key);
Object list = entry.getValue();
if (!(list instanceof List<?> || list instanceof String)) {
if (list == null) {
addError("The item with " + key + " is null.");
} else {
addError("The item with " + key + " is not a list or a string, it is a " + list.getClass().getName());
}
return Collections.emptyMap();
} else if (list instanceof String) {
newMap.put(key, new String[] { (String) list });
} else {
List<?> items = (List<?>) list;
String[] newItems = new String[items.size()];
for (int i = 0; i < items.size(); i++) {
Object listItem = items.get(i);
if (!(listItem instanceof String)) {
newItems[i] = listItem.toString();
} else {
newItems[i] = (String) listItem;
}
}
newMap.put(key, newItems);
}
}
return newMap;
}Example 36
| Project: org.eclipse.ecr-master File: Scripting.java View source code |
public static void run(OperationContext ctx, URL script) throws Exception {
String key = script.toExternalForm();
Script cs = cache.get(key);
if (cs != null) {
cs.eval(ctx);
return;
}
String path = script.getPath();
int p = path.lastIndexOf('.');
if (p == -1) {
throw new OperationException("Script files must have an extension: " + script);
}
String ext = path.substring(p + 1).toLowerCase();
if ("mvel".equals(ext)) {
InputStream in = script.openStream();
try {
Serializable c = MVEL.compileExpression(FileUtils.read(in));
cs = new MvelScript(c);
} finally {
in.close();
}
} else if ("groovy".equals(ext)) {
// Script gs = new GroovyScript();
} else {
throw new OperationException("Unsupported script file: " + script + ". Only mvel and groovy scripts are supported");
}
cache.put(key, cs);
cs.eval(ctx);
}Example 37
| Project: stargate-core-master File: AggregateFunction.java View source code |
@Override
public void init(Options options) {
this.options = options;
int k = 0;
positions = new HashMap<>();
aggregateFields = new String[aggregates.length];
for (AggregateFactory aggregateFactory : aggregates) {
String field = aggregateFactory.getField();
if (field != null) {
aggregateFields[k] = field;
positions.put(field, k++);
}
}
ParserConfiguration parserConfig = getParserConfiguration();
if (groupBy != null) {
this.groupByExpressions = new ExecutableStatement[groupBy.length];
this.simpleExpressions = new boolean[groupBy.length];
groupByFields = new ArrayList<>();
for (int i = 0; i < groupBy.length; i++) {
String groupByField = groupBy[i];
String groupByCol = getGroupBy(groupByField);
boolean isSimpleExpression = options.types.containsKey(getColumnName(groupByCol));
ParserContext parserContext = new ParserContext(parserConfig);
groupByExpressions[i] = (ExecutableStatement) MVEL.compileExpression(groupByField, parserContext);
if (isSimpleExpression) {
simpleExpressions[i] = true;
int pos = k++;
positions.put(groupByCol, pos);
groupByFields.add(groupByCol);
} else {
simpleExpressions[i] = false;
Set<String> keys = parserContext.getInputs().keySet();
for (String key : keys) {
int pos = k++;
boolean canResolve = options.types.containsKey(getColumnName(key));
if (canResolve) {
String groupByColField = getGroupBy(key);
positions.put(key, pos);
groupByFields.add(groupByColField);
}
}
}
}
}
group = new Group(options, aggregates, groupBy, groupByExpressions);
}Example 38
| Project: jhove2-master File: MvelTest.java View source code |
// This test is failing because of a bug in MVEL which has been reported @Test public void testIntegerEvaluations() { // Maximum size of an integer is 2147483647 [0x7fffffff] Integer myInteger = new Integer(Integer.MAX_VALUE); assertEquals(2147483647, myInteger.intValue()); // However MVEL converts this string to a Long // (see org.mvel2.util.ParseTools.numericTest // which returns LONG if string length > 9) Object mvelObject = MVEL.eval("2147483647"); assertEquals("java.lang.Long", mvelObject.getClass().getName()); // Boolean comparison of the Integer object's value // to the string value returns FALSE !!! WRONG !!!. boolean result = MVEL.evalToBoolean("intValue() == 2147483647", myInteger); assertTrue(result); // Why does the comparison return FALSE? because... // a debugging trace shows the following sequence // MVEL.evalToBoolean(String, Object) line: 678 // MVEL.eval(String, Object, Class<T>) line: 218 // MVELInterpretedRuntime.parse() line: 45 // MVELInterpretedRuntime.parseAndExecuteInterpreted() line: 133 // MVELInterpretedRuntime(AbstractParser).arithmeticFunctionReduction(int) line: 2473 // MVELInterpretedRuntime(AbstractParser).reduce() line: 2508 // ExecutionStack.op(int) line: 166 // MathProcessor.doOperations(Object, int, Object) line: 45 // MathProcessor.doOperations(int, Object, int, int, Object) line: 79 // MathProcessor._doOperations(int, Object, int, int, Object) line: 155 // // Here is the full method signature with argument names // MathProcessor._doOperations(int type1, Object val1, int operation, int type2, Object val2) // // At this point the method argument values are: // int type1 = 106 (DataTypes.W_INTEGER) // Object val1 = 2147483647 (java.lang.Integer) // int operation = 18 (Operator.EQUAL) // int type2 = 107 (DataTypes.W_LONG) // Object val2 = 2147483647 (java.lang.Long) // // The _doOperations method makes the following call: // return doBigDecimalArithmetic(getInternalNumberFromType(val1, type1), // operation, // getInternalNumberFromType(val2, type2), // true, box(type2) > box(type1) ? box(type2) : box(type1)); // // Contained in the above are 2 calls to getInternalNumberFromType(Object, int) // The first of these has the argument values: // Object in = 2147483647 (java.lang.Integer) // int type = 106 (DataTypes.W_INTEGER) // // Which causes the following constructor call to be made: // return new InternalNumber((Integer) in, MathContext.DECIMAL32); // // InternalNumber calls its super class constructor: // public BigDecimal(int val, MathContext mc) { // intCompact = val; // if (mc.precision > 0) // roundThis(mc); // } // // The value of mc.precision is 7 for MathContext.DECIMAL32 // // Therefore there is a call to BigDecimal.roundThis(MathContext mc), // which in turn calls BigDecimal.doRound(BigDecimal d, MathContext mc), // which sets: // intVal = null // intCompact = 2147484 // scale = -3 // precision = 10 // // What the hell is going on here? Why is the integer being manipulated in this way? // // The second call to getInternalNumberFromType results in the following: // return new InternalNumber((Long) in, MathContext.DECIMAL64); // // The value of mc.precision is 16 for MathContext.DECIMAL64 // which yields the following settings for the BigDecimal that is created: // intVal = null // intCompact = 2147483647 // scale = 0 // precision = 10 // // Now that the BigDecimals have been created, MVEL can finally enter the // MathProcessor.doBigDecimalArithmetic method which compares like this: // case EQUAL: // return val1.compareTo(val2) == 0 ? Boolean.TRUE : Boolean.FALSE; // // I am having trouble following the logic at this point, // but the bottom line is that the comparison returns FALSE, // which is totally unexpected. }
Example 39
| Project: nuxeo-master File: Scripting.java View source code |
public static void run(OperationContext ctx, URL script) throws OperationException, IOException {
String key = script.toExternalForm();
Script cs = cache.get(key);
if (cs != null) {
cs.eval(ctx);
return;
}
String path = script.getPath();
int p = path.lastIndexOf('.');
if (p == -1) {
throw new OperationException("Script files must have an extension: " + script);
}
String ext = path.substring(p + 1).toLowerCase();
try (InputStream in = script.openStream()) {
if ("mvel".equals(ext)) {
Serializable c = MVEL.compileExpression(IOUtils.toString(in, Charsets.UTF_8));
cs = new MvelScript(c);
} else if ("groovy".equals(ext)) {
cs = new GroovyScript(IOUtils.toString(in, Charsets.UTF_8));
} else {
throw new OperationException("Unsupported script file: " + script + ". Only MVEL and Groovy scripts are supported");
}
cache.put(key, cs);
cs.eval(ctx);
}
}Example 40
| Project: Broadleaf-eCommerce-master File: PomEvaluator.java View source code |
private static void initializeKnownLibraries() {
// Spring
knownLibraries.put("org.springframework", SPRING);
knownLibraries.put("org.springframework.security", SPRING);
knownLibraries.put("org.springframework.social", SPRING);
// Hibernate
knownLibraries.put("org.hibernate", HIBERNATE);
knownLibraries.put("org.hibernate.javax.persistence", HIBERNATE);
// Broadleaf
knownLibraries.put("org.broadleafcommerce", BROADLEAF_OPEN_SOURCE);
knownLibraries.put("com.broadleafcommerce", BROADLEAF_COMMERCIAL);
// Thymeleaf
knownLibraries.put("org.thymeleaf", THYMELEAF);
// JavaX
knownLibraries.put("javax.xml.bind", JAVAX);
knownLibraries.put("javax.mail", JAVAX);
knownLibraries.put("javax.servlet", JAVAX);
knownLibraries.put("javax.servlet.jsp", JAVAX);
knownLibraries.put("javax.validation", JAVAX);
knownLibraries.put("jstl", JAVAX);
// Logging
knownLibraries.put("org.slf4j", SLF4J);
knownLibraries.put("log4j", LOG4J);
// Apache
knownLibraries.put("commons-validator", APACHE_FOUNDATION);
knownLibraries.put("commons-collections", APACHE_FOUNDATION);
knownLibraries.put("commons-beanutils", APACHE_FOUNDATION);
knownLibraries.put("commons-cli", APACHE_FOUNDATION);
knownLibraries.put("commons-fileupload", APACHE_FOUNDATION);
knownLibraries.put("commons-dbcp", APACHE_FOUNDATION);
knownLibraries.put("commons-codec", APACHE_FOUNDATION);
knownLibraries.put("org.apache.commons", APACHE_FOUNDATION);
knownLibraries.put("commons-lang", APACHE_FOUNDATION);
knownLibraries.put("commons-digester", APACHE_FOUNDATION);
knownLibraries.put("commons-logging", APACHE_FOUNDATION);
knownLibraries.put("commons-pool", APACHE_FOUNDATION);
knownLibraries.put("org.apache.geronimo.specs", APACHE_FOUNDATION);
knownLibraries.put("org.apache.solr", APACHE_FOUNDATION);
knownLibraries.put("org.apache.velocity", APACHE_FOUNDATION);
knownLibraries.put("org.apache.xmlbeans", APACHE_FOUNDATION);
knownLibraries.put("taglibs", APACHE_FOUNDATION);
knownLibraries.put("jakarta-regexp", APACHE_FOUNDATION);
knownLibraries.put("ant.ant", APACHE_FOUNDATION);
// Google - Will retire
knownLibraries.put("com.google.gwt", GOOGLE);
knownLibraries.put("com.google.code.gwt-math", GOOGLE);
knownLibraries.put("com.google.code.findbugs", GOOGLE);
knownLibraries.put("net.sf.gwt-widget", GOOGLE);
knownLibraries.put("com.google.guava", GOOGLE);
// CodeHaus - JSON / XML processing
knownLibraries.put("org.codehaus.jackson", JACKSON);
knownLibraries.put("org.codehaus.plexus", PLEXUS);
// ASM
knownLibraries.put("asm", ASM);
// CGLIB
knownLibraries.put("cglib", CGLIB);
// Jersey - used for REST services
knownLibraries.put("com.sun.jersey", JERSEY);
knownLibraries.put("com.sun.jersey.contribs", JERSEY);
// XStream - used for REST services
knownLibraries.put("com.thoughtworks.xstream", JERSEY);
// Joda-Time
knownLibraries.put("joda-time", JODA_TIME);
// Cache
knownLibraries.put("net.sf.jsr107cache", JAVAX);
// Transmorph - Will retire with 3.0
knownLibraries.put("net.sf.transmorph", TRANSMORPH);
// Teracotta software
knownLibraries.put("net.sf.ehcache", EHCACHE);
knownLibraries.put("org.opensymphony.quartz", QUARTZ);
// Antlr
knownLibraries.put("org.antlr", ANTLR);
// Aspect J
knownLibraries.put("org.aspectj", ASPECTJ);
// MVEL
knownLibraries.put("org.mvel", MVEL);
// ORO
knownLibraries.put("oro", ORO);
// Java Assist
knownLibraries.put("org.javassist", JAVA_ASSIST);
// OWASP
knownLibraries.put("org.owasp.antisamy", ANTISAMMY);
// OWASP
knownLibraries.put("com.yahoo.platform.yui", YAHOO);
}Example 41
| Project: BroadleafCommerce-master File: PomEvaluator.java View source code |
private static void initializeKnownLibraries() {
// Spring
knownLibraries.put("org.springframework", SPRING);
knownLibraries.put("org.springframework.security", SPRING);
knownLibraries.put("org.springframework.social", SPRING);
// Hibernate
knownLibraries.put("org.hibernate", HIBERNATE);
knownLibraries.put("org.hibernate.javax.persistence", HIBERNATE);
// Broadleaf
knownLibraries.put("org.broadleafcommerce", BROADLEAF_OPEN_SOURCE);
knownLibraries.put("com.broadleafcommerce", BROADLEAF_COMMERCIAL);
// Thymeleaf
knownLibraries.put("org.thymeleaf", THYMELEAF);
// JavaX
knownLibraries.put("javax.xml.bind", JAVAX);
knownLibraries.put("javax.mail", JAVAX);
knownLibraries.put("javax.servlet", JAVAX);
knownLibraries.put("javax.servlet.jsp", JAVAX);
knownLibraries.put("javax.validation", JAVAX);
knownLibraries.put("jstl", JAVAX);
// Logging
knownLibraries.put("org.slf4j", SLF4J);
knownLibraries.put("log4j", LOG4J);
// Apache
knownLibraries.put("commons-validator", APACHE_FOUNDATION);
knownLibraries.put("commons-collections", APACHE_FOUNDATION);
knownLibraries.put("commons-beanutils", APACHE_FOUNDATION);
knownLibraries.put("commons-cli", APACHE_FOUNDATION);
knownLibraries.put("commons-fileupload", APACHE_FOUNDATION);
knownLibraries.put("commons-dbcp", APACHE_FOUNDATION);
knownLibraries.put("commons-codec", APACHE_FOUNDATION);
knownLibraries.put("org.apache.commons", APACHE_FOUNDATION);
knownLibraries.put("commons-lang", APACHE_FOUNDATION);
knownLibraries.put("commons-digester", APACHE_FOUNDATION);
knownLibraries.put("commons-logging", APACHE_FOUNDATION);
knownLibraries.put("commons-pool", APACHE_FOUNDATION);
knownLibraries.put("org.apache.geronimo.specs", APACHE_FOUNDATION);
knownLibraries.put("org.apache.solr", APACHE_FOUNDATION);
knownLibraries.put("org.apache.velocity", APACHE_FOUNDATION);
knownLibraries.put("org.apache.xmlbeans", APACHE_FOUNDATION);
knownLibraries.put("taglibs", APACHE_FOUNDATION);
knownLibraries.put("jakarta-regexp", APACHE_FOUNDATION);
knownLibraries.put("ant.ant", APACHE_FOUNDATION);
// Google - Will retire
knownLibraries.put("com.google.gwt", GOOGLE);
knownLibraries.put("com.google.code.gwt-math", GOOGLE);
knownLibraries.put("com.google.code.findbugs", GOOGLE);
knownLibraries.put("net.sf.gwt-widget", GOOGLE);
knownLibraries.put("com.google.guava", GOOGLE);
// CodeHaus - JSON / XML processing
knownLibraries.put("org.codehaus.jackson", JACKSON);
knownLibraries.put("org.codehaus.plexus", PLEXUS);
// ASM
knownLibraries.put("asm", ASM);
// CGLIB
knownLibraries.put("cglib", CGLIB);
// Jersey - used for REST services
knownLibraries.put("com.sun.jersey", JERSEY);
knownLibraries.put("com.sun.jersey.contribs", JERSEY);
// XStream - used for REST services
knownLibraries.put("com.thoughtworks.xstream", JERSEY);
// Joda-Time
knownLibraries.put("joda-time", JODA_TIME);
// Cache
knownLibraries.put("net.sf.jsr107cache", JAVAX);
// Transmorph - Will retire with 3.0
knownLibraries.put("net.sf.transmorph", TRANSMORPH);
// Teracotta software
knownLibraries.put("net.sf.ehcache", EHCACHE);
knownLibraries.put("org.opensymphony.quartz", QUARTZ);
// Antlr
knownLibraries.put("org.antlr", ANTLR);
// Aspect J
knownLibraries.put("org.aspectj", ASPECTJ);
// MVEL
knownLibraries.put("org.mvel", MVEL);
// ORO
knownLibraries.put("oro", ORO);
// Java Assist
knownLibraries.put("org.javassist", JAVA_ASSIST);
// OWASP
knownLibraries.put("org.owasp.antisamy", ANTISAMMY);
// OWASP
knownLibraries.put("com.yahoo.platform.yui", YAHOO);
}Example 42
| Project: commerce-master File: PomEvaluator.java View source code |
private static void initializeKnownLibraries() {
// Spring
knownLibraries.put("org.springframework", SPRING);
knownLibraries.put("org.springframework.security", SPRING);
knownLibraries.put("org.springframework.social", SPRING);
// Hibernate
knownLibraries.put("org.hibernate", HIBERNATE);
knownLibraries.put("org.hibernate.javax.persistence", HIBERNATE);
// Broadleaf
knownLibraries.put("org.broadleafcommerce", BROADLEAF_OPEN_SOURCE);
knownLibraries.put("com.broadleafcommerce", BROADLEAF_COMMERCIAL);
// Thymeleaf
knownLibraries.put("org.thymeleaf", THYMELEAF);
// JavaX
knownLibraries.put("javax.xml.bind", JAVAX);
knownLibraries.put("javax.mail", JAVAX);
knownLibraries.put("javax.servlet", JAVAX);
knownLibraries.put("javax.servlet.jsp", JAVAX);
knownLibraries.put("javax.validation", JAVAX);
knownLibraries.put("jstl", JAVAX);
// Logging
knownLibraries.put("org.slf4j", SLF4J);
knownLibraries.put("log4j", LOG4J);
// Apache
knownLibraries.put("commons-validator", APACHE_FOUNDATION);
knownLibraries.put("commons-collections", APACHE_FOUNDATION);
knownLibraries.put("commons-beanutils", APACHE_FOUNDATION);
knownLibraries.put("commons-cli", APACHE_FOUNDATION);
knownLibraries.put("commons-fileupload", APACHE_FOUNDATION);
knownLibraries.put("commons-dbcp", APACHE_FOUNDATION);
knownLibraries.put("commons-codec", APACHE_FOUNDATION);
knownLibraries.put("org.apache.commons", APACHE_FOUNDATION);
knownLibraries.put("commons-lang", APACHE_FOUNDATION);
knownLibraries.put("commons-digester", APACHE_FOUNDATION);
knownLibraries.put("commons-logging", APACHE_FOUNDATION);
knownLibraries.put("commons-pool", APACHE_FOUNDATION);
knownLibraries.put("org.apache.geronimo.specs", APACHE_FOUNDATION);
knownLibraries.put("org.apache.solr", APACHE_FOUNDATION);
knownLibraries.put("org.apache.velocity", APACHE_FOUNDATION);
knownLibraries.put("org.apache.xmlbeans", APACHE_FOUNDATION);
knownLibraries.put("taglibs", APACHE_FOUNDATION);
knownLibraries.put("jakarta-regexp", APACHE_FOUNDATION);
knownLibraries.put("ant.ant", APACHE_FOUNDATION);
// Google - Will retire
knownLibraries.put("com.google.gwt", GOOGLE);
knownLibraries.put("com.google.code.gwt-math", GOOGLE);
knownLibraries.put("com.google.code.findbugs", GOOGLE);
knownLibraries.put("net.sf.gwt-widget", GOOGLE);
knownLibraries.put("com.google.guava", GOOGLE);
// CodeHaus - JSON / XML processing
knownLibraries.put("org.codehaus.jackson", JACKSON);
knownLibraries.put("org.codehaus.plexus", PLEXUS);
// ASM
knownLibraries.put("asm", ASM);
// CGLIB
knownLibraries.put("cglib", CGLIB);
// Jersey - used for REST services
knownLibraries.put("com.sun.jersey", JERSEY);
knownLibraries.put("com.sun.jersey.contribs", JERSEY);
// XStream - used for REST services
knownLibraries.put("com.thoughtworks.xstream", JERSEY);
// Joda-Time
knownLibraries.put("joda-time", JODA_TIME);
// Cache
knownLibraries.put("net.sf.jsr107cache", JAVAX);
// Transmorph - Will retire with 3.0
knownLibraries.put("net.sf.transmorph", TRANSMORPH);
// Teracotta software
knownLibraries.put("net.sf.ehcache", EHCACHE);
knownLibraries.put("org.opensymphony.quartz", QUARTZ);
// Antlr
knownLibraries.put("org.antlr", ANTLR);
// Aspect J
knownLibraries.put("org.aspectj", ASPECTJ);
// MVEL
knownLibraries.put("org.mvel", MVEL);
// ORO
knownLibraries.put("oro", ORO);
// Java Assist
knownLibraries.put("org.javassist", JAVA_ASSIST);
// OWASP
knownLibraries.put("org.owasp.antisamy", ANTISAMMY);
// OWASP
knownLibraries.put("com.yahoo.platform.yui", YAHOO);
}Example 43
| Project: apiman-master File: TestPlanRunner.java View source code |
/**
* Evaluates the given expression against the given JSON object.
*
* @param bindExpression
* @param json
*/
private String evaluate(String bindExpression, final JsonNode json) {
PropertyHandlerFactory.registerPropertyHandler(ObjectNode.class, new PropertyHandler() {
@Override
public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) {
throw new RuntimeException("Not supported!");
}
@Override
public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) {
ObjectNode node = (ObjectNode) contextObj;
TestVariableResolver resolver = new TestVariableResolver(node, name);
return resolver.getValue();
}
});
return String.valueOf(MVEL.eval(bindExpression, new TestVariableResolverFactory(json)));
}Example 44
| Project: human-task-poc-proposal-master File: MVELLifeCycleManager.java View source code |
public static Object eval(String str, Map<String, Object> vars) {
ParserConfiguration pconf = new ParserConfiguration();
// pconf.addPackageImport("org.jbpm.task");
// pconf.addPackageImport("org.jbpm.task.service");
// pconf.addPackageImport("org.jbpm.task.query");
pconf.addPackageImport("org.jboss.human.interactions.internals.lifecycle");
pconf.addPackageImport("org.jboss.human.interactions.model");
pconf.addImport(Status.class);
pconf.addImport(Allowed.class);
pconf.addPackageImport("java.util");
// for(String entry : getInputs().keySet()){
// pconf.addImport(entry, getInputs().get(entry));
// }
ParserContext context = new ParserContext(pconf);
Serializable s = MVEL.compileExpression(str.trim(), context);
if (vars != null) {
return MVEL.executeExpression(s, vars);
} else {
return MVEL.executeExpression(s);
}
}Example 45
| Project: Squidy-master File: NodeShape.java View source code |
/**
*
*/
private void buildPropertiesForPropertiesTable() {
propertiesTable.clearEntries();
Field[] fields = ReflectionUtil.getFieldsInObjectHierarchy(getProcessable().getClass());
for (Field field : fields) {
if (field.isAnnotationPresent(Property.class)) {
final String fieldName = field.getName();
Object value = MVEL.getProperty(field.getName(), getProcessable());
final AbstractBasicControl<Object, ?> control;
if (field.isAnnotationPresent(TextField.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(TextField.class), value);
} else if (field.isAnnotationPresent(CheckBox.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(CheckBox.class), value);
} else if (field.isAnnotationPresent(ComboBox.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(ComboBox.class), value);
} else if (field.isAnnotationPresent(Slider.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(Slider.class), value);
} else if (field.isAnnotationPresent(Spinner.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(Spinner.class), value);
} else if (field.isAnnotationPresent(ImagePanel.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(ImagePanel.class), value);
} else if (field.isAnnotationPresent(Gauge.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(Gauge.class), value);
} else if (field.isAnnotationPresent(FileChooser.class)) {
control = (AbstractBasicControl<Object, ?>) ControlUtils.createControl(field.getAnnotation(FileChooser.class), value);
} else {
throw new SquidyException("Couldn't add property " + fieldName + " to properties table because of a not existing control annotation.");
}
Property property = field.getAnnotation(Property.class);
String name = property.name();
String description = property.description();
String prefix = property.prefix();
String suffix = property.suffix();
// Add property change listener to receive processing updates.
getProcessable().addStatusChangeListener(fieldName, new PropertyChangeListener() {
/*
* (non-Javadoc)
*
* @see
* java.beans.PropertyChangeListener#propertyChange(java
* .beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt) {
try {
control.setValueWithoutPropertyUpdate(evt.getNewValue());
} catch (Exception e) {
control.setValueWithoutPropertyUpdate(control.valueFromString(evt.getNewValue().toString()));
}
control.getComponent().repaint();
propertiesTable.firePropertyChange(CropScroll.CROP_SCROLLER_UPDATE, null, null);
}
});
// Add property update change listener to inform the processable
// about UI update events.
control.addPropertyUpdateListener(new PropertyUpdateListener<Object>() {
/*
* (non-Javadoc)
*
* @see org.squidy.designer.components.
* PropertyUpdateListener #propertyUpdate(java.lang.Object)
*/
public void propertyUpdate(Object value) {
try {
// Notify manager about property changes.
Manager.get().propertyChanged(getProcessable(), fieldName, value);
control.firePropertyChange(PROPERTY_BINDING_OK, null, null);
} catch (Exception e) {
control.firePropertyChange(PROPERTY_BINDING_EXCEPTION, null, null);
publishFailure(new SquidyException("Could not set property " + fieldName + ". Please check setter of this property for any Exceptions such as NullPointerException.", e));
}
propertiesTable.firePropertyChange(CropScroll.CROP_SCROLLER_UPDATE, null, null);
}
});
TableEntry entry = new TableEntry<IBasicControl<?, ?>>(name, description, control, prefix, suffix);
if (field.isAnnotationPresent(ImagePanel.class)) {
entry.addInputEventListener(new PBasicInputEventHandler() {
@Override
public void mouseClicked(PInputEvent event) {
control.customPInputEvent(event);
}
});
}
propertiesTable.addEntryToGroup(entry, property.group());
}
}
}Example 46
| Project: vertx-codegen-master File: CodeGenProcessor.java View source code |
private Collection<CodeGenerator> getCodeGenerators() {
if (codeGenerators == null) {
String outputDirectoryOption = processingEnv.getOptions().get("codegen.output");
if (outputDirectoryOption == null) {
outputDirectoryOption = processingEnv.getOptions().get("outputDirectory");
if (outputDirectoryOption != null) {
log.warning("Please use 'codegen.output' option instead of 'outputDirectory' option");
}
}
if (outputDirectoryOption != null) {
outputDirectory = new File(outputDirectoryOption);
if (!outputDirectory.exists()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " does not exist");
}
if (!outputDirectory.isDirectory()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " is not a directory");
}
}
List<CodeGenerator> generators = loadGenerators();
Predicate<CodeGenerator> filter = filterGenerators();
if (filter != null) {
generators = generators.stream().filter(filter).collect(Collectors.toList());
}
generators.forEach( gen -> {
Template template = new Template(gen.templateFilename);
template.setOptions(processingEnv.getOptions());
gen.template = template;
gen.filenameExpr = MVEL.compileExpression(gen.filename);
log.info("Loaded " + gen.name + " code generator");
});
relocations = processingEnv.getOptions().entrySet().stream().filter( e -> e.getKey().startsWith("codegen.output.")).collect(Collectors.toMap( e -> e.getKey().substring("codegen.output.".length()), Map.Entry::getValue));
codeGenerators = generators;
}
return codeGenerators;
}Example 47
| Project: errai-master File: TypedQueryFactoryGenerator.java View source code |
/**
* Consumes the next token from the traverser and returns the equivalent Java
* expression, recursing if necessary.
*
* @param traverser
* The traverser that walks through the nodes of the Hibernate
* second-level AST in order. When this method returns, the traverser
* will have completely walked the subtree under the starting node.
* The traverser will be left on the next node.
* @param dotNodeResolver
* the mechanism for resolving a DotNode (that is, a JPQL property
* reference in the query) into an Errai codegen Statement.
* @param containingMethod
* the builder for the method that will eventually receive the
* returned statement. If the code emitted by this generator depends
* on some variable declaration, the variable declaration statement
* will be appended to this block.
* @return a statement that evaluates to the subtree rooted at the current
* position of {@code traverser}.
*/
private Statement generateExpression(AstInorderTraversal traverser, DotNodeResolver dotNodeResolver, BlockBuilder<?> containingMethod) {
AST ast = traverser.next();
switch(ast.getType()) {
case HqlSqlTokenTypes.EQ:
return Stmt.invokeStatic(Comparisons.class, "nullSafeEquals", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.NE:
return Bool.notExpr(Stmt.invokeStatic(Comparisons.class, "nullSafeEquals", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod)));
case HqlSqlTokenTypes.GT:
return Stmt.invokeStatic(Comparisons.class, "nullSafeGreaterThan", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.GE:
return Stmt.invokeStatic(Comparisons.class, "nullSafeGreaterThanOrEqualTo", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.LT:
return Stmt.invokeStatic(Comparisons.class, "nullSafeLessThan", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.LE:
return Stmt.invokeStatic(Comparisons.class, "nullSafeLessThanOrEqualTo", generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.BETWEEN:
{
Statement middle = generateExpression(traverser, dotNodeResolver, containingMethod);
Statement small = generateExpression(traverser, dotNodeResolver, containingMethod);
Statement big = generateExpression(traverser, dotNodeResolver, containingMethod);
return Bool.and(Stmt.invokeStatic(Comparisons.class, "nullSafeLessThanOrEqualTo", small, middle), Stmt.invokeStatic(Comparisons.class, "nullSafeLessThanOrEqualTo", middle, big));
}
case HqlSqlTokenTypes.NOT_BETWEEN:
{
Statement outside = generateExpression(traverser, dotNodeResolver, containingMethod);
Statement small = generateExpression(traverser, dotNodeResolver, containingMethod);
Statement big = generateExpression(traverser, dotNodeResolver, containingMethod);
return Bool.or(Stmt.invokeStatic(Comparisons.class, "nullSafeLessThan", outside, small), Stmt.invokeStatic(Comparisons.class, "nullSafeGreaterThan", outside, big));
}
case HqlSqlTokenTypes.NOT_IN:
case HqlSqlTokenTypes.IN:
{
final boolean notIn = ast.getType() == HqlSqlTokenTypes.NOT_IN;
Statement thingToTest = generateExpression(traverser, dotNodeResolver, containingMethod);
ast = traverser.next();
if (ast.getType() != HqlSqlTokenTypes.IN_LIST) {
throw new GenerationException("Expected IN_LIST node but found " + ast.getText());
}
List<Statement> collection = new ArrayList<Statement>(ast.getNumberOfChildren());
for (int i = 0; i < ast.getNumberOfChildren(); i++) {
collection.add(Cast.to(Object.class, generateExpression(traverser, dotNodeResolver, containingMethod)));
}
Statement callToComparisonsIn = Stmt.invokeStatic(Comparisons.class, "in", thingToTest, collection.toArray());
return notIn ? Bool.notExpr(callToComparisonsIn) : callToComparisonsIn;
}
case HqlSqlTokenTypes.NOT_LIKE:
case HqlSqlTokenTypes.LIKE:
{
Statement valueExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
Statement patternExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
Statement escapeCharExpr = Cast.to(String.class, Stmt.loadLiteral(null));
if (ast.getNumberOfChildren() == 3) {
traverser.next();
escapeCharExpr = Cast.to(String.class, generateExpression(traverser, dotNodeResolver, containingMethod));
}
Statement likeStmt = Stmt.invokeStatic(Comparisons.class, "like", valueExpr, patternExpr, escapeCharExpr);
return ast.getType() == HqlSqlTokenTypes.LIKE ? likeStmt : Bool.notExpr(likeStmt);
}
case HqlSqlTokenTypes.IS_NULL:
return Bool.isNull(generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.IS_NOT_NULL:
return Bool.isNotNull(generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.OR:
return Bool.or(generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.AND:
return Bool.and(generateExpression(traverser, dotNodeResolver, containingMethod), generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.NOT:
return Bool.notExpr(generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.DOT:
DotNode dotNode = (DotNode) ast;
traverser.fastForwardToNextSiblingOf(dotNode);
return dotNodeResolver.resolve(dotNode);
case HqlSqlTokenTypes.NAMED_PARAM:
ParameterNode paramNode = (ParameterNode) ast;
NamedParameterSpecification namedParamSpec = (NamedParameterSpecification) paramNode.getHqlParameterSpecification();
return Stmt.loadVariable("this").invoke("getParameterValue", namedParamSpec.getName());
case HqlSqlTokenTypes.QUOTED_STRING:
return Stmt.loadLiteral(SqlUtil.parseStringLiteral(ast.getText()));
case HqlSqlTokenTypes.UNARY_MINUS:
return ArithmeticExpressionBuilder.create(ArithmeticOperator.Subtraction, generateExpression(traverser, dotNodeResolver, containingMethod));
case HqlSqlTokenTypes.NUM_INT:
case HqlSqlTokenTypes.NUM_DOUBLE:
case HqlSqlTokenTypes.NUM_FLOAT:
// (long and char are the exceptions)
return Stmt.loadLiteral(Double.valueOf(ast.getText()));
case HqlSqlTokenTypes.NUM_LONG:
return Stmt.loadLiteral(Long.valueOf(ast.getText()));
case HqlSqlTokenTypes.TRUE:
case HqlSqlTokenTypes.FALSE:
return Stmt.loadLiteral(((BooleanLiteralNode) ast).getValue());
case HqlSqlTokenTypes.JAVA_CONSTANT:
return Stmt.loadLiteral(MVEL.eval(ast.getText()));
case HqlSqlTokenTypes.METHOD_CALL:
IdentNode methodNameNode = (IdentNode) traverser.next();
SqlNode exprList = (SqlNode) traverser.next();
// trim is weird because it can take keywords (IDENT nodes) in its arg list
if ("trim".equals(methodNameNode.getOriginalText())) {
String trimType = "BOTH";
Statement trimChar = Stmt.loadLiteral(' ');
Statement untrimmedStr;
ast = traverser.next();
if (ast.getType() == HqlSqlTokenTypes.IDENT) {
if (ast.getText().equalsIgnoreCase("BOTH")) {
trimType = "BOTH";
ast = traverser.next();
} else if (ast.getText().equalsIgnoreCase("LEADING")) {
trimType = "LEADING";
ast = traverser.next();
} else if (ast.getText().equalsIgnoreCase("TRAILING")) {
trimType = "TRAILING";
ast = traverser.next();
}
}
if (exprList.getNumberOfChildren() == 4 || (exprList.getNumberOfChildren() == 3 && ast.getType() != HqlSqlTokenTypes.IDENT)) {
// [[IDENT('LEADING|TRAILING|BOTH')], [<expression:trimchar>], IDENT(FROM),] <expression:untrimmedStr>
// ^^^ you are here
Statement trimStr = generateExpression(new AstInorderTraversal(ast), dotNodeResolver, containingMethod);
trimChar = Stmt.nestedCall(trimStr).invoke("charAt", 0);
ast = traverser.fastForwardTo(ast.getNextSibling());
}
if (ast.getType() == HqlSqlTokenTypes.IDENT) {
if (ast.getText().equalsIgnoreCase("FROM")) {
ast = traverser.next();
} else {
throw new GenerationException("Found unexpected JPQL keyword " + ast.getText() + " in query (expected FROM)");
}
}
untrimmedStr = generateExpression(new AstInorderTraversal(ast), dotNodeResolver, containingMethod);
traverser.fastForwardToNextSiblingOf(ast);
// declare a local variable with the regex pattern in it
int uniq = uniqueNumber.incrementAndGet();
StringBuilderBuilder trimPattern = Implementations.newStringBuilder();
trimPattern.append("^");
if (trimType.equals("LEADING") || trimType.equals("BOTH")) {
trimPattern.append(Stmt.invokeStatic(Comparisons.class, "escapeRegexChar", trimChar));
trimPattern.append("*");
}
trimPattern.append("(.*?)");
if (trimType.equals("TRAILING") || trimType.equals("BOTH")) {
trimPattern.append(Stmt.invokeStatic(Comparisons.class, "escapeRegexChar", trimChar));
trimPattern.append("*");
}
trimPattern.append("$");
containingMethod.append(Stmt.declareFinalVariable("trimmer" + uniq, RegExp.class, Stmt.invokeStatic(RegExp.class, "compile", Stmt.load(trimPattern).invoke("toString"))));
return Stmt.nestedCall(Stmt.loadVariable("trimmer" + uniq).invoke("exec", Stmt.castTo(String.class, Stmt.load(untrimmedStr))).invoke("getGroup", 1));
}
// for all other functions, we can pre-process the arguments like this:
Statement[] args = new Statement[exprList.getNumberOfChildren()];
for (int i = 0; i < args.length; i++) {
args[i] = generateExpression(traverser, dotNodeResolver, containingMethod);
}
if ("lower".equals(methodNameNode.getOriginalText())) {
return Stmt.castTo(String.class, Stmt.load(args[0])).invoke("toLowerCase");
} else if ("upper".equals(methodNameNode.getOriginalText())) {
return Stmt.castTo(String.class, Stmt.load(args[0])).invoke("toUpperCase");
} else if ("concat".equals(methodNameNode.getOriginalText())) {
StringBuilderBuilder sb = Implementations.newStringBuilder();
for (Statement s : args) {
sb.append(s);
}
return Stmt.load(sb).invoke("toString");
} else if ("substring".equals(methodNameNode.getOriginalText())) {
int uniq = uniqueNumber.incrementAndGet();
containingMethod.append(Stmt.declareFinalVariable("substrOrig" + uniq, String.class, Cast.to(String.class, args[0])));
containingMethod.append(Stmt.declareFinalVariable("substrStart" + uniq, int.class, Arith.expr(Cast.to(Integer.class, args[1]), ArithmeticOperator.Subtraction, 1)));
if (args.length == 2) {
return Stmt.loadVariable("substrOrig" + uniq).invoke("substring", Stmt.loadVariable("substrStart" + uniq));
} else if (args.length == 3) {
containingMethod.append(Stmt.declareFinalVariable("substrEnd" + uniq, int.class, Arith.expr(Cast.to(Integer.class, args[2]), ArithmeticOperator.Addition, Stmt.loadVariable("substrStart" + uniq))));
return Stmt.loadVariable("substrOrig" + uniq).invoke("substring", Stmt.loadVariable("substrStart" + uniq), Stmt.loadVariable("substrEnd" + uniq));
} else {
throw new GenerationException("Found " + args.length + " arguments to concat() function. Expected 2 or 3.");
}
} else if ("length".equals(methodNameNode.getOriginalText())) {
// all numerics must be double for purposes of comparison in this JPQL implementation
return Stmt.castTo(double.class, Stmt.nestedCall(Stmt.castTo(String.class, Stmt.load(args[0])).invoke("length")));
} else if ("locate".equals(methodNameNode.getOriginalText())) {
// all numerics must be double for purposes of comparison in this JPQL implementation
Statement startIndex = Stmt.loadLiteral(0);
if (args.length == 3) {
// For the 3-arg variant, JPA spec doesn't say whether we return the index in the original string or the index in the substring.
// I'm just guessing it's the same as Java's rule.
startIndex = Arith.expr(Stmt.castTo(int.class, Stmt.load(args[2])), ArithmeticOperator.Subtraction, 1);
}
Statement indexOf = Stmt.castTo(String.class, Stmt.load(args[1])).invoke("indexOf", Stmt.castTo(String.class, Stmt.load(args[0])), startIndex);
return Stmt.castTo(double.class, Stmt.nestedCall(Arith.expr(indexOf, ArithmeticOperator.Addition, 1)));
}
throw new UnsupportedOperationException("The JPQL function " + methodNameNode.getOriginalText() + " is not supported");
// JUNK EXPRESSIONS
case HqlSqlTokenTypes.FILTERS:
// Hibernate inserts one of these into the second-level parse tree when the query is on a type
// which has a supertype which is also an entity. it's a SQL snippet that tests the discriminator
// column to ensure the type is what we want.
traverser.fastForwardToNextSiblingOf(ast);
return generateExpression(traverser, dotNodeResolver, containingMethod);
default:
throw new UnexpectedTokenException(ast.getType(), "an expression (boolean, literal, JPQL path, method call, or named parameter)");
}
// I keep feeling like this will be useful, but so far it has turned out to be unnecessary:
// LiteralNode literalNode = (LiteralNode) ast;
// return Stmt.loadLiteral(((StringRepresentableType<?>) literalNode.getDataType()).fromStringValue(literalNode.getText()));
}Example 48
| Project: drools-guvnor-plugin-master File: RuleCompletionProcessor.java View source code |
private MvelContext analyzeMvelExpression(@SuppressWarnings("rawtypes") Map<String, Class> params, DRLInfo drlInfo, String mvel) {
String expr = processMacros(mvel);
String name = context.getRuleName();
RuleInfo currentRule = getCurrentRule(drlInfo, name);
String qName = drlInfo.getPackageName() + "." + name;
MVELDialect dialect = (MVELDialect) drlInfo.getDialectRegistry().getDialect("mvel");
ParserContext initialContext = createInitialContext(params, qName, dialect);
MvelContext mCon = new MvelContext();
mCon.setContext(initialContext);
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(expr, initialContext);
Class<?> lastType = stmt.getKnownEgressType();
//Statics expression may return Class as an egress type
if (lastType != null && "java.lang.Class".equals(lastType.getName())) {
mCon.setStaticFlag(true);
}
if (lastType == null || "java.lang.Object".equals(lastType.getName()) || "java.lang.Class".equals(lastType.getName())) {
// attempt to use the property verifier to get
// a better type resolution (a recommend by cbrock, though egress gives consistent results)
lastType = new PropertyVerifier(expr, initialContext).analyze();
}
if (lastType == null) {
lastType = Object.class;
}
mCon.setReturnedType(lastType);
} catch (Exception e) {
}
return mCon;
}Example 49
| Project: droolsjbpm-tools-master File: RuleCompletionProcessor.java View source code |
private MvelContext analyzeMvelExpression(@SuppressWarnings("rawtypes") Map<String, Class> params, DRLInfo drlInfo, String mvel) {
String expr = processMacros(mvel);
String name = context.getRuleName();
RuleInfo currentRule = getCurrentRule(drlInfo, name);
String qName = drlInfo.getPackageName() + "." + name;
MVELDialect dialect = (MVELDialect) drlInfo.getDialectRegistry().getDialect("mvel");
ParserContext initialContext = createInitialContext(params, qName, dialect);
MvelContext mCon = new MvelContext();
mCon.setContext(initialContext);
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(expr, initialContext);
Class<?> lastType = stmt.getKnownEgressType();
//Statics expression may return Class as an egress type
if (lastType != null && "java.lang.Class".equals(lastType.getName())) {
mCon.setStaticFlag(true);
}
if (lastType == null || "java.lang.Object".equals(lastType.getName()) || "java.lang.Class".equals(lastType.getName())) {
// attempt to use the property verifier to get
// a better type resolution (a recommend by cbrock, though egress gives consistent results)
lastType = new PropertyVerifier(expr, initialContext).analyze();
}
if (lastType == null) {
lastType = Object.class;
}
mCon.setReturnedType(lastType);
} catch (Exception e) {
}
return mCon;
}Example 50
| Project: park_java-master File: CheckoutController.java View source code |
public Boolean executeExpression(String expression, Map<String, Object> vars) {
try {
Serializable exp;
synchronized (EXPRESSION_CACHE) {
exp = (Serializable) EXPRESSION_CACHE.get(expression);
if (exp == null) {
ParserContext context = new ParserContext();
context.addImport("OfferType", OfferType.class);
context.addImport("FulfillmentType", FulfillmentType.class);
context.addImport("MVEL", MVEL.class);
context.addImport("MvelHelper", MvelHelper.class);
// StringBuffer completeExpression = new
// StringBuffer(functions.toString());
// completeExpression.append(" ").append(expression);
exp = MVEL.compileExpression(expression, context);
EXPRESSION_CACHE.put(expression, exp);
}
}
Object test = MVEL.executeExpression(exp, vars);
return (Boolean) test;
} catch (Exception e) {
LOG.warn("Unable to parse and/or execute an mvel expression. Reporting to the logs and returning false " + "for the match expression:" + expression, e);
return false;
}
}Example 51
| Project: plugin.maven-drools-plugin-master File: RuleCompletionProcessor.java View source code |
private MvelContext analyzeMvelExpression(@SuppressWarnings("rawtypes") Map<String, Class> params, DRLInfo drlInfo, String mvel) {
String expr = processMacros(mvel);
String name = context.getRuleName();
RuleInfo currentRule = getCurrentRule(drlInfo, name);
String qName = drlInfo.getPackageName() + "." + name;
MVELDialect dialect = (MVELDialect) drlInfo.getDialectRegistry().getDialect("mvel");
ParserContext initialContext = createInitialContext(params, qName, dialect);
MvelContext mCon = new MvelContext();
mCon.setContext(initialContext);
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(expr, initialContext);
Class<?> lastType = stmt.getKnownEgressType();
//Statics expression may return Class as an egress type
if (lastType != null && "java.lang.Class".equals(lastType.getName())) {
mCon.setStaticFlag(true);
}
if (lastType == null || "java.lang.Object".equals(lastType.getName()) || "java.lang.Class".equals(lastType.getName())) {
// attempt to use the property verifier to get
// a better type resolution (a recommend by cbrock, though egress gives consistent results)
lastType = new PropertyVerifier(expr, initialContext).analyze();
}
if (lastType == null) {
lastType = Object.class;
}
mCon.setReturnedType(lastType);
} catch (Exception e) {
}
return mCon;
}Example 52
| Project: aspectj-scripting-master File: MvelRunnable.java View source code |
public void run() {
MVEL.executeExpression(mvelExpression, variableResolverFactory);
}Example 53
| Project: camel-master File: MvelExpression.java View source code |
public <T> T evaluate(Exchange exchange, Class<T> tClass) {
try {
Object value = org.mvel2.MVEL.executeExpression(compiled, new RootObject(exchange));
return exchange.getContext().getTypeConverter().convertTo(tClass, value);
} catch (Exception e) {
throw new ExpressionEvaluationException(this, exchange, e);
}
}Example 54
| Project: fast-java-expr-eval-master File: Evaluators.java View source code |
public void compileMVEL() throws Exception {
mvelExpression = org.mvel2.MVEL.compileExpression("2 + x * (7-5) * 3.14159 + Math.sin(0)", org.mvel2.ParserContext.create().stronglyTyped().withInput("x", double.class));
}Example 55
| Project: cloudmix-master File: MvelExpression.java View source code |
public Object evaluate(Map<String, Object> variables) {
ParserContext context = new ParserContext();
context.addImport("Strings", Strings.class);
Serializable compiled = MVEL.compileExpression(expression, context);
return MVEL.executeExpression(compiled, variables);
}Example 56
| Project: coherence-tools-master File: MvelExpression.java View source code |
// ---- Expression implementation ----------------------------------------
/**
* {@inheritDoc}
*/
public T evaluate(Object target, Map<String, Object> variables) {
return (T) MVEL.executeExpression(getCompiledExpression(), target, variables);
}Example 57
| Project: elasticsearch-server-master File: MvelScriptEngineService.java View source code |
@Override
public Object compile(String script) {
return MVEL.compileExpression(script, new ParserContext(parserConfiguration));
}Example 58
| Project: elasticsearch-lang-mvel-master File: MvelScriptEngineService.java View source code |
@Override
public Object compile(String script) {
return MVEL.compileExpression(script, new ParserContext(parserConfiguration));
}Example 59
| Project: Rythm-master File: RythmEngine.java View source code |
public Object eval(String script, Map<String, Object> params) {
Serializable ce = mvels.get(script);
if (null == ce) {
ce = MVEL.compileExpression(script);
mvels.put(script, ce);
}
return MVEL.executeExpression(ce, params);
}Example 60
| Project: rythmengine-master File: RythmEngine.java View source code |
public Object eval(String script, Map<String, Object> params) {
Serializable ce = mvels.get(script);
if (null == ce) {
ce = MVEL.compileExpression(script);
mvels.put(script, ce);
}
return MVEL.executeExpression(ce, params);
}