Search in sources :

Example 31 with ValidationAware

use of com.opensymphony.xwork2.interceptor.ValidationAware in project struts by apache.

the class AliasInterceptor method intercept.

@Override
public String intercept(ActionInvocation invocation) throws Exception {
    ActionConfig config = invocation.getProxy().getConfig();
    ActionContext ac = invocation.getInvocationContext();
    Object action = invocation.getAction();
    // get the action's parameters
    final Map<String, String> parameters = config.getParams();
    if (parameters.containsKey(aliasesKey)) {
        String aliasExpression = parameters.get(aliasesKey);
        ValueStack stack = ac.getValueStack();
        Object obj = stack.findValue(aliasExpression);
        if (obj instanceof Map) {
            // get secure stack
            ValueStack newStack = valueStackFactory.createValueStack(stack);
            boolean clearableStack = newStack instanceof ClearableValueStack;
            if (clearableStack) {
                // if the stack's context can be cleared, do that to prevent OGNL
                // from having access to objects in the stack, see XW-641
                ((ClearableValueStack) newStack).clearContextValues();
                Map<String, Object> context = newStack.getContext();
                ReflectionContextState.setCreatingNullObjects(context, true);
                ReflectionContextState.setDenyMethodExecution(context, true);
                ReflectionContextState.setReportingConversionErrors(context, true);
                // keep locale from original context
                newStack.getActionContext().withLocale(stack.getActionContext().getLocale());
            }
            // override
            Map aliases = (Map) obj;
            for (Object o : aliases.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                String name = entry.getKey().toString();
                if (isNotAcceptableExpression(name)) {
                    continue;
                }
                String alias = (String) entry.getValue();
                if (isNotAcceptableExpression(alias)) {
                    continue;
                }
                Evaluated value = new Evaluated(stack.findValue(name));
                if (!value.isDefined()) {
                    // workaround
                    HttpParameters contextParameters = ActionContext.getContext().getParameters();
                    if (null != contextParameters) {
                        Parameter param = contextParameters.get(name);
                        if (param.isDefined()) {
                            value = new Evaluated(param.getValue());
                        }
                    }
                }
                if (value.isDefined()) {
                    try {
                        newStack.setValue(alias, value.get());
                    } catch (RuntimeException e) {
                        if (devMode) {
                            String developerNotification = localizedTextProvider.findText(ParametersInterceptor.class, "devmode.notification", ActionContext.getContext().getLocale(), "Developer Notification:\n{0}", new Object[] { "Unexpected Exception caught setting '" + entry.getKey() + "' on '" + action.getClass() + ": " + e.getMessage() });
                            LOG.error(developerNotification);
                            if (action instanceof ValidationAware) {
                                ((ValidationAware) action).addActionMessage(developerNotification);
                            }
                        }
                    }
                }
            }
            if (clearableStack) {
                stack.getActionContext().withConversionErrors(newStack.getActionContext().getConversionErrors());
            }
        } else {
            LOG.debug("invalid alias expression: {}", aliasesKey);
        }
    }
    return invocation.invoke();
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) ClearableValueStack(com.opensymphony.xwork2.util.ClearableValueStack) ValueStack(com.opensymphony.xwork2.util.ValueStack) HttpParameters(org.apache.struts2.dispatcher.HttpParameters) Evaluated(com.opensymphony.xwork2.util.Evaluated) ActionContext(com.opensymphony.xwork2.ActionContext) ClearableValueStack(com.opensymphony.xwork2.util.ClearableValueStack) Parameter(org.apache.struts2.dispatcher.Parameter) Map(java.util.Map)

Example 32 with ValidationAware

use of com.opensymphony.xwork2.interceptor.ValidationAware in project struts by apache.

the class ConversionErrorInterceptor method doIntercept.

@Override
public String doIntercept(ActionInvocation invocation) throws Exception {
    ActionContext invocationContext = invocation.getInvocationContext();
    Map<String, ConversionData> conversionErrors = invocationContext.getConversionErrors();
    ValueStack stack = invocationContext.getValueStack();
    HashMap<Object, Object> fakie = null;
    for (Map.Entry<String, ConversionData> entry : conversionErrors.entrySet()) {
        String propertyName = entry.getKey();
        ConversionData conversionData = entry.getValue();
        if (shouldAddError(propertyName, conversionData.getValue())) {
            String message = XWorkConverter.getConversionErrorMessage(propertyName, conversionData.getToClass(), stack);
            Object action = invocation.getAction();
            if (action instanceof ValidationAware) {
                ValidationAware va = (ValidationAware) action;
                va.addFieldError(propertyName, message);
            }
            if (fakie == null) {
                fakie = new HashMap<>();
            }
            fakie.put(propertyName, getOverrideExpr(invocation, conversionData.getValue()));
        }
    }
    if (fakie != null) {
        // if there were some errors, put the original (fake) values in place right before the result
        stack.getContext().put(ORIGINAL_PROPERTY_OVERRIDE, fakie);
        invocation.addPreResultListener(new PreResultListener() {

            public void beforeResult(ActionInvocation invocation, String resultCode) {
                Map<Object, Object> fakie = (Map<Object, Object>) invocation.getInvocationContext().get(ORIGINAL_PROPERTY_OVERRIDE);
                if (fakie != null) {
                    invocation.getStack().setExprOverrides(fakie);
                }
            }
        });
    }
    return invocation.invoke();
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) ActionContext(com.opensymphony.xwork2.ActionContext) ConversionData(com.opensymphony.xwork2.conversion.impl.ConversionData) Map(java.util.Map) HashMap(java.util.HashMap)

Example 33 with ValidationAware

use of com.opensymphony.xwork2.interceptor.ValidationAware in project struts by apache.

the class StaticParametersInterceptor method intercept.

@Override
public String intercept(ActionInvocation invocation) throws Exception {
    ActionConfig config = invocation.getProxy().getConfig();
    Object action = invocation.getAction();
    final Map<String, String> parameters = config.getParams();
    LOG.debug("Setting static parameters: {}", parameters);
    // for actions marked as Parameterizable, pass the static parameters directly
    if (action instanceof Parameterizable) {
        ((Parameterizable) action).setParams(parameters);
    }
    if (parameters != null) {
        ActionContext ac = ActionContext.getContext();
        Map<String, Object> contextMap = ac.getContextMap();
        try {
            ReflectionContextState.setCreatingNullObjects(contextMap, true);
            ReflectionContextState.setReportingConversionErrors(contextMap, true);
            final ValueStack stack = ac.getValueStack();
            ValueStack newStack = valueStackFactory.createValueStack(stack);
            boolean clearableStack = newStack instanceof ClearableValueStack;
            if (clearableStack) {
                // if the stack's context can be cleared, do that to prevent OGNL
                // from having access to objects in the stack, see XW-641
                ((ClearableValueStack) newStack).clearContextValues();
                Map<String, Object> context = newStack.getContext();
                ReflectionContextState.setCreatingNullObjects(context, true);
                ReflectionContextState.setDenyMethodExecution(context, true);
                ReflectionContextState.setReportingConversionErrors(context, true);
                // keep locale from original context
                newStack.getActionContext().withLocale(stack.getActionContext().getLocale());
            }
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                Object val = entry.getValue();
                if (parse && val instanceof String) {
                    val = TextParseUtil.translateVariables(val.toString(), stack);
                }
                try {
                    newStack.setValue(entry.getKey(), val);
                } catch (RuntimeException e) {
                    if (devMode) {
                        String developerNotification = localizedTextProvider.findText(ParametersInterceptor.class, "devmode.notification", ActionContext.getContext().getLocale(), "Developer Notification:\n{0}", new Object[] { "Unexpected Exception caught setting '" + entry.getKey() + "' on '" + action.getClass() + ": " + e.getMessage() });
                        LOG.error(developerNotification);
                        if (action instanceof ValidationAware) {
                            ((ValidationAware) action).addActionMessage(developerNotification);
                        }
                    }
                }
            }
            if (clearableStack) {
                stack.getActionContext().withConversionErrors(newStack.getActionContext().getConversionErrors());
            }
            if (merge)
                addParametersToContext(ac, parameters);
        } finally {
            ReflectionContextState.setCreatingNullObjects(contextMap, false);
            ReflectionContextState.setReportingConversionErrors(contextMap, false);
        }
    }
    return invocation.invoke();
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) ClearableValueStack(com.opensymphony.xwork2.util.ClearableValueStack) ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionContext(com.opensymphony.xwork2.ActionContext) ClearableValueStack(com.opensymphony.xwork2.util.ClearableValueStack) Parameterizable(com.opensymphony.xwork2.config.entities.Parameterizable) Map(java.util.Map)

Example 34 with ValidationAware

use of com.opensymphony.xwork2.interceptor.ValidationAware in project struts by apache.

the class DateRangeValidatorTest method testRangeValidation.

/**
 * Tests whether the date range validation is working. Should produce an validation error,
 * because the action config sets date to 12/20/2002 while expected range is Dec 22-25.
 */
public void testRangeValidation() throws Exception {
    Calendar date = Calendar.getInstance();
    date.set(2002, Calendar.NOVEMBER, 20);
    Map<String, Object> context = new HashMap<>();
    HashMap<String, Object> params = new HashMap<>();
    params.put("date", date.getTime());
    context.put(ActionContext.PARAMETERS, HttpParameters.create(params).build());
    // Force US Locale for date conversion tests on JDK9+
    context.put(ActionContext.LOCALE, Locale.US);
    ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, null, context);
    proxy.execute();
    assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
    Map<String, List<String>> errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
    List<String> errorMessages = errors.get("date");
    assertNotNull("Expected date range validation error message.", errorMessages);
    assertEquals(1, errorMessages.size());
    String errorMessage = errorMessages.get(0);
    assertEquals("The date must be between 12-22-2002 and 12-25-2002.", errorMessage);
}
Also used : ActionProxy(com.opensymphony.xwork2.ActionProxy) ValidationAware(com.opensymphony.xwork2.interceptor.ValidationAware)

Example 35 with ValidationAware

use of com.opensymphony.xwork2.interceptor.ValidationAware in project struts by apache.

the class DoubleRangeFieldValidatorTest method testRangeValidationWithExpressionsFail.

public void testRangeValidationWithExpressionsFail() throws Exception {
    // Explicitly set an out-of-range double for DoubleRangeValidatorTest
    Map<String, Object> context = new HashMap<>();
    HashMap<String, Object> params = new HashMap<>();
    params.put("percentage", 100.12);
    context.put(ActionContext.PARAMETERS, HttpParameters.create(params).build());
    ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.EXPRESSION_VALIDATION_ACTION, null, context);
    proxy.execute();
    assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
    Map<String, List<String>> errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
    List<String> errorMessages = errors.get("percentage");
    assertNotNull("Expected double range validation error message.", errorMessages);
    assertEquals(1, errorMessages.size());
    String errorMessage = errorMessages.get(0);
    assertNotNull("Expecting: percentage must be between 0.1 and 10.1, current value is 100.12.", errorMessage);
    assertEquals("percentage must be between 0.1 and 10.1, current value is 100.12.", errorMessage);
}
Also used : ActionProxy(com.opensymphony.xwork2.ActionProxy) HashMap(java.util.HashMap) List(java.util.List) ValidationAware(com.opensymphony.xwork2.interceptor.ValidationAware)

Aggregations

ValidationAware (com.opensymphony.xwork2.interceptor.ValidationAware)42 ActionProxy (com.opensymphony.xwork2.ActionProxy)38 List (java.util.List)28 HashMap (java.util.HashMap)23 Map (java.util.Map)8 ValueStack (com.opensymphony.xwork2.util.ValueStack)6 Collection (java.util.Collection)5 ModelDrivenAction (org.apache.struts.beanvalidation.actions.ModelDrivenAction)5 ActionContext (com.opensymphony.xwork2.ActionContext)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 ValidationAwareSupport (com.opensymphony.xwork2.ValidationAwareSupport)2 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)2 ConversionData (com.opensymphony.xwork2.conversion.impl.ConversionData)2 ClearableValueStack (com.opensymphony.xwork2.util.ClearableValueStack)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 ValidateGroupAction (org.apache.struts.beanvalidation.actions.ValidateGroupAction)2 HttpParameters (org.apache.struts2.dispatcher.HttpParameters)2 Parameter (org.apache.struts2.dispatcher.Parameter)2 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)1 ActionProxyFactory (com.opensymphony.xwork2.ActionProxyFactory)1