protected void setProperties(UIComponent component) { super.setProperties(component); javax.faces.component.UIOutput output = null; try { output = (javax.faces.component.UIOutput) component; } catch (ClassCastException cce) { throw new IllegalStateException( "Component " + component.toString() + " not expected type. Expected: javax.faces.component.UIOutput. Perhaps you're missing a tag?"); } if (converter != null) { if (!converter.isLiteralText()) { output.setValueExpression("converter", converter); } else { Converter conv = FacesContext.getCurrentInstance() .getApplication() .createConverter(converter.getExpressionString()); output.setConverter(conv); } } if (value != null) { if (!value.isLiteralText()) { output.setValueExpression("value", value); } else { output.setValue(value.getExpressionString()); } } if (escape != null) { if (!escape.isLiteralText()) { output.setValueExpression("escape", escape); } else { output .getAttributes() .put("escape", java.lang.Boolean.valueOf(escape.getExpressionString())); } } if (style != null) { if (!style.isLiteralText()) { output.setValueExpression("style", style); } else { output.getAttributes().put("style", style.getExpressionString()); } } if (styleClass != null) { if (!styleClass.isLiteralText()) { output.setValueExpression("styleClass", styleClass); } else { output.getAttributes().put("styleClass", styleClass.getExpressionString()); } } }
public Object getAsObject(FacesContext context, UIComponent component, String value) { Converter delegate = getDelegate(context); if (delegate != null) { return delegate.getAsObject(context, component, value); } else { throw new ConverterException( MessageUtils.getExceptionMessage( MessageUtils.CANNOT_CONVERT_ID, converterId != null ? converterId.getExpressionString() : "", binding != null ? binding.getExpressionString() : "")); } }
/** * Perform the correctness checks implemented by this {@link javax.faces.validator.Validator} * against the specified {@link javax.faces.component.UIComponent}. If any violations are found, * a {@link javax.faces.validator.ValidatorException} will be thrown containing the {@link * javax.faces.application.FacesMessage} describing the failure. * * @param context FacesContext for the request we are processing * @param component UIComponent we are checking for correctness * @param value the value to validate * @throws javax.faces.validator.ValidatorException if validation fails * @throws NullPointerException if <code>context</code> or <code>component</code> is <code>null * </code> */ public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { Validator instance = createValidator(validatorId, binding, context); if (instance != null) { instance.validate(context, component, value); } else { throw new ValidatorException( MessageUtils.getExceptionMessage( MessageUtils.CANNOT_VALIDATE_ID, validatorId != null ? validatorId.getExpressionString() : "", binding != null ? binding.getExpressionString() : "")); } }
/** * * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, * javax.faces.component.UIComponent) */ public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { VariableMapper origVarMap = ctx.getVariableMapper(); try { VariableMapperWrapper variableMap = new VariableMapperWrapper(origVarMap); ctx.setVariableMapper(variableMap); if (methodBindings != null) { String value = (String) methodBindings.getValue(ctx); Matcher match = METHOD_PATTERN.matcher(value); while (match.find()) { String var = match.group(1); ValueExpression currentExpression = origVarMap.resolveVariable(var); if (currentExpression != null) { try { FunctionMethodData methodData = new FunctionMethodData(var, match.group(2).split("\\s+")); MethodExpression mexpr = buildMethodExpression(ctx, currentExpression.getExpressionString(), methodData); variableMap.setVariable(var, new MethodValueExpression(currentExpression, mexpr)); } catch (Exception ex) { throw new FacesException(ex); } } } } componentHandler.apply(ctx, parent); } finally { ctx.setVariableMapper(origVarMap); } }
public static Object evaluateValueExpression(ValueExpression expression, ELContext elContext) { if (expression.isLiteralText()) { return expression.getExpressionString(); } else { return expression.getValue(elContext); } }
private boolean isResolvable(ValueReference ref, ValueExpression valueExpression) { Boolean result = null; String failureMessage = null; if (null == valueExpression) { failureMessage = "Unable to validate expression using Bean " + "Validation. Expression must not be null."; result = false; } else if (null == ref) { failureMessage = "Unable to validate expression " + valueExpression.getExpressionString() + " using Bean Validation. Unable to get value of expression."; result = false; } else { Class baseClass = ref.getBaseClass(); // case 1, base classes of Map, List, or Array are not resolvable if (null != baseClass) { if (Map.class.isAssignableFrom(baseClass) || Collection.class.isAssignableFrom(baseClass) || Array.class.isAssignableFrom(baseClass)) { failureMessage = "Unable to validate expression " + valueExpression.getExpressionString() + " using Bean Validation. Expression evaluates to a Map, List or array."; result = false; } } } result = ((null != result) ? result : true); if (!result) { LOGGER.fine(failureMessage); } return result; }
/** * Attempt to obtain the resource from the server by parsing the valueExpression of the image * attribute. Returns null if the valueExpression is not of the form * #{resource['path/to/resource']} or #{resource['library:name']}. Otherwise returns the value * obtained by ResourceHandler.createResource(). */ private Resource getImageResource(FacesContext facesContext, ImageCropper imageCropper) { Resource resource = null; ValueExpression imageValueExpression = imageCropper.getValueExpression(ImageCropper.PropertyKeys.image.toString()); if (imageValueExpression != null) { String imageValueExpressionString = imageValueExpression.getExpressionString(); if (imageValueExpressionString.matches("^[#][{]resource\\['[^']+'\\][}]$")) { imageValueExpressionString = imageValueExpressionString.replaceFirst("^[#][{]resource\\['", ""); imageValueExpressionString = imageValueExpressionString.replaceFirst("'\\][}]$", ""); String resourceLibrary = null; String resourceName; String[] resourceInfo = imageValueExpressionString.split(":"); if (resourceInfo.length == 2) { resourceLibrary = resourceInfo[0]; resourceName = resourceInfo[1]; } else { resourceName = resourceInfo[0]; } if (resourceName != null) { Application application = facesContext.getApplication(); ResourceHandler resourceHandler = application.getResourceHandler(); if (resourceLibrary != null) { resource = resourceHandler.createResource(resourceName, resourceLibrary); } else { resource = resourceHandler.createResource(resourceName); } } } } return resource; }
static Object saveWithType(ValueExpression expr, FacesContext context) { if (expr != null) { return new Object[] {expr.getExpressionString(), expr.getExpectedType()}; } else return null; }
protected void setProperties(UIComponent component) { super.setProperties(component); javax.faces.component.UISelectOne selectone = null; try { selectone = (javax.faces.component.UISelectOne) component; } catch (ClassCastException cce) { throw new IllegalStateException( "Component " + component.toString() + " not expected type. Expected: javax.faces.component.UISelectOne. Perhaps you're missing a tag?"); } if (converter != null) { if (!converter.isLiteralText()) { selectone.setValueExpression("converter", converter); } else { Converter conv = FacesContext.getCurrentInstance() .getApplication() .createConverter(converter.getExpressionString()); selectone.setConverter(conv); } } if (converterMessage != null) { selectone.setValueExpression("converterMessage", converterMessage); } if (immediate != null) { selectone.setValueExpression("immediate", immediate); } if (required != null) { selectone.setValueExpression("required", required); } if (requiredMessage != null) { selectone.setValueExpression("requiredMessage", requiredMessage); } if (validator != null) { selectone.addValidator(new MethodExpressionValidator(validator)); } if (validatorMessage != null) { selectone.setValueExpression("validatorMessage", validatorMessage); } if (value != null) { selectone.setValueExpression("value", value); } if (valueChangeListener != null) { selectone.addValueChangeListener( new MethodExpressionValueChangeListener(valueChangeListener)); } if (accesskey != null) { selectone.setValueExpression("accesskey", accesskey); } if (dir != null) { selectone.setValueExpression("dir", dir); } if (disabled != null) { selectone.setValueExpression("disabled", disabled); } if (disabledClass != null) { selectone.setValueExpression("disabledClass", disabledClass); } if (enabledClass != null) { selectone.setValueExpression("enabledClass", enabledClass); } if (label != null) { selectone.setValueExpression("label", label); } if (lang != null) { selectone.setValueExpression("lang", lang); } if (onblur != null) { selectone.setValueExpression("onblur", onblur); } if (onchange != null) { selectone.setValueExpression("onchange", onchange); } if (onclick != null) { selectone.setValueExpression("onclick", onclick); } if (ondblclick != null) { selectone.setValueExpression("ondblclick", ondblclick); } if (onfocus != null) { selectone.setValueExpression("onfocus", onfocus); } if (onkeydown != null) { selectone.setValueExpression("onkeydown", onkeydown); } if (onkeypress != null) { selectone.setValueExpression("onkeypress", onkeypress); } if (onkeyup != null) { selectone.setValueExpression("onkeyup", onkeyup); } if (onmousedown != null) { selectone.setValueExpression("onmousedown", onmousedown); } if (onmousemove != null) { selectone.setValueExpression("onmousemove", onmousemove); } if (onmouseout != null) { selectone.setValueExpression("onmouseout", onmouseout); } if (onmouseover != null) { selectone.setValueExpression("onmouseover", onmouseover); } if (onmouseup != null) { selectone.setValueExpression("onmouseup", onmouseup); } if (onselect != null) { selectone.setValueExpression("onselect", onselect); } if (readonly != null) { selectone.setValueExpression("readonly", readonly); } if (style != null) { selectone.setValueExpression("style", style); } if (styleClass != null) { selectone.setValueExpression("styleClass", styleClass); } if (tabindex != null) { selectone.setValueExpression("tabindex", tabindex); } if (title != null) { selectone.setValueExpression("title", title); } }
/** * @see ViewHandler#retargetMethodExpressions(javax.faces.context.FacesContext, * javax.faces.component.UIComponent) */ @Override public void retargetMethodExpressions(FacesContext context, UIComponent topLevelComponent) { BeanInfo componentBeanInfo = (BeanInfo) topLevelComponent.getAttributes().get(UIComponent.BEANINFO_KEY); // PENDING(edburns): log error message if componentBeanInfo is null; if (null == componentBeanInfo) { return; } PropertyDescriptor attributes[] = componentBeanInfo.getPropertyDescriptors(); String targets = null, attrName = null, strValue = null, methodSignature = null; UIComponent target = null; ExpressionFactory expressionFactory = null; ValueExpression valueExpression = null; MethodExpression toApply = null; Class expectedReturnType = null; Class expectedParameters[] = null; for (PropertyDescriptor cur : attributes) { // If the current attribute represents a ValueExpression if (null != (valueExpression = (ValueExpression) cur.getValue("type"))) { // take no action on this attribute. continue; } // If the current attribute representes a MethodExpression if (null != (valueExpression = (ValueExpression) cur.getValue("method-signature"))) { methodSignature = (String) valueExpression.getValue(context.getELContext()); if (null != methodSignature) { // This is the name of the attribute on the top level component, // and on the inner component. if (null != (valueExpression = (ValueExpression) cur.getValue("targets"))) { targets = (String) valueExpression.getValue(context.getELContext()); } if (null == targets) { targets = cur.getName(); } if (null == targets || 0 == targets.length()) { // PENDING error message in page? logger.severe("Unable to retarget MethodExpression: " + methodSignature); continue; } String[] targetIds = targets.split(" "); for (String curTarget : targetIds) { attrName = cur.getName(); // Find the attribute on the top level component valueExpression = (ValueExpression) topLevelComponent.getAttributes().get(attrName); if (null == valueExpression) { // PENDING error message in page? logger.severe( "Unable to find attribute with name \"" + attrName + "\" in top level component in consuming page. " + "Page author error."); continue; } // lazily initialize this local variable if (null == expressionFactory) { expressionFactory = context.getApplication().getExpressionFactory(); } // If the attribute is one of the pre-defined // MethodExpression attributes boolean isAction = false, isActionListener = false, isValidator = false, isValueChangeListener = false; if ((isAction = attrName.equals("action")) || (isActionListener = attrName.equals("actionListener")) || (isValidator = attrName.equals("validator")) || (isValueChangeListener = attrName.equals("valueChangeListener"))) { // This is the inner component to which the attribute should // be applied target = topLevelComponent.findComponent(curTarget); if (null == targets) { // PENDING error message in page? logger.severe( "Unable to retarget MethodExpression. " + "Unable to find inner component with id " + targets + "."); continue; } if (isAction) { expectedReturnType = Object.class; expectedParameters = new Class[] {}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((ActionSource2) target).setActionExpression(toApply); } else if (isActionListener) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {ActionEvent.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((ActionSource2) target) .addActionListener(new MethodExpressionActionListener(toApply)); } else if (isValidator) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {FacesContext.class, UIComponent.class, Object.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((EditableValueHolder) target).addValidator(new MethodExpressionValidator(toApply)); } else if (isValueChangeListener) { expectedReturnType = Void.TYPE; expectedParameters = new Class[] {ValueChangeEvent.class}; toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); ((EditableValueHolder) target) .addValueChangeListener(new MethodExpressionValueChangeListener(toApply)); } } else { // There is no explicit methodExpression property on // an inner component to which this MethodExpression // should be retargeted. In this case, replace the // ValueExpression with a method expresson. // Pull apart the methodSignature to derive the // expectedReturnType and expectedParameters // PENDING(rlubke,jimdriscoll) bulletproof this assert (null != methodSignature); methodSignature = methodSignature.trim(); // Get expectedReturnType int j, i = methodSignature.indexOf(" "); if (-1 != i) { strValue = methodSignature.substring(0, i); try { expectedReturnType = Util.getTypeFromString(strValue); } catch (ClassNotFoundException cnfe) { logger.log( Level.SEVERE, "Unable to determine expected return type for " + methodSignature, cnfe); continue; } } else { logger.severe("Unable to determine expected return type for " + methodSignature); continue; } // derive the arguments i = methodSignature.indexOf("("); if (-1 != i) { j = methodSignature.indexOf(")", i + 1); if (-1 != j) { strValue = methodSignature.substring(i + 1, j); if (0 < strValue.length()) { String[] params = strValue.split(","); expectedParameters = new Class[params.length]; boolean exceptionThrown = false; for (i = 0; i < params.length; i++) { try { expectedParameters[i] = Util.getTypeFromString(params[i]); } catch (ClassNotFoundException cnfe) { logger.log( Level.SEVERE, "Unable to determine expected return type for " + methodSignature, cnfe); exceptionThrown = true; break; } } if (exceptionThrown) { continue; } } else { expectedParameters = new Class[] {}; } } } assert (null != expectedReturnType); assert (null != expectedParameters); toApply = expressionFactory.createMethodExpression( context.getELContext(), valueExpression.getExpressionString(), expectedReturnType, expectedParameters); topLevelComponent.getAttributes().put(attrName, toApply); } } } } } }
protected void setProperties(UIComponent component) { super.setProperties(component); javax.faces.component.UICommand command = null; try { command = (javax.faces.component.UICommand) component; } catch (ClassCastException cce) { throw new IllegalStateException( "Component " + component.toString() + " not expected type. Expected: javax.faces.component.UICommand. Perhaps you're missing a tag?"); } if (action != null) { command.setActionExpression(action); } if (actionListener != null) { command.addActionListener(new MethodExpressionActionListener(actionListener)); } if (immediate != null) { if (!immediate.isLiteralText()) { command.setValueExpression("immediate", immediate); } else { command.setImmediate( java.lang.Boolean.valueOf(immediate.getExpressionString()).booleanValue()); } } if (label != null) { if (!label.isLiteralText()) { command.setValueExpression("label", label); } else { command.getAttributes().put("label", label.getExpressionString()); } } if (oncommand != null) { if (!oncommand.isLiteralText()) { command.setValueExpression("oncommand", oncommand); } else { command.getAttributes().put("oncommand", oncommand.getExpressionString()); } } if (onclick != null) { if (!onclick.isLiteralText()) { command.setValueExpression("onclick", onclick); } else { command.getAttributes().put("onclick", onclick.getExpressionString()); } } if (onfocusin != null) { if (!onfocusin.isLiteralText()) { command.setValueExpression("onfocusin", onfocusin); } else { command.getAttributes().put("onfocusin", onfocusin.getExpressionString()); } } if (onfocusout != null) { if (!onfocusout.isLiteralText()) { command.setValueExpression("onfocusout", onfocusout); } else { command.getAttributes().put("onfocusout", onfocusout.getExpressionString()); } } if (onmousedown != null) { if (!onmousedown.isLiteralText()) { command.setValueExpression("onmousedown", onmousedown); } else { command.getAttributes().put("onmousedown", onmousedown.getExpressionString()); } } if (onmousemove != null) { if (!onmousemove.isLiteralText()) { command.setValueExpression("onmousemove", onmousemove); } else { command.getAttributes().put("onmousemove", onmousemove.getExpressionString()); } } if (onmouseout != null) { if (!onmouseout.isLiteralText()) { command.setValueExpression("onmouseout", onmouseout); } else { command.getAttributes().put("onmouseout", onmouseout.getExpressionString()); } } if (onmouseover != null) { if (!onmouseover.isLiteralText()) { command.setValueExpression("onmouseover", onmouseover); } else { command.getAttributes().put("onmouseover", onmouseover.getExpressionString()); } } if (onmouseup != null) { if (!onmouseup.isLiteralText()) { command.setValueExpression("onmouseup", onmouseup); } else { command.getAttributes().put("onmouseup", onmouseup.getExpressionString()); } } if (style != null) { if (!style.isLiteralText()) { command.setValueExpression("style", style); } else { command.getAttributes().put("style", style.getExpressionString()); } } if (styleClass != null) { if (!styleClass.isLiteralText()) { command.setValueExpression("styleClass", styleClass); } else { command.getAttributes().put("styleClass", styleClass.getExpressionString()); } } if (type != null) { if (!type.isLiteralText()) { command.setValueExpression("type", type); } else { command.getAttributes().put("type", type.getExpressionString()); } } if (value != null) { if (!value.isLiteralText()) { command.setValueExpression("value", value); } else { command.setValue(value.getExpressionString()); } } }
protected void setProperties(UIComponent component) { super.setProperties(component); javax.faces.component.UIPanel panel = null; try { panel = (javax.faces.component.UIPanel) component; } catch (ClassCastException cce) { throw new IllegalStateException( "Component " + component.toString() + " not expected type. Expected: javax.faces.component.UIPanel. Perhaps you're missing a tag?"); } if (bgcolor != null) { if (!bgcolor.isLiteralText()) { panel.setValueExpression("bgcolor", bgcolor); } else { panel.getAttributes().put("bgcolor", bgcolor.getExpressionString()); } } if (border != null) { if (!border.isLiteralText()) { panel.setValueExpression("border", border); } else { panel .getAttributes() .put("border", java.lang.Integer.valueOf(border.getExpressionString())); } } if (columnClasses != null) { if (!columnClasses.isLiteralText()) { panel.setValueExpression("columnClasses", columnClasses); } else { panel.getAttributes().put("columnClasses", columnClasses.getExpressionString()); } } if (columns != null) { if (!columns.isLiteralText()) { panel.setValueExpression("columns", columns); } else { panel .getAttributes() .put("columns", java.lang.Integer.valueOf(columns.getExpressionString())); } } if (onclick != null) { if (!onclick.isLiteralText()) { panel.setValueExpression("onclick", onclick); } else { panel.getAttributes().put("onclick", onclick.getExpressionString()); } } if (ondblclick != null) { if (!ondblclick.isLiteralText()) { panel.setValueExpression("ondblclick", ondblclick); } else { panel.getAttributes().put("ondblclick", ondblclick.getExpressionString()); } } if (onkeydown != null) { if (!onkeydown.isLiteralText()) { panel.setValueExpression("onkeydown", onkeydown); } else { panel.getAttributes().put("onkeydown", onkeydown.getExpressionString()); } } if (onkeypress != null) { if (!onkeypress.isLiteralText()) { panel.setValueExpression("onkeypress", onkeypress); } else { panel.getAttributes().put("onkeypress", onkeypress.getExpressionString()); } } if (onkeyup != null) { if (!onkeyup.isLiteralText()) { panel.setValueExpression("onkeyup", onkeyup); } else { panel.getAttributes().put("onkeyup", onkeyup.getExpressionString()); } } if (onmousedown != null) { if (!onmousedown.isLiteralText()) { panel.setValueExpression("onmousedown", onmousedown); } else { panel.getAttributes().put("onmousedown", onmousedown.getExpressionString()); } } if (onmousemove != null) { if (!onmousemove.isLiteralText()) { panel.setValueExpression("onmousemove", onmousemove); } else { panel.getAttributes().put("onmousemove", onmousemove.getExpressionString()); } } if (onmouseout != null) { if (!onmouseout.isLiteralText()) { panel.setValueExpression("onmouseout", onmouseout); } else { panel.getAttributes().put("onmouseout", onmouseout.getExpressionString()); } } if (onmouseover != null) { if (!onmouseover.isLiteralText()) { panel.setValueExpression("onmouseover", onmouseover); } else { panel.getAttributes().put("onmouseover", onmouseover.getExpressionString()); } } if (onmouseup != null) { if (!onmouseup.isLiteralText()) { panel.setValueExpression("onmouseup", onmouseup); } else { panel.getAttributes().put("onmouseup", onmouseup.getExpressionString()); } } if (rowClasses != null) { if (!rowClasses.isLiteralText()) { panel.setValueExpression("rowClasses", rowClasses); } else { panel.getAttributes().put("rowClasses", rowClasses.getExpressionString()); } } if (style != null) { if (!style.isLiteralText()) { panel.setValueExpression("style", style); } else { panel.getAttributes().put("style", style.getExpressionString()); } } if (styleClass != null) { if (!styleClass.isLiteralText()) { panel.setValueExpression("styleClass", styleClass); } else { panel.getAttributes().put("styleClass", styleClass.getExpressionString()); } } }
@Override public String getExpressionString() { return originalValueExpression.getExpressionString(); }
/** * <span class="changed_modified_2_3">Verify</span> that the value is valid according to the Bean * Validation constraints. <div class="changed_added_2_0"> * * <p>Obtain a {@link ValidatorFactory} instance by calling {@link * javax.validation.Validation#buildDefaultValidatorFactory}. * * <p>Let <em>validationGroupsArray</em> be a <code>Class []</code> representing validator groups * set on the component by the tag handler for this validator. The first search component * terminates the search for the validation groups value. If no such value is found use the class * name of {@link javax.validation.groups.Default} as the value of the validation groups. * * <p>Let <em>valueExpression</em> be the return from calling {@link * UIComponent#getValueExpression} on the argument <em>component</em>, passing the literal string * “value” (without the quotes) as an argument. If this application is running in an * environment with a Unified EL Implementation for Java EE6 or later, obtain the <code> * ValueReference</code> from <em>valueExpression</em> and let <em>valueBaseClase</em> be the * return from calling <code>ValueReference.getBase()</code> and <em>valueProperty</em> be the * return from calling <code>ValueReference.getProperty()</code>. If an earlier version of the * Unified EL is present, use the appropriate methods to inspect <em>valueExpression</em> and * derive values for <em>valueBaseClass</em> and <em>valueProperty</em>. * * <p>If no <code>ValueReference</code> can be obtained, take no action and return. * * <p>If <code>ValueReference.getBase()</code> return <code>null</code>, take no action and * return. * * <p>Obtain the {@link ValidatorContext} from the {@link ValidatorFactory}. * * <p>Decorate the {@link MessageInterpolator} returned from {@link * ValidatorFactory#getMessageInterpolator} with one that leverages the <code>Locale</code> * returned from {@link javax.faces.component.UIViewRoot#getLocale}, and store it in the <code> * ValidatorContext</code> using {@link ValidatorContext#messageInterpolator}. * * <p>Obtain the {@link javax.validation.Validator} instance from the <code>validatorContext * </code>. * * <p>Obtain a <code>javax.validation.BeanDescriptor</code> from the <code> * javax.validation.Validator</code>. If <code>hasConstraints()</code> on the <code>BeanDescriptor * </code> returns false, take no action and return. Otherwise proceed. * * <p>Call {@link javax.validation.Validator#validateValue}, passing <em>valueBaseClass</em>, * <em>valueProperty</em>, the <em>value</em> argument, and <em>validatorGroupsArray</em> as * arguments. * * <p>If the returned <code>Set<{@link * ConstraintViolation}></code> is non-empty, for each element in the <code>Set</code>, create * a {@link FacesMessage} where the summary and detail are the return from calling {@link * ConstraintViolation#getMessage}. Capture all such <code>FacesMessage</code> instances into a * <code>Collection</code> and pass them to {@link * ValidatorException#ValidatorException(java.util.Collection)}. <span * class="changed_added_2_3">If the {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application * parameter is enabled and this {@code Validator} instance has validation groups other than or in * addition to the {@code Default} group, record the fact that this field failed validation so * that any <code><f:validateWholeBean /></code> component later in the tree is able to skip * class-level validation for the bean for which this particular field is a property. Regardless * of whether or not {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} is set, throw the new * exception.</span> * * <p class="changed_added_2_3">If the returned {@code Set} is empty, the {@link * #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application parameter is enabled and this {@code * Validator} instance has validation groups other than or in addition to the {@code Default} * group, record the fact that this field passed validation so that any <code> * <f:validateWholeBean /></code> component later in the tree is able to allow class-level * validation for the bean for which this particular field is a property. </div> * * @param context {@inheritDoc} * @param component {@inheritDoc} * @param value {@inheritDoc} * @throws ValidatorException {@inheritDoc} */ @Override public void validate(FacesContext context, UIComponent component, Object value) { if (context == null) { throw new NullPointerException(); } if (component == null) { throw new NullPointerException(); } ValueExpression valueExpression = component.getValueExpression("value"); if (valueExpression == null) { return; } ValidatorFactory validatorFactory; Object cachedObject = context.getExternalContext().getApplicationMap().get(VALIDATOR_FACTORY_KEY); if (cachedObject instanceof ValidatorFactory) { validatorFactory = (ValidatorFactory) cachedObject; } else { try { validatorFactory = Validation.buildDefaultValidatorFactory(); } catch (ValidationException e) { throw new FacesException("Could not build a default Bean Validator factory", e); } context.getExternalContext().getApplicationMap().put(VALIDATOR_FACTORY_KEY, validatorFactory); } ValidatorContext validatorContext = validatorFactory.usingContext(); MessageInterpolator jsfMessageInterpolator = new JsfAwareMessageInterpolator(context, validatorFactory.getMessageInterpolator()); validatorContext.messageInterpolator(jsfMessageInterpolator); javax.validation.Validator beanValidator = validatorContext.getValidator(); Class[] validationGroupsArray = parseValidationGroups(getValidationGroups()); // PENDING(rlubke, driscoll): When EL 1.3 is present, we won't need // this. ValueExpressionAnalyzer expressionAnalyzer = new ValueExpressionAnalyzer(valueExpression); ValueReference valueReference = expressionAnalyzer.getReference(context.getELContext()); if (valueReference == null) { return; } if (isResolvable(valueReference, valueExpression)) { Set<ConstraintViolation<?>> violations = null; try { //noinspection unchecked violations = beanValidator.validateValue( valueReference.getBaseClass(), valueReference.getProperty(), value, validationGroupsArray); } catch (IllegalArgumentException iae) { String failureMessage = "Unable to validate expression " + valueExpression.getExpressionString() + " using Bean Validation. Unable to get value of expression. " + " Message from Bean Validation: " + iae.getMessage(); LOGGER.fine(failureMessage); } if (violations != null && !violations.isEmpty()) { ValidatorException toThrow; if (1 == violations.size()) { ConstraintViolation violation = violations.iterator().next(); toThrow = new ValidatorException( MessageFactory.getMessage( context, MESSAGE_ID, violation.getMessage(), MessageFactory.getLabel(context, component))); } else { Set<FacesMessage> messages = new LinkedHashSet<>(violations.size()); for (ConstraintViolation violation : violations) { messages.add( MessageFactory.getMessage( context, MESSAGE_ID, violation.getMessage(), MessageFactory.getLabel(context, component))); } toThrow = new ValidatorException(messages); } // Record the fact that this field failed validation, so that multi-field // validation is not attempted. if (MultiFieldValidationUtils.wholeBeanValidationEnabled(context, validationGroupsArray)) { Map<Object, Map<String, Map<String, Object>>> multiFieldCandidates = MultiFieldValidationUtils.getMultiFieldValidationCandidates(context, true); Object val = valueReference.getBase(); Map<String, Map<String, Object>> candidate = multiFieldCandidates.getOrDefault(val, new HashMap<>()); Map<String, Object> tuple = new HashMap<>(); tuple.put("component", component); tuple.put("value", FAILED_FIELD_LEVEL_VALIDATION); candidate.put(valueReference.getProperty(), tuple); multiFieldCandidates.putIfAbsent(val, candidate); } throw toThrow; } } // Record the fact that this field passed validation, so that multi-field // validation can be performed if desired if (MultiFieldValidationUtils.wholeBeanValidationEnabled(context, validationGroupsArray)) { Map<Object, Map<String, Map<String, Object>>> multiFieldCandidates = MultiFieldValidationUtils.getMultiFieldValidationCandidates(context, true); Object val = valueReference.getBase(); Map<String, Map<String, Object>> candidate = multiFieldCandidates.getOrDefault(val, new HashMap<>()); Map<String, Object> tuple = new HashMap<>(); // new ComponentValueTuple((EditableValueHolder) component, value); tuple.put("component", component); tuple.put("value", value); candidate.put(valueReference.getProperty(), tuple); multiFieldCandidates.putIfAbsent(val, candidate); } }
private void printComponentTree( PrintWriter out, String errorId, FacesContext context, UIComponent comp, int depth) { for (int i = 0; i < depth; i++) out.print(' '); boolean isError = false; if (errorId != null && errorId.equals(comp.getClientId(context))) { isError = true; out.print("<span style='color:red'>"); } out.print("<" + comp.getClass().getSimpleName()); if (comp.getId() != null) out.print(" id=\"" + comp.getId() + "\""); for (Method method : comp.getClass().getMethods()) { if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) continue; else if (method.getParameterTypes().length != 0) continue; String name; if (method.getName().startsWith("get")) name = method.getName().substring(3); else if (method.getName().startsWith("is")) name = method.getName().substring(2); else continue; // XXX: getURL name = Character.toLowerCase(name.charAt(0)) + name.substring(1); ValueExpression expr = comp.getValueExpression(name); Class type = method.getReturnType(); if (expr != null) { out.print(" " + name + "=\"" + expr.getExpressionString() + "\""); } else if (method.getDeclaringClass().equals(UIComponent.class) || method.getDeclaringClass().equals(UIComponentBase.class)) { } else if (name.equals("family")) { } else if (String.class.equals(type)) { try { Object value = method.invoke(comp); if (value != null) out.print(" " + name + "=\"" + value + "\""); } catch (Exception e) { } } } int facetCount = comp.getFacetCount(); int childCount = comp.getChildCount(); if (facetCount == 0 && childCount == 0) { out.print("/>"); if (isError) out.print("</span>"); out.println(); return; } out.println(">"); if (isError) out.print("</span>"); for (int i = 0; i < childCount; i++) { printComponentTree(out, errorId, context, comp.getChildren().get(i), depth + 1); } for (int i = 0; i < depth; i++) out.print(' '); if (isError) out.print("<span style='color:red'>"); out.println("</" + comp.getClass().getSimpleName() + ">"); if (isError) out.print("</span>"); }
static String save(ValueExpression expr, FacesContext context) { if (expr != null) return expr.getExpressionString(); else return null; }
/** * Attempts to return the property accessed in a simple EL expression of the form * ${someObject.property}. * * @param expression An EL expression to parse the property from. * @return The property name of the EL expression. */ public static String resolveField(ValueExpression expression) { String expressionString = expression.getExpressionString(); return expressionString.substring( expressionString.indexOf(".") + 1, expressionString.length() - 1); }
@Override public String toString() { return expression.getExpressionString(); }