Java Code Examples for javax.el.ValueExpression#getValue()

The following examples show how to use javax.el.ValueExpression#getValue() . 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: TestValueExpressionImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetValueReference() {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl();

    TesterBeanB beanB = new TesterBeanB();
    beanB.setName("Tomcat");
    ValueExpression var =
        factory.createValueExpression(beanB, TesterBeanB.class);
    context.getVariableMapper().setVariable("beanB", var);

    ValueExpression ve = factory.createValueExpression(
            context, "${beanB.name}", String.class);

    // First check the basics work
    String result = (String) ve.getValue(context);
    assertEquals("Tomcat", result);

    // Now check the value reference
    ValueReference vr = ve.getValueReference(context);
    assertNotNull(vr);

    assertEquals(beanB, vr.getBase());
    assertEquals("name", vr.getProperty());
}
 
Example 2
Source File: TestValueExpressionImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug56522SetNullValue() {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl(factory);

    TesterBeanB beanB = new TesterBeanB();
    beanB.setName("Tomcat");
    ValueExpression var =
        factory.createValueExpression(beanB, TesterBeanB.class);
    context.getVariableMapper().setVariable("beanB", var);

    ValueExpression ve = factory.createValueExpression(
            context, "${beanB.name}", String.class);

    // First check the basics work
    String result = (String) ve.getValue(context);
    Assert.assertEquals("Tomcat", result);

    // Now set the value to null
    ve.setValue(context, null);

    Assert.assertEquals("", beanB.getName());
}
 
Example 3
Source File: TestMethodExpressionImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug53792a() {
    MethodExpression me = factory.createMethodExpression(context,
            "${beanA.setBean(beanB)}", null ,
            new Class<?>[] { TesterBeanB.class });
    me.invoke(context, null);
    me = factory.createMethodExpression(context,
            "${beanB.setName('" + BUG53792 + "')}", null ,
            new Class<?>[] { TesterBeanB.class });
    me.invoke(context, null);

    ValueExpression ve = factory.createValueExpression(context,
            "#{beanA.getBean().name}", java.lang.String.class);
    String actual = (String) ve.getValue(context);
    assertEquals(BUG53792, actual);
}
 
Example 4
Source File: TestValueExpressionImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug50105() {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl(factory);

    TesterEnum testEnum = TesterEnum.APPLE;

    ValueExpression var =
        factory.createValueExpression(testEnum, TesterEnum.class);
    context.getVariableMapper().setVariable("testEnum", var);

    // When coercing an Enum to a String, name() should always be used.
    ValueExpression ve1 = factory.createValueExpression(
            context, "${testEnum}", String.class);
    String result1 = (String) ve1.getValue(context);
    Assert.assertEquals("APPLE", result1);

    ValueExpression ve2 = factory.createValueExpression(
            context, "foo${testEnum}bar", String.class);
    String result2 = (String) ve2.getValue(context);
    Assert.assertEquals("fooAPPLEbar", result2);
}
 
Example 5
Source File: TestValueExpressionImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug50105() {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl();

    TesterEnum testEnum = TesterEnum.APPLE;

    ValueExpression var =
        factory.createValueExpression(testEnum, TesterEnum.class);
    context.getVariableMapper().setVariable("testEnum", var);

    // When coercing an Enum to a String, name() should always be used.
    ValueExpression ve1 = factory.createValueExpression(
            context, "${testEnum}", String.class);
    String result1 = (String) ve1.getValue(context);
    assertEquals("APPLE", result1);

    ValueExpression ve2 = factory.createValueExpression(
            context, "foo${testEnum}bar", String.class);
    String result2 = (String) ve2.getValue(context);
    assertEquals("fooAPPLEbar", result2);
}
 
Example 6
Source File: TestMethodExpressionImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug53792b() {
    MethodExpression me = factory.createMethodExpression(context,
            "${beanA.setBean(beanB)}", null ,
            new Class<?>[] { TesterBeanB.class });
    me.invoke(context, null);
    me = factory.createMethodExpression(context,
            "${beanB.setName('" + BUG53792 + "')}", null ,
            new Class<?>[] { TesterBeanB.class });
    me.invoke(context, null);

    ValueExpression ve = factory.createValueExpression(context,
            "#{beanA.getBean().name.length()}", java.lang.Integer.class);
    Integer actual = (Integer) ve.getValue(context);
    assertEquals(Integer.valueOf(BUG53792.length()), actual);
}
 
Example 7
Source File: TestELParser.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestBug56179(int parenthesesCount, String innerExpr) {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl(factory);

    ValueExpression var =
        factory.createValueExpression(Boolean.TRUE, Boolean.class);
    context.getVariableMapper().setVariable("test", var);

    StringBuilder expr = new StringBuilder();
    expr.append("${");
    for (int i = 0; i < parenthesesCount; i++) {
        expr.append("(");
    }
    expr.append(innerExpr);
    for (int i = 0; i < parenthesesCount; i++) {
        expr.append(")");
    }
    expr.append("}");
    ValueExpression ve = factory.createValueExpression(
            context, expr.toString(), String.class);

    String result = (String) ve.getValue(context);
    Assert.assertEquals("true", result);
}
 
Example 8
Source File: ValueExpressionHelper.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
/**
 * Source adapted from Seam's enumConverter. The goal is to get the type to which this component's value is bound.
 * First, check if the valueExpression provides the type. For dropdown-like components, this may not work, so check
 * for SelectItems children.
 * 
 * @param context the current FacesContext
 * @param uiComponent
 * @param validTypes a list of types to look for
 * @return null if a valid type cannot be found
 */
public static Class<?> getValueType(FacesContext context, UIComponent uiComponent, Collection<Class<?>> validTypes) {
	Class<?> valueType = getValueType(context, uiComponent);
	if (valueType != null && isValid(validTypes, valueType)) {
		return valueType;
	}
	else {
		for (UIComponent child : uiComponent.getChildren()) {
			UIComponent c = (UIComponent) child;
			ValueExpression expr = c.getValueExpression("value");
			Object val = expr == null ? null : expr.getValue(context.getELContext());
			if (val != null) {

				valueType = val.getClass();
				if (valueType.isArray() && isValid(validTypes, valueType.getComponentType())) {
					return valueType;
				}
				else if (val instanceof Collection<?>) {
					valueType = ((Collection<?>) val).iterator().next().getClass();
					if (isValid(validTypes, valueType)) {
						return valueType;
					}
				}
			}
		}
	}
	return null;
}
 
Example 9
Source File: TabRepeat.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
public Integer getEnd() {

		if (this.end != null) {
			return end;
		}
		ValueExpression ve = this.getValueExpression("end");
		if (ve != null) {
			return (Integer) ve.getValue(getFacesContext().getELContext());
		}
		return null;

	}
 
Example 10
Source File: TestMethodExpressionImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeWithSuper() {
    MethodExpression me = factory.createMethodExpression(context,
            "${beanA.setBean(beanBB)}", null ,
            new Class<?>[] { TesterBeanB.class });
    me.invoke(context, null);
    ValueExpression ve = factory.createValueExpression(context,
            "${beanA.bean.name}", String.class);
    Object r = ve.getValue(context);
    assertEquals("BB", r);
}
 
Example 11
Source File: TestMethodExpressionImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug52970() {
    MethodExpression me = factory.createMethodExpression(context,
            "${beanEnum.submit('APPLE')}", null ,
            new Class<?>[] { TesterBeanEnum.class });
    me.invoke(context, null);

    ValueExpression ve = factory.createValueExpression(context,
            "#{beanEnum.lastSubmitted}", TesterEnum.class);
    TesterEnum actual = (TesterEnum) ve.getValue(context);
    assertEquals(TesterEnum.APPLE, actual);

}
 
Example 12
Source File: TestValueExpressionImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug49345() {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl(factory);

    TesterBeanA beanA = new TesterBeanA();
    TesterBeanB beanB = new TesterBeanB();
    beanB.setName("Tomcat");
    beanA.setBean(beanB);

    ValueExpression var =
        factory.createValueExpression(beanA, TesterBeanA.class);
    context.getVariableMapper().setVariable("beanA", var);

    ValueExpression ve = factory.createValueExpression(
            context, "${beanA.bean.name}", String.class);

    // First check the basics work
    String result = (String) ve.getValue(context);
    Assert.assertEquals("Tomcat", result);

    // Now check the value reference
    ValueReference vr = ve.getValueReference(context);
    Assert.assertNotNull(vr);

    Assert.assertEquals(beanB, vr.getBase());
    Assert.assertEquals("name", vr.getProperty());
}
 
Example 13
Source File: TestELParser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void testExpression(String expression, String expected) {
    ExpressionFactory factory = ExpressionFactory.newInstance();
    ELContext context = new ELContextImpl(factory);

    ValueExpression ve = factory.createValueExpression(
            context, expression, String.class);

    String result = (String) ve.getValue(context);
    Assert.assertEquals(expected, result);
}
 
Example 14
Source File: ResourceHandlerWrapper.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void handleResourceRequest(FacesContext context) throws IOException {
	Map<String, String> params = context.getExternalContext().getRequestParameterMap();
	String library = params.get("ln");
	String dynamicContentId = params.get(Constants.DYNAMIC_CONTENT_PARAM);
	if (dynamicContentId != null && library != null && library.equals("primefaces")) {
		Map<String, Object> session = context.getExternalContext().getSessionMap();
		try {
			String dynamicContentEL = (String) session.get(dynamicContentId);
			if (!ALLOWED_EXPRESSIONS.contains(dynamicContentEL)) {
				throw new Exception("prevented EL " + dynamicContentEL);
			}
			System.out.println(dynamicContentEL);
			ELContext elContext = context.getELContext();
			ValueExpression ve = context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(), dynamicContentEL, StreamedContent.class);
			StreamedContent content = (StreamedContent) ve.getValue(elContext);
			HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
			response.setContentType(content.getContentType());
			byte[] buffer = new byte[2048];
			int length;
			InputStream inputStream = content.getStream();
			while ((length = (inputStream.read(buffer))) >= 0) {
				response.getOutputStream().write(buffer, 0, length);
			}
			response.setStatus(200);
			response.getOutputStream().flush();
			context.responseComplete();
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Error in streaming dynamic resource" + e.getMessage());
		} finally {
			session.remove(dynamicContentId);
		}
	} else {
		super.handleResourceRequest(context);
	}
}
 
Example 15
Source File: TestMethodExpressionImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug50790a() throws Exception {
    ValueExpression ve = factory.createValueExpression(context,
            "#{beanAA.name.contains(beanA.name)}", java.lang.Boolean.class);
    Boolean actual = (Boolean) ve.getValue(context);
    assertEquals(Boolean.TRUE, actual);
}
 
Example 16
Source File: TestAttributeParser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private String evalAttr(String expression, char quote) {

        ExpressionFactoryImpl exprFactory = new ExpressionFactoryImpl();
        ELContextImpl ctx = new ELContextImpl(exprFactory);
        ctx.setFunctionMapper(new TesterFunctions.FMapper());
        ValueExpression ve = exprFactory.createValueExpression(ctx,
                AttributeParser.getUnquoted(expression, quote, false, false,
                        false, false),
                String.class);
        return (String) ve.getValue(ctx);
    }
 
Example 17
Source File: RuleEvaluator.java    From proctor with Apache License 2.0 5 votes vote down vote up
public boolean evaluateBooleanRule(final String rule, @Nonnull final Map<String, Object> values) throws IllegalArgumentException {
    if (StringUtils.isBlank(rule)) {
        return true;
    }
    if (!rule.startsWith("${") || !rule.endsWith("}")) {
        LOGGER.error("Invalid rule '" +  rule + "'");   //  TODO: should this be an exception?
        return false;
    }
    final String bareRule = ProctorUtils.removeElExpressionBraces(rule);
    if (StringUtils.isBlank(bareRule) || "true".equalsIgnoreCase(bareRule)) {
        return true;    //  always passes
    }
    if ("false".equalsIgnoreCase(bareRule)) {
        return false;
    }

    final ELContext elContext = createElContext(values);
    final ValueExpression ve = expressionFactory.createValueExpression(elContext, rule, boolean.class);
    checkRuleIsBooleanType(rule, elContext, ve);

    final Object result = ve.getValue(elContext);

    if (result instanceof Boolean) {
        return ((Boolean) result);
    }
    // this should never happen, evaluateRule throws ELException when it cannot coerce to Boolean
    throw new IllegalArgumentException("Received non-boolean return value: "
            + (result == null ? "null" : result.getClass().getCanonicalName())
            + " from rule " + rule);
}
 
Example 18
Source File: TestMethodExpressionImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug52970() {
    MethodExpression me = factory.createMethodExpression(context,
            "${beanEnum.submit('APPLE')}", null ,
            new Class<?>[] { TesterBeanEnum.class });
    me.invoke(context, null);

    ValueExpression ve = factory.createValueExpression(context,
            "#{beanEnum.lastSubmitted}", TesterEnum.class);
    TesterEnum actual = (TesterEnum) ve.getValue(context);
    assertEquals(TesterEnum.APPLE, actual);

}
 
Example 19
Source File: BenchmarkEl.java    From proctor with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) {
    final FunctionMapper functionMapper = new LibraryFunctionMapperBuilder().add("proctor", ProctorRuleFunctions.class).build();

    final ExpressionFactory expressionFactory = new ExpressionFactoryImpl();

    final CompositeELResolver elResolver = new CompositeELResolver();
    elResolver.add(new ArrayELResolver());
    elResolver.add(new ListELResolver());
    elResolver.add(new BeanELResolver());
    elResolver.add(new MapELResolver());

    final Map<String, Object> values = Maps.newLinkedHashMap();
    values.put("countries", Sets.newHashSet("AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM"));
    values.put("AA", "AA");
    values.put("CC", "CC");
    values.put("NN", "NN");
    values.put("ZZ", "ZZ");
    values.put("I1", 239235);
    values.put("I2", 569071142);
    values.put("I3", -189245);
    values.put("D1", 129835.12512);
    values.put("D2", -9582.9385);
    values.put("D3", 98982223.598731412);
    values.put("BT", Boolean.TRUE);
    values.put("BF", Boolean.FALSE);
    values.put("GLOOP", "");

    final String[] expressions = {
            "${proctor:contains(countries, AA) || proctor:contains(countries, CC) || D2 < I3 && BF}",
            "${! proctor:contains(countries, ZZ) && I1 < I2 && empty GLOOP}",
            "${I2 - I3 + D3 - D1}",
            "${NN == '0' && ZZ == 'ZZ'}",
            "${BT != BF}",
    };

    final int iterations = 100*1000;
    long elapsed = -System.currentTimeMillis();
    for (int i = 0; i < iterations; i++) {
        final Map<String, ValueExpression> localContext = ProctorUtils.convertToValueExpressionMap(expressionFactory, values);
        final VariableMapper variableMapper = new MulticontextReadOnlyVariableMapper(localContext);

        final ELContext elContext = new ELContext() {
            @Override
            public ELResolver getELResolver() {
                return elResolver;
            }

            @Override
            public FunctionMapper getFunctionMapper() {
                return functionMapper;
            }

            @Override
            public VariableMapper getVariableMapper() {
                return variableMapper;
            }
        };

        for (int j = 0; j < expressions.length; j++) {
            final ValueExpression ve = expressionFactory.createValueExpression(elContext, expressions[j], Object.class);
            final Object result = ve.getValue(elContext);
            if (i % 10000 == 0) {
                System.out.println(result);
            }
        }
    }
    elapsed += System.currentTimeMillis();

    final int total = iterations * expressions.length;
    System.out.println(total + " expressions in " + elapsed + " ms (average " + (elapsed/(((double) total))) + " ms/expression)");
}
 
Example 20
Source File: AstIdentifier.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public Object getValue(EvaluationContext ctx) throws ELException {
    // Lambda parameters
    if (ctx.isLambdaArgument(this.image)) {
        return ctx.getLambdaArgument(this.image);
    }

    // Variable mapper
    VariableMapper varMapper = ctx.getVariableMapper();
    if (varMapper != null) {
        ValueExpression expr = varMapper.resolveVariable(this.image);
        if (expr != null) {
            return expr.getValue(ctx.getELContext());
        }
    }

    // EL Resolvers
    ctx.setPropertyResolved(false);
    Object result;
    /* Putting the Boolean into the ELContext is part of a performance
     * optimisation for ScopedAttributeELResolver. When looking up "foo",
     * the resolver can't differentiate between ${ foo } and ${ foo.bar }.
     * This is important because the expensive class lookup only needs to
     * be performed in the later case. This flag tells the resolver if the
     * lookup can be skipped.
     */
    if (parent instanceof AstValue) {
        ctx.putContext(this.getClass(), Boolean.FALSE);
    } else {
        ctx.putContext(this.getClass(), Boolean.TRUE);
    }
    try {
        result = ctx.getELResolver().getValue(ctx, null, this.image);
    } finally {
        // Always reset the flag to false so the optimisation is not applied
        // inappropriately
        ctx.putContext(this.getClass(), Boolean.FALSE);
    }

    if (ctx.isPropertyResolved()) {
        return result;
    }

    // Import
    result = ctx.getImportHandler().resolveClass(this.image);
    if (result != null) {
        return new ELClass((Class<?>) result);
    }
    result = ctx.getImportHandler().resolveStatic(this.image);
    if (result != null) {
        try {
            return ((Class<?>) result).getField(this.image).get(null);
        } catch (IllegalArgumentException | IllegalAccessException
                | NoSuchFieldException | SecurityException e) {
            throw new ELException(e);
        }
    }

    throw new PropertyNotFoundException(MessageFactory.get(
            "error.resolver.unhandled.null", this.image));
}