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

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

Introduction

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

Prototype

public ValidationError setVariable(String name, Object value) 

Source Link

Document

Sets a key and value in the variables map for use in substitution.

Usage

From source file:org.obiba.onyx.quartz.core.wicket.layout.impl.validation.ComparingDataSourceValidator.java

License:Open Source License

private ValidationError newValidationError(String message, Data data, Data dataToCompare) {
    ValidationError error = new ValidationError();
    error.addMessageKey("DataSourceValidator." + message);
    if (data != null) {
        error.setVariable("expected", data.getValue());
    } else {/*from w  w w .j  a  v  a  2 s.co  m*/
        error.setVariable("expected", "?");
    }
    if (dataToCompare != null) {
        error.setVariable("found", dataToCompare.getValue());
    } else {
        error.setVariable("found", "?");
    }
    return error;
}

From source file:org.obiba.onyx.webapp.crypt.X509CertificateValidator.java

License:Open Source License

public void validate(IValidatable validatable) {
    String certString = (String) validatable.getValue();
    try {/* w  ww  .j  a v  a 2  s  .c o m*/
        CryptUtil.parseCertificate(certString);
    } catch (CertificateException e) {
        ValidationError error = new ValidationError();
        error.addMessageKey("InvalidCertificate");
        error.setVariable("certificateException", e);
        validatable.error(error);
    }
}

From source file:org.obiba.onyx.wicket.data.DataValidator.java

License:Open Source License

public void validate(IValidatable validatable) {
    Data value = (Data) validatable.getValue();

    // targetValue should be null if either value or value.getValue is null.
    Object targetValue = value != null ? value.getValue() : null;

    // Handle the case where there's a value and it needs conversion before being validated
    if (targetValue != null && dataType != value.getType()) {
        try {/*from w  w  w .  ja  va  2s.co  m*/
            targetValue = convertValue(value);
        } catch (IllegalArgumentException e) {
            // Can't convert a String to a number
            ValidationError error = new ValidationError();
            error.addMessageKey("DataValidator.incompatibleTypes");
            error.setVariable("expectedType", dataType);
            error.setVariable("actualType", value.getType());
            error.setVariable("value", value.getValue());
            validatable.error(error);
            return;
        }
    }

    // value may be null here. If so, create the Validatable with null value.
    Validatable adaptedValidatable = new Validatable(targetValue);

    // Have the underlying validator validate the value
    validator.validate(adaptedValidatable);

    // Extract any validation errors and report them on the original Validatable.
    for (Object error : adaptedValidatable.getErrors()) {
        validatable.error((IValidationError) error);
    }

}

From source file:org.wicketstuff.multitextinput.MultiTextInput.java

License:Apache License

/**
 * Robbed from {@link FormComponent}/*  w ww  .j  ava 2  s . c om*/
 * 
 * @param e
 * @param error
 */
private void reportValidationError(ConversionException e, ValidationError error) {
    final Locale locale = e.getLocale();
    if (locale != null) {
        error.setVariable("locale", locale);
    }
    error.setVariable("exception", e);
    Format format = e.getFormat();
    if (format instanceof SimpleDateFormat) {
        error.setVariable("format", ((SimpleDateFormat) format).toLocalizedPattern());
    }

    Map<String, Object> variables = e.getVariables();
    if (variables != null) {
        error.getVariables().putAll(variables);
    }

    error(error);
}

From source file:org.wicketstuff.multitextinput.MultiTextInput.java

License:Apache License

@SuppressWarnings("unchecked")
private Collection<T> convertInput(String[] inputs) {
    if (getType() == null) {
        try {/*from   w  ww  . ja  va2  s . c o m*/
            return convertValue(inputs);
        } catch (ConversionException e) {
            ValidationError error = new ValidationError();
            if (e.getResourceKey() != null) {
                error.addMessageKey(e.getResourceKey());
            }
            if (e.getTargetType() != null) {
                error.addMessageKey("ConversionError." + Classes.simpleName(e.getTargetType()));
            }
            error.addMessageKey("ConversionError");
            reportValidationError(e, error);
        }
    } else {
        final IConverter<Collection<T>> converter = getConverter(getType());
        String curInput = "";
        try {
            Collection<T> convertedInput = new ArrayList<T>();
            if (inputs != null) {
                for (String input : inputs) {
                    curInput = input;
                    // 2011.04.14. akiraly This cast does not seem okay
                    // converter returns Collection<T> which is cast to T?
                    convertedInput.add((T) converter.convertToObject(curInput, getLocale()));
                }
            }
            return convertedInput;
        } catch (ConversionException e) {
            ValidationError error = new ValidationError();
            if (e.getResourceKey() != null) {
                error.addMessageKey(e.getResourceKey());
            }
            String simpleName = Classes.simpleName(getType());
            error.addMessageKey("IConverter." + simpleName);
            error.addMessageKey("IConverter");
            error.setVariable("type", simpleName);
            error.setVariable("input", curInput);
            reportValidationError(e, error);
        }
    }
    return null;
}

From source file:org.wicketTutorial.customvalidator.UsernameValidator.java

License:Apache License

public void validate(IValidatable<String> validatable) {
    String chosenUserName = validatable.getValue();

    if (existingUsernames.contains(chosenUserName)) {
        ValidationError error = new ValidationError(this);
        Random random = new Random();

        error.setVariable("suggestedUserName", validatable.getValue() + random.nextInt());
        validatable.error(error);//w  w w . ja  va2 s .  c  om
    }
}

From source file:se.inera.axel.shs.broker.webconsole.agreement.AgreementFormPanel.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public AgreementFormPanel(final String panelId, final PageParameters parameters) {
    super(panelId);

    add(new FeedbackPanel("feedback"));

    ShsAgreement agreement = getAgreement(parameters);

    IModel<ShsAgreement> agreementModel = new CompoundPropertyModel<ShsAgreement>(agreement);

    final Form<ShsAgreement> form = new Form<ShsAgreement>("agreementForm", agreementModel) {
        private static final long serialVersionUID = 1L;

        @Override/*  www  .  ja  v a2  s .co  m*/
        protected void onSubmit() {
            super.onSubmit();
            ShsAgreement shsAgreement = getModelObject();
            parameters.set(CURRENT_UUID.toString(), shsAgreement.getUuid());

            agreementAdminService.save(shsAgreement);

            String view = parameters.get(VIEW.toString()).toString();
            if (view != null && view.equals("xml")) {
                setResponsePage(EditAgreementPage.class, parameters);
            } else {
                setResponsePage(AgreementPage.class);
            }
        }
    };

    boolean isEditMode = isEditMode(parameters);

    final TextField<String> uuidField = new TextField<String>("uuid");
    uuidField.setRequired(true).setEnabled(!isEditMode);
    uuidField.add(new IValidator<String>() {

        @Override
        public void validate(IValidatable<String> validatable) {
            String value = validatable.getValue();
            if (!isEditMode(parameters)) {
                if (agreementAdminService.findOne(value) != null) {
                    ValidationError error = new ValidationError();
                    error.addMessageKey("agreementForm.uuid.Exists");
                    error.setVariable("uuid", value);
                    validatable.error(error);
                }
            }
        }
    });
    form.add(new ControlGroupContainer(uuidField));

    List<Principal> principals = getPrincipals();
    IChoiceRenderer<Principal> principalRenderer = new PrincipalChoiceRenderer();
    form.add(new ControlGroupContainer(
            new DropDownChoice("shs.principal", Model.ofList(principals), principalRenderer)
                    .setRequired(true)));

    List<Customer> customers = getCustomers();
    IChoiceRenderer<Customer> customerRenderer = new CustomerChoiceRenderer();
    DropDownChoice ddcCustomer = new DropDownChoice("shs.customer", Model.ofList(customers), customerRenderer);
    form.add(new ControlGroupContainer(ddcCustomer));

    DropDownChoice<String> transferType = new DropDownChoice<String>("transferType",
            Model.ofList(Constant.TRANSFER_TYPE_LIST));
    transferType.setRequired(true);
    form.add(new ControlGroupContainer(transferType));

    form.add(new ControlGroupContainer(new CheckBox("shs.confirm.required")));
    form.add(new ControlGroupContainer(
            new DropDownChoice<String>("shs.direction.flow", Model.ofList(Constant.DIRECTION_LIST))
                    .setRequired(true)));

    List<Product> products = getProducts();
    IChoiceRenderer<Product> productRenderer = new ProductChoiceRenderer();
    form.add(new ControlGroupContainer(
            new DropDownChoice("shs.product.0", Model.ofList(products), productRenderer).setRequired(true)));

    form.add(new ControlGroupContainer(
            new DateTextField("general.valid.validFrom.date", "yyyy-MM-dd").setRequired(true)));
    form.add(new ControlGroupContainer(new DateTextField("general.valid.validTo.date", "yyyy-MM-dd")));

    form.add(new ControlGroupContainer(new TextArea<String>("general.description")));

    form.add(new SubmitLink("showxml") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onSubmit() {
            super.onSubmit();
            parameters.set(VIEW.toString(), "xml");
        }
    });
    form.add(new SubmitLink("submit"));
    add(form);
}

From source file:se.inera.axel.shs.broker.webconsole.agreement.AgreementXmlPanel.java

License:Open Source License

/**
 * Constructor//w  w w .jav  a  2  s  . co  m
 * 
 * @param id
 * @param parameters
 */
public AgreementXmlPanel(final String id, final PageParameters parameters) {
    super(id);

    add(new FeedbackPanel("feedback"));

    ShsAgreement agreement = getAgreement(parameters);

    marshaller = new ShsAgreementMarshaller(ObjectFactory.class.getClassLoader());

    String xml = marshaller.marshal(agreement);

    XmlForm xmlForm = new XmlForm(agreement.getUuid(), xml);
    IModel<XmlForm> xmlModel = new CompoundPropertyModel<>(xmlForm);

    Form<XmlForm> form = new Form<XmlForm>("agreementForm", xmlModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            super.onSubmit();
            XmlForm xmlForm = getModelObject();
            try {
                ShsAgreement agreement = unmarshal(xmlForm.getXml());

                parameters.set(CURRENT_UUID.toString(), agreement.getUuid());
                agreementAdminService.save(agreement);

                String view = parameters.get(VIEW.toString()).toString();
                if (view != null && view.equals("form")) {
                    setResponsePage(EditAgreementPage.class, parameters);
                } else {
                    setResponsePage(AgreementPage.class);
                }
            } catch (Exception e) {
                error(e.getMessage());
                e.printStackTrace();
            }
        }

        private ShsAgreement unmarshal(String xml) {
            ShsAgreementMarshaller marshaller = new ShsAgreementMarshaller(
                    ObjectFactory.class.getClassLoader());
            return marshaller.unmarshal(xml);
        }

    };
    form.add(new HiddenField<String>("uuid"));
    TextArea<String> xmlField = new TextArea<>("xml");
    xmlField.add(new IValidator<String>() {

        @Override
        public void validate(IValidatable<String> validatable) {
            ShsAgreement shsAgreement = null;

            try {
                shsAgreement = marshaller.unmarshal(validatable.getValue());
            } catch (XmlException e) {
                ValidationError error = new ValidationError();
                error.addKey("xml.InvalidXml");
                validatable.error(error);
                return;
            }

            if (isEditMode(parameters)) {
                String currentUUID = parameters.get(CURRENT_UUID.toString()).toOptionalString();
                if (currentUUID != null && !currentUUID.equalsIgnoreCase(shsAgreement.getUuid())) {
                    ValidationError error = new ValidationError();
                    error.addKey("uuid.ReadOnly");
                    error.setVariable("originalUUID", currentUUID);
                    validatable.error(error);
                    return;
                }
            } else {
                if (agreementAdminService.findOne(shsAgreement.getUuid()) != null) {
                    ValidationError error = new ValidationError();
                    error.addKey("Exists");
                    error.setVariable("uuid", shsAgreement.getUuid());
                    validatable.error(error);
                    return;
                }
            }
        }
    });
    form.add(new ControlGroupContainer(xmlField));
    form.add(new SubmitLink("showform") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onSubmit() {
            super.onSubmit();
            parameters.set(VIEW.toString(), "form");
        }
    });
    form.add(new SubmitLink("submit"));
    add(form);
}

From source file:se.inera.axel.shs.broker.webconsole.product.ProductFormPanel.java

License:Open Source License

/**
 * Constructor//from   ww  w .  j a  va2  s  . com
 *
 * @param panelId
 * @param parameters
 */
public ProductFormPanel(final String panelId, final PageParameters parameters) {

    super(panelId);

    add(new FeedbackPanel("feedback"));

    final IModel<ShsProduct> product = getProduct(parameters);

    // Create form
    final Form<ShsProduct> form = new Form<ShsProduct>("productForm", product);

    form.add(new ControlGroupContainer(new TextField<String>("commonName")));
    TextField<String> uuidField = new TextField<String>("uuid");
    uuidField.setRequired(true);

    uuidField.setEnabled(!isEditMode(parameters));
    uuidField.add(new IValidator<String>() {

        @Override
        public void validate(IValidatable<String> validatable) {
            String value = validatable.getValue();
            if (!isEditMode(parameters)) {
                if (productAdminService.getProduct(value) != null) {
                    ValidationError error = new ValidationError();
                    error.addMessageKey("Exists");
                    error.setVariable("uuid", value);
                    validatable.error(error);
                }
            }
        }
    });

    form.add(new ControlGroupContainer(uuidField));

    form.add(new ControlGroupContainer(new TextField<String>("labeledURI")));
    form.add(new ControlGroupContainer(new TextArea<String>("description")));

    CheckBox respRequiredField = new CheckBox("respRequired") {
        private static final long serialVersionUID = 1L;

        @Override
        protected IModel<?> initModel() {
            return new YesNoBooleanConverterModel(super.initModel());
        }
    };

    form.add(new ControlGroupContainer(respRequiredField));

    form.add(new ControlGroupContainer(getPrincipalDropDownChoice()));

    form.add(getDataListView(product));
    form.add(new SubmitLink("addData") {
        @Override
        public void onSubmit() {
            product.getObject().getData().add(new Data());
        }

        private static final long serialVersionUID = 1L;
    }.setOutputMarkupId(true));

    form.add(getReplyDataListView(product));
    form.add(new SubmitLink("addReplyData") {
        @Override
        public void onSubmit() {
            product.getObject().getReplyData().add(new ReplyData());
        }

        private static final long serialVersionUID = 1L;
    }.setOutputMarkupId(true));

    form.add(new SubmitLink("showxml") {
        @Override
        public void onSubmit() {
            super.onSubmit();

            // The xml-view loads the model from the data store so we need to save it first.
            ShsProduct shsProduct = form.getModelObject();
            productAdminService.save(shsProduct);

            parameters.remove("view");
            parameters.add("view", "xml");
            parameters.add(AdminPageParameters.EDIT_MODE.toString(), true);
            parameters.add("uuid", ((ShsProduct) getParent().getDefaultModelObject()).getUuid());
            setResponsePage(EditProductPage.class, parameters);
        }

        private static final long serialVersionUID = 1L;
    });
    form.add(new SubmitLink("submit") {
        @Override
        public void onSubmit() {

            ShsProduct shsProduct = form.getModelObject();
            productAdminService.save(shsProduct);

            setResponsePage(ProductPage.class);
        }

        private static final long serialVersionUID = 1L;
    });
    add(form);
}

From source file:se.inera.axel.shs.broker.webconsole.product.ProductXmlPanel.java

License:Open Source License

/**
 * Constructor//ww w .ja v a 2  s .  c o m
 * 
 * @param id
 * @param parameters
 */
public ProductXmlPanel(final String id, final PageParameters parameters) {
    super(id);

    add(new FeedbackPanel("feedback"));

    ShsProduct product = getProduct(parameters);

    marshaller = new ShsProductMarshaller(ObjectFactory.class.getClassLoader());
    String xml = marshaller.marshal(product);

    XmlForm xmlForm = new XmlForm("uuid1", xml);
    IModel<XmlForm> xmlModel = new CompoundPropertyModel<XmlForm>(xmlForm);

    Form<XmlForm> form = new Form<XmlForm>("productForm", xmlModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            super.onSubmit();
            XmlForm xmlForm = getModelObject();
            try {
                ShsProduct shsProduct = marshaller.unmarshal(xmlForm.getXml());
                parameters.add("uuid", shsProduct.getUuid());
                productAdminService.save(shsProduct);

                String view = parameters.get("view").toString();
                if (view != null && view.equals("form")) {
                    setResponsePage(EditProductPage.class, parameters);
                } else {
                    setResponsePage(ProductPage.class);
                }
            } catch (Exception e) {
                error(e.getMessage());
                e.printStackTrace();
            }
        }

    };
    form.add(new HiddenField<String>("uuid"));
    TextArea<String> xmlField = new TextArea<String>("xml");
    xmlField.add(new IValidator<String>() {

        @Override
        public void validate(IValidatable<String> validatable) {
            ShsProduct shsProduct = null;

            try {
                shsProduct = marshaller.unmarshal(validatable.getValue());
            } catch (XmlException e) {
                ValidationError error = new ValidationError();
                error.addMessageKey("xml.InvalidXml");
                validatable.error(error);
                return;
            }

            if (isEditMode(parameters)) {
                String currentUUID = parameters.get(CURRENT_UUID.toString()).toOptionalString();
                if (currentUUID != null && !currentUUID.equalsIgnoreCase(shsProduct.getUuid())) {
                    ValidationError error = new ValidationError();
                    error.addMessageKey("uuid.ReadOnly");
                    error.setVariable("originalUUID", currentUUID);
                    validatable.error(error);
                    return;
                }
            } else {
                if (productAdminService.getProduct(shsProduct.getUuid()) != null) {
                    ValidationError error = new ValidationError();
                    error.addMessageKey("Exists");
                    error.setVariable("uuid", shsProduct.getUuid());
                    validatable.error(error);
                    return;
                }
            }
        }
    });
    form.add(new ControlGroupContainer(xmlField));

    form.add(new SubmitLink("showform") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onSubmit() {
            super.onSubmit();
            parameters.remove("view");
            parameters.add("view", "form");
        }
    });
    form.add(new SubmitLink("submit"));
    add(form);
}