Example usage for org.apache.wicket.validation.validator StringValidator StringValidator

List of usage examples for org.apache.wicket.validation.validator StringValidator StringValidator

Introduction

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

Prototype

protected StringValidator() 

Source Link

Document

Constructor used for subclasses who want to set the range using #setRange(Comparable,Comparable)

Usage

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  ww  w  . j a  va  2 s. com*/
        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:hsa.awp.admingui.edit.SubjectPanel.java

License:Open Source License

/**
 * Constructor with {@link Panel}ID and {@link Subject}.
 *
 * @param id  the {@link Panel}ID//from  w w w  .  j a v a 2s .c om
 * @param sub the subject which has to be edited
 */
public SubjectPanel(String id, final Subject sub) {

    super(id);

    final Subject subject;
    if (sub == null) {
        subject = Subject.getInstance(controller.getActiveMandator(getSession()));
    } else {
        subject = sub;
    }

    final Form<Object> form = new Form<Object>("form");
    // form.setDefaultModel(new CompoundPropertyModel<Subject>(subject));

    name.setRequired(true);

    StringValidator stringValidator = new StringValidator() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -8354513043330314939L;

        @Override
        protected void onValidate(IValidatable<String> validatable) {

            Subject found = controller.getSubjectByNameAndMandator(validatable.getValue(), getSession());

            if (found != null) {
                validatable.error(new IValidationError() {
                    @Override
                    public String getErrorMessage(IErrorMessageSource messageSource) {

                        return "Fachname existiert bereits";
                    }
                });
            }
        }
    };

    if (subject.getId() == 0) {
        name.add(stringValidator);
    }

    category.setRequired(true);
    category.add(categoryAutoCompleteBehavior);

    feedbackPanel.setOutputMarkupId(true);

    // add(new FeedbackPanel("feedback").setOutputMarkupId(true));
    // TODO Sprache:
    add(panelLabel.setDefaultModel(new Model<String>("Fach bearbeiten")));

    form.add(name.setDefaultModel(new Model<String>(subject.getName())));
    try {
        form.add(category.setDefaultModel(new Model<String>(subject.getCategory().getName())));
    } catch (NullPointerException e) {
        form.add(category.setDefaultModel(new Model<String>("")));
    }
    form.add(desc.setDefaultModel(new Model<String>(subject.getDescription())));
    form.add(link.setDefaultModel(new Model<String>(subject.getLink())));

    form.add(new AjaxButton("submit") {
        /**
         * generated serialization id.
         */
        private static final long serialVersionUID = -6537464906539587006L;

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {

            target.addComponent(feedbackPanel);
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            target.addComponent(form);
            target.addComponent(feedbackPanel);

            if (saveSubject(subject))
                return;

            // TODO Sprache:
            feedbackPanel.info("Eingaben bernommen.");
            this.setVisible(false);
        }
    });
    add(feedbackPanel);
    add(form);
}

From source file:hsa.awp.admingui.rule.rules.AbstractRulePanel.java

License:Open Source License

/**
 * Creates a new RulePanel./*from  w w  w .  j  a  v  a 2 s . c om*/
 *
 * @param id   wicket-id.
 * @param rule rule that is created or edited. The values will be used to fill the rule's input fields with default values.
 */
public AbstractRulePanel(String id, T rule) {

    super(id);

    if (rule == null) {
        throw new IllegalArgumentException("No rule given");
    }

    this.rule = rule;

    feedbackPanel = new FeedbackPanel("feedbackPanel");
    feedbackPanel.setOutputMarkupId(true);
    add(feedbackPanel);

    form = new Form<Object>("rule.form");
    add(form);

    name = new TextField<String>("rule.name", new Model<String>(rule.getName()));
    name.setRequired(true);
    name.add(new StringValidator() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -3503841430415001646L;

        @Override
        protected void onValidate(IValidatable<String> validatable) {

            if (validatable.getValue() == null || validatable.getValue().equals("")) {
                validatable.error(new IValidationErrorSerializable() {
                    /**
                     * unique serialization id.
                     */
                    private static final long serialVersionUID = 2893129433111740381L;

                    @Override
                    public String getErrorMessage(IErrorMessageSource messageSource) {

                        return "Kein Name ausgewhlt";
                    }
                });
            }

            if (validatable.isValid()
                    && controller.getRuleByNameAndMandator(validatable.getValue(), getSession()) != null) {
                validatable.error(new IValidationErrorSerializable() {
                    /**
                     * unique serialization id.
                     */
                    private static final long serialVersionUID = 4583676857544619819L;

                    @Override
                    public String getErrorMessage(IErrorMessageSource messageSource) {

                        return "Regelname existiert bereits.";
                    }
                });
            }
        }
    });

    form.add(name);

    form.add(new AjaxButton("rule.submit") {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -725179447540520694L;

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {

            target.addComponent(feedbackPanel);
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            target.addComponent(feedbackPanel);

            submitOnClick(target, form);
        }
    });
}

From source file:org.geoserver.web.data.workspace.WorkspaceNewPage.java

License:Open Source License

public WorkspaceNewPage() {
    WorkspaceInfo ws = getCatalog().getFactory().createWorkspace();

    form = new Form("form", new CompoundPropertyModel(ws)) {
        @Override//from   www  . j a  v  a  2s . c o m
        protected void onSubmit() {
            Catalog catalog = getCatalog();

            WorkspaceInfo ws = (WorkspaceInfo) form.getModelObject();

            NamespaceInfo ns = catalog.getFactory().createNamespace();
            ns.setPrefix(ws.getName());
            ns.setURI(nsUriTextField.getDefaultModelObjectAsString());

            catalog.add(ws);
            catalog.add(ns);
            if (defaultWs)
                catalog.setDefaultWorkspace(ws);

            //TODO: set the response page to be the edit 
            doReturn(WorkspacePage.class);
        }
    };
    add(form);

    TextField<String> nameTextField = new TextField<String>("name");
    nameTextField.setRequired(true);
    nameTextField.add(new XMLNameValidator());
    nameTextField.add(new StringValidator() {

        @Override
        protected void onValidate(IValidatable<String> validatable) {
            if (CatalogImpl.DEFAULT.equals(validatable.getValue())) {
                error(validatable, "defaultWsError");
            }
        }
    });
    form.add(nameTextField.setRequired(true));

    nsUriTextField = new TextField("uri", new Model());
    // maybe a bit too restrictive, but better than not validation at all
    nsUriTextField.setRequired(true);
    nsUriTextField.add(new URIValidator());
    form.add(nsUriTextField);

    CheckBox defaultChk = new CheckBox("default", new PropertyModel(this, "defaultWs"));
    form.add(defaultChk);

    SubmitLink submitLink = new SubmitLink("submit", form);
    form.add(submitLink);
    form.setDefaultButton(submitLink);

    AjaxLink cancelLink = new AjaxLink("cancel") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            doReturn(WorkspacePage.class);
        }
    };
    form.add(cancelLink);

}

From source file:org.geoserver.wms.web.data.ExternalGraphicPanel.java

License:Open Source License

/**
 * @param id/*  w  w w .  j  av a2  s.c  o  m*/
 * @param model Must return a {@link ResourceInfo}
 */
public ExternalGraphicPanel(String id, final CompoundPropertyModel<StyleInfo> styleModel,
        final Form styleForm) {
    super(id, styleModel);

    // container for ajax updates
    final WebMarkupContainer container = new WebMarkupContainer("container");
    container.setOutputMarkupId(true);
    add(container);

    table = new WebMarkupContainer("list");
    table.setOutputMarkupId(true);

    IModel<String> bind = styleModel.bind("legend.onlineResource");
    onlineResource = new TextField<String>("onlineResource", bind);
    onlineResource.add(new StringValidator() {
        final List<String> EXTENSIONS = Arrays.asList(new String[] { "png", "gif", "jpeg", "jpg" });

        protected void onValidate(IValidatable<String> input) {
            String value = input.getValue();
            int last = value == null ? -1 : value.lastIndexOf('.');
            if (last == -1 || !EXTENSIONS.contains(value.substring(last + 1).toLowerCase())) {
                ValidationError error = new ValidationError();
                error.setMessage("Not an image");
                error.addMessageKey("nonImage");
                input.error(error);
                return;
            }
            URI uri = null;
            try {
                uri = new URI(value);
            } catch (URISyntaxException e1) {
                // Unable to check if absolute
            }
            if (uri != null && uri.isAbsolute()) {
                try {
                    String baseUrl = baseURL(onlineResource.getForm());
                    if (!value.startsWith(baseUrl)) {
                        onlineResource.warn("Recommend use of styles directory at " + baseUrl);
                    }
                    URL url = uri.toURL();
                    URLConnection conn = url.openConnection();
                    if ("text/html".equals(conn.getContentType())) {
                        ValidationError error = new ValidationError();
                        error.setMessage("Unable to access image");
                        error.addMessageKey("imageUnavailable");
                        input.error(error);
                        return; // error message back!
                    }
                } catch (MalformedURLException e) {
                    ValidationError error = new ValidationError();
                    error.setMessage("Unable to access image");
                    error.addMessageKey("imageUnavailable");
                    input.error(error);
                } catch (IOException e) {
                    ValidationError error = new ValidationError();
                    error.setMessage("Unable to access image");
                    error.addMessageKey("imageUnavailable");
                    input.error(error);
                }
                return; // no further checks possible
            } else {
                GeoServerResourceLoader resources = GeoServerApplication.get().getResourceLoader();
                try {
                    File styles = resources.find("styles");
                    String[] path = value.split(File.separator);
                    File test = resources.find(styles, path);
                    if (test == null) {
                        ValidationError error = new ValidationError();
                        error.setMessage("File not found in styles directory");
                        error.addMessageKey("imageNotFound");
                        input.error(error);
                    }
                } catch (IOException e) {
                    ValidationError error = new ValidationError();
                    error.setMessage("File not found in styles directory");
                    error.addMessageKey("imageNotFound");
                    input.error(error);
                }
            }
        }
    });
    onlineResource.setOutputMarkupId(true);
    table.add(onlineResource);

    // add the autofill button
    autoFill = new GeoServerAjaxFormLink("autoFill", styleForm) {
        @Override
        public void onClick(AjaxRequestTarget target, Form form) {
            onlineResource.processInput();
            if (onlineResource.getModelObject() != null) {
                URL url = null;
                try {
                    String baseUrl = baseURL(form);
                    String external = onlineResource.getModelObject().toString();

                    URI uri = new URI(external);
                    if (uri.isAbsolute()) {
                        url = uri.toURL();
                        if (!external.startsWith(baseUrl)) {
                            form.warn("Recommend use of styles directory at " + baseUrl);
                        }
                    } else {
                        url = new URL(baseUrl + "styles/" + external);
                    }

                    URLConnection conn = url.openConnection();
                    if ("text/html".equals(conn.getContentType())) {
                        form.error("Unable to access url");
                        return; // error message back!
                    }

                    format.setModelValue(conn.getContentType());
                    BufferedImage image = ImageIO.read(conn.getInputStream());
                    width.setModelValue("" + image.getWidth());
                    height.setModelValue("" + image.getHeight());
                } catch (FileNotFoundException notFound) {
                    form.error("Unable to access " + url);
                } catch (Exception e) {
                    e.printStackTrace();
                    form.error("Recommend use of styles directory at " + e);
                }
            }

            target.addComponent(format);
            target.addComponent(width);
            target.addComponent(height);
        }
    };

    table.add(autoFill);

    format = new TextField("format", styleModel.bind("legend.format"));
    format.setOutputMarkupId(true);
    table.add(format);

    width = new TextField("width", styleModel.bind("legend.width"), Integer.class);
    width.add(NumberValidator.minimum(0));
    width.setOutputMarkupId(true);
    table.add(width);

    height = new TextField("height", styleModel.bind("legend.height"), Integer.class);
    height.add(NumberValidator.minimum(0));
    height.setOutputMarkupId(true);
    table.add(height);

    table.add(new AttributeModifier("style", true, showhideStyleModel));

    container.add(table);

    showhideForm = new Form("showhide") {
        @Override
        protected void onSubmit() {
            super.onSubmit();
        }
    };
    showhideForm.setMarkupId("showhideForm");
    container.add(showhideForm);

    show = new AjaxButton("show") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            updateVisibility(true);
            target.addComponent(ExternalGraphicPanel.this);
        }
    };
    container.add(show);
    showhideForm.add(show);

    hide = new AjaxButton("hide") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            onlineResource.setModelObject("");
            format.setModelObject("");
            width.setModelObject("0");
            height.setModelObject("0");

            updateVisibility(false);
            target.addComponent(ExternalGraphicPanel.this);
        }
    };
    container.add(hide);
    showhideForm.add(hide);

    String url = styleModel.getObject().getLegend().getOnlineResource();
    boolean visible = url != null && !url.isEmpty();
    updateVisibility(visible);

}