Search in sources :

Example 71 with Validator

use of com.opensymphony.xwork2.validator.Validator in project struts by apache.

the class AnnotationActionValidatorManager method buildValidatorKey.

/**
 * Builds a key for validators - used when caching validators.
 *
 * @param clazz the action.
 * @param context context
 * @return a validator key which is the class name plus context.
 */
protected String buildValidatorKey(Class clazz, String context) {
    ActionInvocation invocation = ActionContext.getContext().getActionInvocation();
    ActionProxy proxy = invocation.getProxy();
    ActionConfig config = proxy.getConfig();
    StringBuilder sb = new StringBuilder(clazz.getName());
    sb.append("/");
    if (StringUtils.isNotBlank(config.getPackageName())) {
        sb.append(config.getPackageName());
        sb.append("/");
    }
    // the key needs to use the name of the action from the config file,
    // instead of the url, so wild card actions will have the same validator
    // see WW-2996
    // UPDATE:
    // WW-3753 Using the config name instead of the context only for
    // wild card actions to keep the flexibility provided
    // by the original design (such as mapping different contexts
    // to the same action and method if desired)
    // UPDATE:
    // WW-4536 Using NameVariablePatternMatcher allows defines actions
    // with patterns enclosed with '{}', it's similar case to WW-3753
    String configName = config.getName();
    if (configName.contains(ActionConfig.WILDCARD) || (configName.contains("{") && configName.contains("}"))) {
        sb.append(configName);
        sb.append("|");
        sb.append(proxy.getMethod());
    } else {
        sb.append(context);
    }
    return sb.toString();
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig)

Example 72 with Validator

use of com.opensymphony.xwork2.validator.Validator in project struts by apache.

the class DefaultValidatorFactory method parseValidators.

private void parseValidators() {
    LOG.debug("Loading validator definitions.");
    List<File> files = new ArrayList<>();
    try {
        // Get custom validator configurations via the classpath
        Iterator<URL> urls = ClassLoaderUtil.getResources("", DefaultValidatorFactory.class, false);
        while (urls.hasNext()) {
            URL u = urls.next();
            try {
                URI uri = new URI(u.toExternalForm().replaceAll(" ", "%20"));
                if (!uri.isOpaque() && "file".equalsIgnoreCase(uri.getScheme())) {
                    File f = new File(uri);
                    FilenameFilter filter = new FilenameFilter() {

                        public boolean accept(File file, String fileName) {
                            return fileName.contains("-validators.xml");
                        }
                    };
                    // matches then add to the list of files to be parsed
                    if (f.isDirectory()) {
                        try {
                            File[] ff = f.listFiles(filter);
                            if (ff != null && ff.length > 0) {
                                files.addAll(Arrays.asList(ff));
                            }
                        } catch (SecurityException se) {
                            LOG.error("Security Exception while accessing directory '{}'", f, se);
                        }
                    } else {
                        // If this is not a directory, then get hold of the inputstream.
                        // If its not a ZipInputStream, then create a ZipInputStream out
                        // of it. The intention is to allow nested jar files to be scanned
                        // for *-validators.xml.
                        // Ex: struts-app.jar -> MyApp.jar -> Login-validators.xml should be
                        // parsed and loaded.
                        ZipInputStream zipInputStream = null;
                        try (InputStream inputStream = u.openStream()) {
                            if (inputStream instanceof ZipInputStream) {
                                zipInputStream = (ZipInputStream) inputStream;
                            } else {
                                zipInputStream = new ZipInputStream(inputStream);
                            }
                            ZipEntry zipEntry = zipInputStream.getNextEntry();
                            while (zipEntry != null) {
                                if (zipEntry.getName().endsWith("-validators.xml")) {
                                    LOG.trace("Adding validator {}", zipEntry.getName());
                                    files.add(new File(zipEntry.getName()));
                                }
                                zipEntry = zipInputStream.getNextEntry();
                            }
                        } finally {
                            // cleanup
                            if (zipInputStream != null) {
                                zipInputStream.close();
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LOG.error("Unable to load {}", u, ex);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationException("Unable to parse validators", e);
    }
    // Parse default validator configurations
    String resourceName = "com/opensymphony/xwork2/validator/validators/default.xml";
    retrieveValidatorConfiguration(resourceName);
    // Overwrite and extend defaults with application specific validator configurations
    resourceName = "validators.xml";
    retrieveValidatorConfiguration(resourceName);
    // Add custom (plugin) specific validator configurations
    for (File file : files) {
        retrieveValidatorConfiguration(file.getName());
    }
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) IOException(java.io.IOException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) StrutsException(org.apache.struts2.StrutsException) FilenameFilter(java.io.FilenameFilter) ZipInputStream(java.util.zip.ZipInputStream) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) File(java.io.File)

Example 73 with Validator

use of com.opensymphony.xwork2.validator.Validator in project struts by apache.

the class DefaultValidatorFactory method getValidator.

public Validator getValidator(ValidatorConfig cfg) {
    String className = lookupRegisteredValidatorType(cfg.getType());
    Validator validator;
    try {
        // instantiate the validator, and set configured parameters
        // todo - can this use the ThreadLocal?
        validator = objectFactory.buildValidator(className, cfg.getParams(), ActionContext.getContext().getContextMap());
    } catch (Exception e) {
        final String msg = "There was a problem creating a Validator of type " + className + " : caused by " + e.getMessage();
        throw new StrutsException(msg, e, cfg);
    }
    // set other configured properties
    validator.setMessageKey(cfg.getMessageKey());
    validator.setDefaultMessage(cfg.getDefaultMessage());
    validator.setMessageParameters(cfg.getMessageParams());
    if (validator instanceof ShortCircuitableValidator) {
        ((ShortCircuitableValidator) validator).setShortCircuit(cfg.isShortCircuit());
    }
    return validator;
}
Also used : StrutsException(org.apache.struts2.StrutsException) IOException(java.io.IOException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) StrutsException(org.apache.struts2.StrutsException)

Example 74 with Validator

use of com.opensymphony.xwork2.validator.Validator in project struts by apache.

the class LongRangeFieldValidatorTest method testPassValidation.

public void testPassValidation() throws Exception {
    // given
    ValidationAction action = prepareAction(100);
    ValidatorContext context = new DummyValidatorContext(action, tpf);
    LongRangeFieldValidator validator = prepareValidator(action, context);
    // when
    validator.validate(action);
    // then
    assertTrue(context.getFieldErrors().size() == 0);
}
Also used : DummyValidatorContext(com.opensymphony.xwork2.validator.DummyValidatorContext) ValidatorContext(com.opensymphony.xwork2.validator.ValidatorContext) DummyValidatorContext(com.opensymphony.xwork2.validator.DummyValidatorContext)

Example 75 with Validator

use of com.opensymphony.xwork2.validator.Validator in project struts by apache.

the class RequiredStringValidatorTest method testRequiredStringPass.

public void testRequiredStringPass() throws Exception {
    // given
    ValueStack valueStack = ActionContext.getContext().getValueStack();
    ValidationAction action = new ValidationAction();
    action.setStringValue("a string");
    valueStack.push(action);
    ValidatorContext context = new DummyValidatorContext(action, tpf);
    RequiredStringValidator validator = new RequiredStringValidator();
    validator.setValidatorContext(context);
    validator.setFieldName("stringValue");
    validator.setValueStack(valueStack);
    // when
    validator.validate(action);
    // then
    assertTrue(context.getFieldErrors().size() == 0);
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) DummyValidatorContext(com.opensymphony.xwork2.validator.DummyValidatorContext) ValidatorContext(com.opensymphony.xwork2.validator.ValidatorContext) DummyValidatorContext(com.opensymphony.xwork2.validator.DummyValidatorContext)

Aggregations

ValueStack (com.opensymphony.xwork2.util.ValueStack)19 DummyValidatorContext (com.opensymphony.xwork2.validator.DummyValidatorContext)18 ValidatorContext (com.opensymphony.xwork2.validator.ValidatorContext)18 URLValidator (com.opensymphony.xwork2.validator.validators.URLValidator)16 RegexFieldValidator (com.opensymphony.xwork2.validator.validators.RegexFieldValidator)12 EmailValidator (com.opensymphony.xwork2.validator.validators.EmailValidator)9 ValueStackFactory (com.opensymphony.xwork2.util.ValueStackFactory)7 RequiredStringValidator (com.opensymphony.xwork2.validator.validators.RequiredStringValidator)6 HashMap (java.util.HashMap)6 ActionSupport (com.opensymphony.xwork2.ActionSupport)5 Validator (com.opensymphony.xwork2.validator.Validator)5 ExpressionValidator (com.opensymphony.xwork2.validator.validators.ExpressionValidator)5 VisitorFieldValidator (com.opensymphony.xwork2.validator.validators.VisitorFieldValidator)5 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)4 RequiredFieldValidator (com.opensymphony.xwork2.validator.validators.RequiredFieldValidator)4 StringLengthFieldValidator (com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator)4 TextProviderFactory (com.opensymphony.xwork2.TextProviderFactory)3 ConversionErrorFieldValidator (com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator)3 DateRangeFieldValidator (com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator)3 DoubleRangeFieldValidator (com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator)3