Example usage for org.apache.wicket.validation ValidationError ValidationError

List of usage examples for org.apache.wicket.validation ValidationError ValidationError

Introduction

In this page you can find the example usage for org.apache.wicket.validation ValidationError ValidationError.

Prototype

public ValidationError(String message) 

Source Link

Document

Constructs a validation error with the specified message.

Usage

From source file:ca.travelagency.components.validators.DuplicateValidator.java

License:Apache License

@Override
public void validate(IValidatable<String> validatable) {
    super.validate(validatable);
    T daoEntity = form.getModelObject();
    daoEntity.setName(validatable.getValue());
    if (daoSupport.duplicated(daoEntity)) {
        ValidationError error = new ValidationError(this);
        validatable.error(decorate(error, validatable));
    }// ww w.j ava 2s  .c om
}

From source file:ca.travelagency.components.validators.PhoneNumberValidator.java

License:Apache License

@Override
public void validate(IValidatable<String> validatable) {
    if (!PhoneNumberUtils.isValid(validatable.getValue())) {
        ValidationError error = new ValidationError(this);
        validatable.error(decorate(error, validatable));
    }//from w w  w .ja v a2 s  .  co  m
}

From source file:com.commafeed.frontend.pages.RfcCompliantEmailAddressValidator.java

License:Apache License

@Override
public void validate(IValidatable<String> validatable) {
    final String email = validatable.getValue().toString();
    if (email.length() != email.trim().length()) {
        validatable.error(decorate(new ValidationError(this), validatable));
    } else if (!PATTERN.matcher(validatable.getValue()).matches()) {
        validatable.error(decorate(new ValidationError(this), validatable));
    }// w  ww.  ja va2 s .  c om
}

From source file:com.github.cage.cage_e03_wicket.HomePage.java

License:Apache License

public HomePage() {
    super(new CompoundPropertyModel<Token>(new Token()));
    add(new WebMarkupContainer("goodResult") {
        private static final long serialVersionUID = -5279236538017405828L;

        @Override//from w  w w  . ja  va  2s .  c  om
        protected void onConfigure() {
            super.onConfigure();

            final Token token = HomePage.this.getToken();

            setVisible(token.showGoodResult);
            token.showGoodResult = false;
        }
    });
    add(new WebMarkupContainer("badResult") {
        private static final long serialVersionUID = -6479933043124566245L;

        @Override
        protected void onConfigure() {
            super.onConfigure();

            final Token token = HomePage.this.getToken();

            setVisible(token.showBadResult);
            token.showBadResult = false;
        }
    });

    add(new Form<Token>("form") {
        private static final long serialVersionUID = -2783383042739263677L;

        @Override
        protected void onInitialize() {
            super.onInitialize();
            add(new RequiredTextField<String>("captcha") {
                private static final long serialVersionUID = 8416111619173955610L;

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    tag.put("value", "");
                };
            }.add(new StringValidator() {
                private static final long serialVersionUID = 3888825725858419028L;

                @Override
                public void validate(IValidatable<String> validatable) {
                    super.validate(validatable);
                    if (!validatable.isValid())
                        return;

                    final Token token = HomePage.this.getToken();

                    if (token.token == null || !token.token.equals(validatable.getValue())) {
                        LOGGER.error("There was no generated token, or it didn't match the user given one.");
                        validatable.error(decorate(new ValidationError(this), validatable));
                    }
                }
            }));
        }

        @Override
        protected void onSubmit() {
            super.onSubmit();
            onPost(true);
        }

        @Override
        protected void onError() {
            super.onError();
            onPost(false);
        }

        protected void onPost(boolean good) {
            final Token token = HomePage.this.getToken();

            token.showGoodResult = good;
            token.showBadResult = !good;
        }
    });

    add(new Image("captchaImage", new DynamicImageResource(cage.getFormat()) {
        private static final long serialVersionUID = -1475355045487272906L;

        @Override
        protected void configureResponse(ResourceResponse response, Attributes attributes) {
            super.configureResponse(response, attributes);
            final Token token = HomePage.this.getToken();

            LOGGER.info("Token: {}.", token);

            if (token.token == null || token.tokenUsed) {
                LOGGER.error("Requested captcha without token.");
                response.setError(HttpServletResponse.SC_NOT_FOUND, "Captcha not found.");
            }
            token.tokenUsed = true;

            response.disableCaching();
        }

        @Override
        protected byte[] getImageData(Attributes attributes) {
            final Token token = HomePage.this.getToken();

            return cage.draw(token.token);
        }
    }));
}

From source file:com.premiumminds.webapp.wicket.validators.HibernateValidatorProperty.java

License:Open Source License

public void validate(IValidatable<Object> validatable) {
    Validator validator = HibernateValidatorProperty.validatorFactory.getValidator();

    @SuppressWarnings("unchecked")
    Set<ConstraintViolation<Object>> violations = validator.validateValue(
            (Class<Object>) beanModel.getObject().getClass(), propertyName, validatable.getValue());

    if (!violations.isEmpty()) {
        for (ConstraintViolation<?> violation : violations) {
            ValidationError error = new ValidationError(violation.getMessage());

            String key = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
            if (getValidatorPrefix() != null)
                key = getValidatorPrefix() + "." + key;

            error.addKey(key);//from   ww  w  .  j a v  a 2s .co  m
            error.setVariables(
                    new HashMap<String, Object>(violation.getConstraintDescriptor().getAttributes()));

            //remove garbage from the attributes
            error.getVariables().remove("payload");
            error.getVariables().remove("message");
            error.getVariables().remove("groups");

            validatable.error(error);
        }
    }
}

From source file:com.premiumminds.webapp.wicket.validators.PortugueseNIFValidator.java

License:Open Source License

@Override
public void validate(IValidatable<String> validatable) {
    super.validate(validatable);

    final String value = validatable.getValue();

    if (value == null || value.length() == 0)
        return;/*from ww  w  .  ja  v  a2 s  .  c  o m*/

    try {
        if (!isNIFValid(value))
            validatable.error(new ValidationError(this));
    } catch (NumberFormatException e) {
        validatable.error(new ValidationError(this));
    }
}

From source file:eu.esdihumboldt.hale.server.templates.war.components.TemplateUploadForm.java

License:Open Source License

/**
 * Constructor/*  w  w w  .j av  a  2s. c o  m*/
 * 
 * @param id the component ID
 * @param templateId the identifier of the template to update, or
 *            <code>null</code> to create a new template
 */
public TemplateUploadForm(String id, String templateId) {
    super(id);
    this.templateId = templateId;

    Form<Void> form = new Form<Void>("upload") {

        private static final long serialVersionUID = 716487990605324922L;

        @Override
        protected void onSubmit() {
            List<FileUpload> uploads = file.getFileUploads();
            if (uploads != null && !uploads.isEmpty()) {
                final boolean newTemplate = TemplateUploadForm.this.templateId == null;
                final String templateId;
                final File dir;
                File oldContent = null;
                if (newTemplate) {
                    // attempt to reserve template ID
                    Pair<String, File> template;
                    try {
                        template = templates.reserveResource(determinePreferredId(uploads));
                    } catch (ScavengerException e) {
                        error(e.getMessage());
                        return;
                    }
                    templateId = template.getFirst();
                    dir = template.getSecond();
                } else {
                    templateId = TemplateUploadForm.this.templateId;
                    dir = new File(templates.getHuntingGrounds(), templateId);

                    // archive old content
                    try {
                        Path tmpFile = Files.createTempFile("hale-template", ".zip");
                        try (OutputStream out = Files.newOutputStream(tmpFile);
                                ZipOutputStream zos = new ZipOutputStream(out)) {
                            IOUtils.zipDirectory(dir, zos);
                        }
                        oldContent = tmpFile.toFile();
                    } catch (IOException e) {
                        log.error("Error saving old template content to archive", e);
                    }

                    // delete old content
                    try {
                        FileUtils.cleanDirectory(dir);
                    } catch (IOException e) {
                        log.error("Error deleting old template content", e);
                    }
                }

                try {
                    for (FileUpload upload : uploads) {
                        if (isZipFile(upload)) {
                            // extract uploaded file
                            IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream()));
                        } else {
                            // copy uploaded file
                            File target = new File(dir, upload.getClientFileName());
                            ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target));
                        }
                    }

                    // trigger scan after upload
                    if (newTemplate) {
                        templates.triggerScan();
                    } else {
                        templates.forceUpdate(templateId);
                    }

                    TemplateProject ref = templates.getReference(templateId);
                    if (ref != null && ref.isValid()) {
                        info("Successfully uploaded project");
                        boolean infoUpdate = (updateInfo != null) ? (updateInfo.getModelObject()) : (false);
                        onUploadSuccess(this, templateId, ref.getProjectInfo(), infoUpdate);
                    } else {
                        if (newTemplate) {
                            templates.releaseResourceId(templateId);
                        } else {
                            restoreContent(dir, oldContent);
                        }
                        error((ref != null) ? (ref.getNotValidMessage())
                                : ("Uploaded files could not be loaded as HALE project"));
                    }

                } catch (Exception e) {
                    if (newTemplate) {
                        templates.releaseResourceId(templateId);
                    } else {
                        restoreContent(dir, oldContent);
                    }
                    log.error("Error while uploading file", e);
                    error("Error saving the file");
                }
            } else {
                warn("Please provide a file for upload");
            }
        }

        @Override
        protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
            if (e instanceof SizeLimitExceededException) {
                final String msg = "Only files up to  " + bytesToString(getMaxSize(), Locale.US)
                        + " can be uploaded.";
                error(msg);
            } else {
                final String msg = "Error uploading the file: " + e.getLocalizedMessage();
                error(msg);

                log.warn(msg, e);
            }
        }

    };
    add(form);

    // multipart always needed for uploads
    form.setMultiPart(true);

    // max size for upload
    if (UserUtil.isAdmin()) {
        // admin max upload size
        form.setMaxSize(Bytes.megabytes(100));
    } else {
        // normal user max upload size
        // TODO differentiate between logged in and anonymous user?
        form.setMaxSize(Bytes.megabytes(15));
    }

    // Add file input field for multiple files
    form.add(file = new FileUploadField("file"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // add anonym/recaptcha panel
    boolean loggedIn = UserUtil.getLogin() != null;
    WebMarkupContainer anonym = new WebMarkupContainer("anonym");

    if (loggedIn) {
        anonym.add(new WebMarkupContainer("recaptcha"));
    } else {
        anonym.add(new RecaptchaPanel("recaptcha"));
    }

    anonym.add(
            new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass()));

    anonym.setVisible(!loggedIn);
    form.add(anonym);

    // update panel
    WebMarkupContainer update = new WebMarkupContainer("update");
    update.setVisible(templateId != null);

    updateInfo = new CheckBox("updateInfo", Model.of(true));
    update.add(updateInfo);

    form.add(update);

    // feedback panel
    form.add(new BootstrapFeedbackPanel("feedback"));
}

From source file:eu.esdihumboldt.hale.server.templates.war.components.UploadForm.java

License:Open Source License

/**
 * @see Panel#Panel(String)//from  w  w  w  .  j  a  v  a2  s. c  o m
 */
public UploadForm(String id) {
    super(id);

    Form<Void> form = new Form<Void>("upload") {

        private static final long serialVersionUID = 716487990605324922L;

        @Override
        protected void onSubmit() {
            // attempt to reserve template ID
            Pair<String, File> template;
            try {
                template = templates.reserveResource(null);
            } catch (ScavengerException e) {
                error(e.getMessage());
                return;
            }
            final String templateId = template.getFirst();
            final File dir = template.getSecond();

            try {
                List<FileUpload> uploads = file.getFileUploads();
                if (uploads != null && !uploads.isEmpty()) {
                    for (FileUpload upload : uploads) {
                        if (isZipFile(upload)) {
                            // extract uploaded file
                            IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream()));
                        } else {
                            // copy uploaded file
                            File target = new File(dir, upload.getClientFileName());
                            ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target));
                        }
                    }

                    // trigger scan after upload
                    templates.triggerScan();

                    ProjectReference<Void> ref = templates.getReference(templateId);
                    if (ref != null && ref.getProjectInfo() != null) {
                        info("Successfully uploaded project");
                        onUploadSuccess(this, templateId, ref.getProjectInfo());
                    } else {
                        templates.releaseResourceId(templateId);
                        error("Uploaded files could not be loaded as HALE project");
                    }
                } else {
                    templates.releaseResourceId(templateId);
                    warn("Please provide a file for upload");
                }
            } catch (Exception e) {
                templates.releaseResourceId(templateId);
                log.error("Error while uploading file", e);
                error("Error saving the file");
            }
        }

        @Override
        protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
            if (e instanceof SizeLimitExceededException) {
                final String msg = "Only files up to  " + bytesToString(getMaxSize(), Locale.US)
                        + " can be uploaded.";
                error(msg);
            } else {
                final String msg = "Error uploading the file: " + e.getLocalizedMessage();
                error(msg);

                log.warn(msg, e);
            }
        }

    };
    add(form);

    // multipart always needed for uploads
    form.setMultiPart(true);

    // max size for upload
    form.setMaxSize(Bytes.megabytes(1));

    // Add file input field for multiple files
    form.add(file = new FileUploadField("file"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // add anonym/recaptcha panel
    boolean loggedIn = UserUtil.getLogin() != null;
    WebMarkupContainer anonym = new WebMarkupContainer("anonym");

    if (loggedIn) {
        anonym.add(new WebMarkupContainer("recaptcha"));
    } else {
        anonym.add(new RecaptchaPanel("recaptcha"));
    }

    anonym.add(
            new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass()));

    anonym.setVisible(!loggedIn);
    form.add(anonym);

    // feedback panel
    form.add(new BootstrapFeedbackPanel("feedback"));
}

From source file:eu.esdihumboldt.hale.server.webtransform.war.pages.UploadAndTransForm.java

License:Open Source License

/**
 * Create a form for uploading and transforming data.
 * // w  w w . j  a  va  2 s .com
 * @param id the component ID
 * @param projectId the project ID
 */
public UploadAndTransForm(String id, String projectId) {
    super(id);
    this.projectId = projectId;

    // multi-part always needed for uploads
    setMultiPart(true);

    add(new FeedbackPanel("feedback"));

    // Add file input field
    add(file = new FileUploadField("upload"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // target selection
    Select<IOConfiguration> selectTarget = new Select<IOConfiguration>("target",
            new PropertyModel<IOConfiguration>(this, "target"));
    add(selectTarget);

    TransformationEnvironment env = environmentService.getEnvironment(projectId);

    // determine presets
    Collection<NamedIOConfiguration> presetList = new ArrayList<>();
    for (Entry<String, ? extends IOConfiguration> entry : env.getExportPresets().entrySet()) {
        presetList.add(new NamedIOConfiguration(entry.getKey(), entry.getValue()));
    }
    SelectOptions<NamedIOConfiguration> presets = new SelectOptions<NamedIOConfiguration>("presets", presetList,
            RENDERER);
    selectTarget.add(presets);

    // determine valid exporters
    Collection<NamedIOConfiguration> templateList = new ArrayList<>();
    for (Entry<String, ? extends IOConfiguration> entry : env.getExportTemplates().entrySet()) {
        presetList.add(new NamedIOConfiguration(entry.getKey(), entry.getValue()));
    }
    SelectOptions<NamedIOConfiguration> exporters = new SelectOptions<NamedIOConfiguration>("exporters",
            templateList, RENDERER);
    selectTarget.add(exporters);

    // initial selection
    if (!presetList.isEmpty()) {
        setTarget(presetList.iterator().next().getConfig());
    } else if (!templateList.isEmpty()) {
        setTarget(templateList.iterator().next().getConfig());
    }

    // panel for I/O configuration
    final WebMarkupContainer config = new WebMarkupContainer("config");
    config.setOutputMarkupId(true);
    add(config);

    IModel<List<String>> parameterModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 1018038661733512580L;

        @Override
        protected List<String> load() {
            Set<String> properties = new LinkedHashSet<String>();

            if (target != null && target.getProviderId() != null) {
                // must have
                properties.add(IOProvider.PARAM_CONTENT_TYPE);

                // what is supported

                IOProvider p = HeadlessIO.loadProvider(target);
                properties.addAll(p.getSupportedParameters());

                // not allowed
                properties.remove(ExportProvider.PARAM_TARGET);
            }

            return new ArrayList<String>(properties);
        }
    };

    ListView<String> parameterView = new ListView<String>("param", parameterModel) {

        private static final long serialVersionUID = -7838477347365823022L;

        @Override
        protected void populateItem(ListItem<String> item) {
            boolean isContentType = IOProvider.PARAM_CONTENT_TYPE.equals(item.getModelObject());

            // name
            item.add(new Label("name", item.getModelObject()));

            // text field
            TextField<String> textField = new TextField<String>("field",
                    new FieldFieldModel(item.getModelObject()));
            textField.setVisible(!isContentType);
            item.add(textField);

            // contentType select field
            DropDownChoice<String> contentType;
            if (isContentType) {
                IOProviderDescriptor pf = HaleIO.findIOProviderFactory(InstanceWriter.class, null,
                        getTarget().getProviderId());
                List<String> types = new ArrayList<String>();
                for (IContentType type : pf.getSupportedTypes()) {
                    types.add(type.getId());
                }
                contentType = new DropDownChoice<String>("contentType",
                        new FieldFieldModel(item.getModelObject()), types, new ContentTypeChoiceRenderer());
            } else {
                contentType = new DropDownChoice<String>("contentType", new ArrayList<String>());
                contentType.setVisible(false);
            }
            item.add(contentType);
        }

    };
    config.add(parameterView);

    // update parameter panel on target selection change
    selectTarget.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        private static final long serialVersionUID = 8004015871380712045L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // update config panel

            target.add(config);
        }

    });
}

From source file:org.apache.openmeetings.web.admin.configurations.ConfigForm.java

License:Apache License

public ConfigForm(String id, WebMarkupContainer listContainer, Configuration configuration) {
    super(id, new CompoundPropertyModel<Configuration>(configuration));
    setOutputMarkupId(true);/*w  ww  .ja v  a 2s .  co  m*/
    this.listContainer = listContainer;
    add(new RequiredTextField<String>("key").setLabel(Model.of(Application.getString(267)))
            .add(new IValidator<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public void validate(IValidatable<String> validatable) {
                    Configuration c = getBean(ConfigurationDao.class).forceGet(validatable.getValue());
                    if (c != null && !c.isDeleted()
                            && !c.getId().equals(ConfigForm.this.getModelObject().getId())) {
                        validatable.error(new ValidationError(Application.getString(1544L)));
                    }
                }
            }));
    add(new TextField<String>("value").setLabel(Model.of(Application.getString(271))));
    add(forDatePattern("updated", WEB_DATE_PATTERN));
    add(new Label("user.login"));
    add(new TextArea<String>("comment"));

    // attach an ajax validation behavior to all form component's keydown
    // event and throttle it down to once per second
    add(new AjaxFormValidatingBehavior("keydown", Duration.ONE_SECOND));
}