org.eclipse.xtext.xbase.interpreter.IEvaluationContext Java Examples

The following examples show how to use org.eclipse.xtext.xbase.interpreter.IEvaluationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XForLoopExpression forLoop, IEvaluationContext context, CancelIndicator indicator) {
	Object iterableOrIterator = internalEvaluate(forLoop.getForExpression(), context, indicator);
	if (iterableOrIterator == null)
		return throwNullPointerException(forLoop.getForExpression(), "iterable evaluated to 'null'");
	Iterator<?> iter = null;
	if (iterableOrIterator instanceof Iterable<?>) {
		iter = ((Iterable<?>) iterableOrIterator).iterator();
	} else if (iterableOrIterator.getClass().isArray()) {
		iter = ((Iterable<?>) Conversions.doWrapArray(iterableOrIterator)).iterator();
	} else {
		return throwClassCastException(forLoop.getForExpression(), iterableOrIterator, java.lang.Iterable.class);
	}
	IEvaluationContext forkedContext = context.fork();
	QualifiedName paramName = QualifiedName.create(forLoop.getDeclaredParam().getName());
	forkedContext.newValue(paramName, null);
	while (iter.hasNext()) {
		Object next = iter.next();
		forkedContext.assignValue(paramName, next);
		internalEvaluate(forLoop.getEachExpression(), forkedContext, indicator);
	}
	return null;
}
 
Example #2
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XBasicForLoopExpression forLoop, IEvaluationContext context, CancelIndicator indicator) {
	IEvaluationContext forkedContext = context.fork();
	for (XExpression initExpression : forLoop.getInitExpressions()) {
		internalEvaluate(initExpression, forkedContext, indicator);
	}
	XExpression expression = forLoop.getExpression();
	Object condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator);
	while (Boolean.TRUE.equals(condition)) {
		internalEvaluate(forLoop.getEachExpression(), forkedContext, indicator);
		for (XExpression updateExpression : forLoop.getUpdateExpressions()) {
			internalEvaluate(updateExpression, forkedContext, indicator);
		}
		condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator);
	}
	return null;
}
 
Example #3
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _assignValueTo(JvmField jvmField, XAbstractFeatureCall assignment, Object value,
		IEvaluationContext context, CancelIndicator indicator) {
	Object receiver = getReceiver(assignment, context, indicator);
	Field field = javaReflectAccess.getField(jvmField);
	try {
		if (field == null) {
			throw new NoSuchFieldException("Could not find field " + jvmField.getIdentifier());
		}
		if (!Modifier.isStatic(field.getModifiers()) && receiver == null)
			throw new EvaluationException(new NullPointerException("Cannot assign value to field: "
					+ jvmField.getIdentifier() + " on null instance"));
		JvmTypeReference type = jvmField.getType();
		Object coerced = coerceArgumentType(value, type);
		field.setAccessible(true);
		field.set(receiver, coerced);
		return value;
	} catch (Exception e) {
		throw new IllegalStateException("Could not access field: " + jvmField.getIdentifier()
				+ " on instance: " + receiver, e);
	}
}
 
Example #4
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XListLiteral literal, IEvaluationContext context, CancelIndicator indicator) {
	IResolvedTypes resolveTypes = typeResolver.resolveTypes(literal);
	LightweightTypeReference type = resolveTypes.getActualType(literal);
	List<Object> list = newArrayList();
	for(XExpression element: literal.getElements()) {
		if (indicator.isCanceled())
			throw new InterpreterCanceledException();
		list.add(internalEvaluate(element, context, indicator));
	}
	if(type != null && type.isArray()) {
		try {
			LightweightTypeReference componentType = type.getComponentType();
			return Conversions.unwrapArray(list, getJavaType(componentType.getType()));
		} catch (ClassNotFoundException e) {
		}
	}
	return Collections.unmodifiableList(list);
}
 
Example #5
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param context unused in this context but required for dispatching
 * @param indicator unused in this context but required for dispatching
 */
@SuppressWarnings("unchecked")
protected Object _doEvaluate(XNumberLiteral literal, IEvaluationContext context, CancelIndicator indicator) {
	IResolvedTypes resolvedTypes = typeResolver.resolveTypes(literal);
	LightweightTypeReference expectedType = resolvedTypes.getExpectedType(literal);
	Class<? extends Number> type = numberLiterals.getJavaType(literal);
	if (expectedType != null && expectedType.isSubtypeOf(Number.class)) {
		try {
			Class<?> expectedClassType = getJavaType(expectedType.toJavaCompliantTypeReference().getType());
			if (expectedClassType.isPrimitive()) {
				expectedClassType = ReflectionUtil.getObjectType(expectedClassType);
			}
			if (Number.class != expectedClassType && Number.class.isAssignableFrom(expectedClassType)) {
				type = (Class<? extends Number>) expectedClassType;
			}
		} catch (ClassNotFoundException e) {
		}
	}
	return numberLiterals.numberValue(literal, type);
}
 
Example #6
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XConstructorCall constructorCall, IEvaluationContext context, CancelIndicator indicator) {
	JvmConstructor jvmConstructor = constructorCall.getConstructor();
	List<Object> arguments = evaluateArgumentExpressions(jvmConstructor, constructorCall.getArguments(), context, indicator);
	Constructor<?> constructor = javaReflectAccess.getConstructor(jvmConstructor);
	try {
		if (constructor == null)
			throw new NoSuchMethodException("Could not find constructor " + jvmConstructor.getIdentifier());
		constructor.setAccessible(true);
		Object result = constructor.newInstance(arguments.toArray(new Object[arguments.size()]));
		return result;
	} catch (InvocationTargetException targetException) {
		throw new EvaluationException(targetException.getTargetException());
	} catch (Exception e) {
		throw new IllegalStateException("Could not invoke constructor: " + jvmConstructor.getIdentifier(), e);
	}
}
 
Example #7
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object invokeFeature(JvmIdentifiableElement feature, XAbstractFeatureCall featureCall, Object receiverObj,
		IEvaluationContext context, CancelIndicator indicator) {
	if (feature instanceof JvmField) {
		return _invokeFeature((JvmField)feature, featureCall, receiverObj, context, indicator);
	} else if (feature instanceof JvmOperation) {
		return _invokeFeature((JvmOperation)feature, featureCall, receiverObj, context, indicator);
	} else if (feature != null) {
		return _invokeFeature(feature, featureCall, receiverObj, context, indicator);
	} else {
		throw new NullPointerException("Feature was null");
	}
}
 
Example #8
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XAssignment assignment, IEvaluationContext context, CancelIndicator indicator) {
	JvmIdentifiableElement feature = assignment.getFeature();
	if (feature instanceof JvmOperation && ((JvmOperation) feature).isVarArgs()) {
		return _doEvaluate((XAbstractFeatureCall) assignment, context, indicator);
	}
	Object value = internalEvaluate(assignment.getValue(), context, indicator);
	Object assign = assignValueTo(feature, assignment, value, context, indicator);
	return assign;
}
 
Example #9
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object evaluateGetAndAssign(XAbstractFeatureCall featureCall, IEvaluationContext context, CancelIndicator indicator) {
	XAbstractFeatureCall operand = (XAbstractFeatureCall) featureCall.getActualArguments().get(0);
	
	Object originalValue = internalEvaluate(operand, context, indicator);
	Object value = applyGetAndAssignOperator(originalValue, featureCall.getConcreteSyntaxFeatureName());
	
	assignValueTo(operand.getFeature(), featureCall, value, context, indicator);
	return originalValue;
}
 
Example #10
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XFeatureCall featureCall, IEvaluationContext context, CancelIndicator indicator) {
	if (featureCall.isTypeLiteral()) {
		JvmType type = (JvmType) featureCall.getFeature();
		Object result = translateJvmTypeToResult(type, 0);
		return result;
	} else {
		return _doEvaluate((XAbstractFeatureCall) featureCall, context, indicator);
	}
}
 
Example #11
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XVariableDeclaration variableDecl, IEvaluationContext context, CancelIndicator indicator) {
	Object initialValue = null;
	if (variableDecl.getRight()!=null) {
		initialValue = internalEvaluate(variableDecl.getRight(), context, indicator);
	} else {
		if (services.getPrimitives().isPrimitive(variableDecl.getType())) {
			Primitive primitiveKind = services.getPrimitives().primitiveKind((JvmPrimitiveType) variableDecl.getType().getType());
			switch(primitiveKind) {
				case Boolean:
					initialValue = Boolean.FALSE; break;
				case Char:
					initialValue = Character.valueOf((char) 0); break;
				case Double:
					initialValue = Double.valueOf(0d); break;
				case Byte:
					initialValue = Byte.valueOf((byte) 0); break;
				case Float:
					initialValue = Float.valueOf(0f); break;
				case Int:
					initialValue = Integer.valueOf(0); break;
				case Long:
					initialValue = Long.valueOf(0L); break;
				case Short:
					initialValue = Short.valueOf((short) 0); break;
				case Void:
					throw new IllegalStateException("Void is not a valid variable type.");
				default:
					throw new IllegalStateException("Unknown primitive type " + primitiveKind);
			}
		}
	}
	context.newValue(QualifiedName.create(variableDecl.getName()), initialValue);
	return null;
}
 
Example #12
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XClosure closure, IEvaluationContext context, CancelIndicator indicator) {
	Class<?> functionIntf = null;
	switch (closure.getFormalParameters().size()) {
		case 0:
			functionIntf = getClass(Functions.Function0.class);
			break;
		case 1:
			functionIntf = getClass(Functions.Function1.class);
			break;
		case 2:
			functionIntf = getClass(Functions.Function2.class);
			break;
		case 3:
			functionIntf = getClass(Functions.Function3.class);
			break;
		case 4:
			functionIntf = getClass(Functions.Function4.class);
			break;
		case 5:
			functionIntf = getClass(Functions.Function5.class);
			break;
		case 6:
			functionIntf = getClass(Functions.Function6.class);
			break;
		default:
			throw new IllegalStateException("Closures with more then 6 parameters are not supported.");
	}
	ClosureInvocationHandler invocationHandler = new ClosureInvocationHandler(closure, context, this, indicator);
	Object proxy = Proxy.newProxyInstance(classLoader, new Class<?>[] { functionIntf }, invocationHandler);
	return proxy;
}
 
Example #13
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XThrowExpression throwExpression, IEvaluationContext context, CancelIndicator indicator) {
	Object thrown = internalEvaluate(throwExpression.getExpression(), context, indicator);
	if (thrown == null) {
		return throwNullPointerException(throwExpression, "throwable expression evaluated to 'null'");
	}
	if (!(thrown instanceof Throwable)) {
		return throwClassCastException(throwExpression.getExpression(), thrown, Throwable.class);
	}
	throw new EvaluationException((Throwable) thrown);
}
 
Example #14
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XIfExpression ifExpression, IEvaluationContext context, CancelIndicator indicator) {
	Object conditionResult = internalEvaluate(ifExpression.getIf(), context, indicator);
	if (Boolean.TRUE.equals(conditionResult)) {
		return internalEvaluate(ifExpression.getThen(), context, indicator);
	} else {
		if (ifExpression.getElse() == null)
			return getDefaultObjectValue(typeResolver.resolveTypes(ifExpression).getActualType(ifExpression));
		return internalEvaluate(ifExpression.getElse(), context, indicator);
	}
}
 
Example #15
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object internalEvaluate(XExpression expression, IEvaluationContext context, CancelIndicator indicator) throws EvaluationException {
	if (indicator.isCanceled())
		throw new InterpreterCanceledException();
	Object result = doEvaluate(expression, context, indicator);
	final LightweightTypeReference expectedType = typeResolver.resolveTypes(expression).getExpectedType(expression);
	if(expectedType != null)
		result = wrapOrUnwrapArray(result, expectedType);
	return result;
}
 
Example #16
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object _doEvaluate(XBlockExpression literal, IEvaluationContext context, CancelIndicator indicator) {
	List<XExpression> expressions = literal.getExpressions();

	Object result = null;
	IEvaluationContext forkedContext = context.fork();
	for (int i = 0; i < expressions.size(); i++) {
		result = internalEvaluate(expressions.get(i), forkedContext, indicator);
	}
	return result;
}
 
Example #17
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param context unused in this context but required for dispatching
 * @param indicator unused in this context but required for dispatching
 */
protected Object _doEvaluate(XTypeLiteral literal, IEvaluationContext context, CancelIndicator indicator) {
	if (literal.getType() == null || literal.getType().eIsProxy()) {
		List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(literal,
				XbasePackage.Literals.XTYPE_LITERAL__TYPE);
		// TODO cleanup
		if (nodesForFeature.isEmpty())
			throw new EvaluationException(new ClassNotFoundException());
		throw new EvaluationException(new ClassNotFoundException(nodesForFeature.get(0).getText()));
	}
	JvmType type = literal.getType();
	Object result = translateJvmTypeToResult(type, literal.getArrayDimensions().size());
	return result;
}
 
Example #18
Source File: RuleContextHelper.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Retrieves the evaluation context (= set of variables) for a rule. The context is shared with all rules in the
 * same model (= rule file).
 *
 * @param rule the rule to get the context for
 * @return the evaluation context
 */
public static synchronized IEvaluationContext getContext(Rule rule, Injector injector) {
    Logger logger = LoggerFactory.getLogger(RuleContextHelper.class);
    RuleModel ruleModel = (RuleModel) rule.eContainer();

    // check if a context already exists on the resource
    for (Adapter adapter : ruleModel.eAdapters()) {
        if (adapter instanceof RuleContextAdapter) {
            return ((RuleContextAdapter) adapter).getContext();
        }
    }
    Provider<IEvaluationContext> contextProvider = injector.getProvider(IEvaluationContext.class);
    // no evaluation context found, so create a new one
    ScriptEngine scriptEngine = injector.getInstance(ScriptEngine.class);
    if (scriptEngine != null) {
        IEvaluationContext evaluationContext = contextProvider.get();
        for (VariableDeclaration var : ruleModel.getVariables()) {
            try {
                Object initialValue = var.getRight() == null ? null
                        : scriptEngine.newScriptFromXExpression(var.getRight()).execute();
                evaluationContext.newValue(QualifiedName.create(var.getName()), initialValue);
            } catch (ScriptExecutionException e) {
                logger.warn("Variable '{}' on rule file '{}' cannot be initialized with value '{}': {}",
                        new Object[] { var.getName(), ruleModel.eResource().getURI().path(),
                                var.getRight().toString(), e.getMessage() });
            }
        }
        ruleModel.eAdapters().add(new RuleContextAdapter(evaluationContext));
        return evaluationContext;
    } else {
        logger.debug("Rule variables of rule {} cannot be evaluated as no scriptengine is available!",
                ruleModel.eResource().getURI().path());
        return contextProvider.get();
    }
}
 
Example #19
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param featureCall unused in this context but required for dispatching
 * @param indicator unused in this context but required for dispatching
 */
protected Object _invokeFeature(JvmIdentifiableElement identifiable, XAbstractFeatureCall featureCall, Object receiver,
		IEvaluationContext context, CancelIndicator indicator) {
	if (receiver != null)
		throw new IllegalStateException("feature was simple feature call but got receiver instead of null. Receiver: " + receiver);
	String localVarName = featureNameProvider.getSimpleName(identifiable);
	Object value = context.getValue(QualifiedName.create(localVarName));
	return value;
}
 
Example #20
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Object assignValueTo(JvmIdentifiableElement feature, XAbstractFeatureCall assignment, Object value, IEvaluationContext context, CancelIndicator indicator) {
	if (feature instanceof XVariableDeclaration) {
		return _assignValueTo((XVariableDeclaration) feature, assignment, value, context, indicator);
	} else if (feature instanceof JvmField) {
		return _assignValueTo((JvmField) feature, assignment, value, context, indicator);
	} else if (feature instanceof JvmOperation) {
		return _assignValueTo((JvmOperation) feature, assignment, value, context, indicator);
	} else {
		throw new IllegalArgumentException("Couldn't invoke 'assignValueTo' for feature "+feature+"");
	}
}
 
Example #21
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param assignment unused in this context but required for dispatching
 * @param indicator unused in this context but required for dispatching
 */
protected Object _assignValueTo(XVariableDeclaration variable, XAbstractFeatureCall assignment, Object value,
		IEvaluationContext context, CancelIndicator indicator) {
	if (variable.getType() != null) {
		JvmTypeReference type = variable.getType();
		Object coerced = coerceArgumentType(value, type);
		context.assignValue(QualifiedName.create(variable.getName()), coerced);
	} else {
		context.assignValue(QualifiedName.create(variable.getName()), value);
	}
	return value;
}
 
Example #22
Source File: ClosureInvocationHandler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Object doInvoke(Method method, Object[] args) throws Throwable {
	IEvaluationContext forkedContext = context.fork();
	if (args != null) {
		initializeClosureParameters(forkedContext, args);
	}
	IEvaluationResult result = interpreter.evaluate(closure.getExpression(), forkedContext, indicator);
	if (indicator.isCanceled())
		throw new InterpreterCanceledException();
	if (result.getException() != null)
		throw result.getException();
	return result.getResult();
}
 
Example #23
Source File: ClosureInvocationHandler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void initializeClosureParameters(IEvaluationContext context, Object[] args) {
	if (args.length != closure.getFormalParameters().size())
		throw new IllegalStateException("Number of arguments did not match. Expected: " + 
				closure.getFormalParameters().size() + " but was: " + args.length);
	int i = 0;
	for(JvmFormalParameter param: closure.getFormalParameters()) {
		context.newValue(QualifiedName.create(param.getName()), args[i]);
		i++;
	}
}
 
Example #24
Source File: ScriptImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute() throws ScriptExecutionException {
    if (xExpression != null) {
        Resource resource = xExpression.eResource();
        IEvaluationContext evaluationContext = null;
        if (resource instanceof XtextResource) {
            IResourceServiceProvider provider = ((XtextResource) resource).getResourceServiceProvider();
            evaluationContext = provider.get(IEvaluationContext.class);
        }
        return execute(evaluationContext);
    } else {
        throw new ScriptExecutionException("Script does not contain any expression");
    }
}
 
Example #25
Source File: ScriptImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(final IEvaluationContext evaluationContext) throws ScriptExecutionException {
    if (xExpression != null) {
        Resource resource = xExpression.eResource();
        IExpressionInterpreter interpreter = null;
        if (resource instanceof XtextResource) {
            IResourceServiceProvider provider = ((XtextResource) resource).getResourceServiceProvider();
            interpreter = provider.get(IExpressionInterpreter.class);
        }
        if (interpreter == null) {
            throw new ScriptExecutionException("Script interpreter couldn't be obtain");
        }
        try {
            IEvaluationResult result = interpreter.evaluate(xExpression, evaluationContext,
                    CancelIndicator.NullImpl);
            if (result == null) {
                // this can only happen on an InterpreterCancelledException,
                // i.e. NEVER ;-)
                return null;
            }
            if (result.getException() != null) {
                throw new ScriptExecutionException(result.getException().getMessage(), result.getException());
            }
            return result.getResult();
        } catch (Throwable e) {
            if (e instanceof ScriptExecutionException) {
                throw (ScriptExecutionException) e;
            } else {
                throw new ScriptExecutionException(
                        "An error occurred during the script execution: " + e.getMessage(), e);
            }
        }
    } else {
        throw new ScriptExecutionException("Script does not contain any expression");
    }
}
 
Example #26
Source File: DSLScriptEngine.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultEvaluationContext createEvaluationContext(IEvaluationContext specificContext) {
    DefaultEvaluationContext evalContext = new DefaultEvaluationContext(specificContext);
    for (Map.Entry<String, String> entry : implicitVars.entrySet()) {
        Object value = context.getAttribute(entry.getKey());
        if (value != null) {
            evalContext.newValue(QualifiedName.create(entry.getValue()), value);
        }
    }
    return evalContext;
}
 
Example #27
Source File: ScriptImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(final IEvaluationContext evaluationContext) throws ScriptExecutionException {
    if (xExpression != null) {
        Resource resource = xExpression.eResource();
        IExpressionInterpreter interpreter = null;
        if (resource instanceof XtextResource) {
            IResourceServiceProvider provider = ((XtextResource) resource).getResourceServiceProvider();
            interpreter = provider.get(IExpressionInterpreter.class);
        }
        if (interpreter == null) {
            throw new ScriptExecutionException("Script interpreter couldn't be obtain");
        }
        try {
            IEvaluationResult result = interpreter.evaluate(xExpression, evaluationContext,
                    CancelIndicator.NullImpl);
            if (result == null) {
                // this can only happen on an InterpreterCancelledException,
                // i.e. NEVER ;-)
                return null;
            }
            if (result.getException() != null) {
                throw new ScriptExecutionException(result.getException().getMessage(), result.getException());
            }
            return result.getResult();
        } catch (Throwable e) {
            if (e instanceof ScriptExecutionException) {
                throw (ScriptExecutionException) e;
            } else {
                throw new ScriptExecutionException(
                        "An error occurred during the script execution: " + e.getMessage(), e);
            }
        }
    } else {
        throw new ScriptExecutionException("Script does not contain any expression");
    }
}
 
Example #28
Source File: RuleContextHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Retrieves the evaluation context (= set of variables) for a ruleModel. The context is shared with all rules in
 * the
 * same model (= rule file).
 *
 * @param ruleModel the ruleModel to get the context for
 * @return the evaluation context
 */
public static synchronized IEvaluationContext getContext(RuleModel ruleModel) {
    Logger logger = LoggerFactory.getLogger(RuleContextHelper.class);
    Injector injector = RulesStandaloneSetup.getInjector();

    // check if a context already exists on the resource
    for (Adapter adapter : ruleModel.eAdapters()) {
        if (adapter instanceof RuleContextAdapter) {
            return ((RuleContextAdapter) adapter).getContext();
        }
    }
    Provider<@NonNull IEvaluationContext> contextProvider = injector.getProvider(IEvaluationContext.class);
    // no evaluation context found, so create a new one
    ScriptEngine scriptEngine = injector.getInstance(ScriptEngine.class);
    IEvaluationContext evaluationContext = contextProvider.get();
    for (VariableDeclaration var : ruleModel.getVariables()) {
        try {
            Object initialValue = var.getRight() == null ? null
                    : scriptEngine.newScriptFromXExpression(var.getRight()).execute();
            evaluationContext.newValue(QualifiedName.create(var.getName()), initialValue);
        } catch (ScriptExecutionException e) {
            logger.warn("Variable '{}' on rule file '{}' cannot be initialized with value '{}': {}", var.getName(),
                    ruleModel.eResource().getURI().path(), var.getRight(), e.getMessage());
        }
    }
    ruleModel.eAdapters().add(new RuleContextAdapter(evaluationContext));
    return evaluationContext;
}
 
Example #29
Source File: DSLRuleProviderTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testVars() {
    Collection<Rule> rules = dslRuleProvider.getAll();
    assertThat(rules.size(), is(0));

    String model = "var x = 3 * 5\n\n" + //
            "rule FirstRule\n" + //
            "when\n" + //
            "   System started\n" + //
            "then\n" + //
            "   logInfo('Test', 'Test')\n" + //
            "end\n\n";

    modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
    Collection<Rule> actualRules = dslRuleProvider.getAll();

    assertThat(actualRules.size(), is(1));

    Iterator<Rule> it = actualRules.iterator();

    Rule rule = it.next();

    assertThat(rule.getUID(), is("dslruletest-1"));
    assertThat(rule.getName(), is("FirstRule"));
    assertThat(rule.getTriggers().size(), is(1));

    IEvaluationContext context = dslRuleProvider.getContext("dslruletest");
    assertThat(context, is(notNullValue()));
    Object x = context.getValue(QualifiedName.create("x"));
    assertThat(x, is(15));
}
 
Example #30
Source File: ScriptImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute() throws ScriptExecutionException {
    if (xExpression != null) {
        Resource resource = xExpression.eResource();
        IEvaluationContext evaluationContext = null;
        if (resource instanceof XtextResource) {
            IResourceServiceProvider provider = ((XtextResource) resource).getResourceServiceProvider();
            evaluationContext = provider.get(IEvaluationContext.class);
        }
        return execute(evaluationContext);
    } else {
        throw new ScriptExecutionException("Script does not contain any expression");
    }
}