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() 

Source Link

Document

Constructs an empty error

Usage

From source file:ar.edu.udc.cirtock.view.intranet.negocio.FormularioInsumo.java

License:Apache License

public FormularioInsumo(final PageParameters parameters) {

    super(parameters);

    add(new FeedbackPanel("feedbackErrors", new ExactLevelFeedbackMessageFilter(FeedbackMessage.ERROR)));
    formulario = new Form("formulario_insumo");

    nombre = new RequiredTextField<String>("nombre", new Model());

    nombre.add(new IValidator<String>() {
        @Override//from   w  w w  .j a  v  a 2s  . com
        public void validate(IValidatable<String> validatable) {
            String nombre = validatable.getValue().trim().toUpperCase();
            if (!nombre.matches("^[\\w\\s]{3,20}$")) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'nombre' no es valido");
                validatable.error(error);
            }
        }

    });
    formulario.add(nombre);

    descripcion = new RequiredTextField<String>("descripcion", new Model());

    descripcion.add(new IValidator<String>() {
        @Override
        public void validate(IValidatable<String> validatable) {
            String descripcion = validatable.getValue().trim().toUpperCase();
            if (!descripcion.matches("^[A-Za-z  ]{3,50}$")) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'descripcion' no es valido");
                validatable.error(error);
            }
        }

    });
    formulario.add(descripcion);

    cantidad = new NumberTextField<Integer>("cantidad", new Model());
    cantidad.setType(Integer.class);
    cantidad.add(new IValidator<Integer>() {
        @Override
        public void validate(IValidatable<Integer> validatable) {
            Integer cantidad = validatable.getValue();
            if (cantidad < 0) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'cantidad' no es valido");
                validatable.error(error);
            }
        }
    });

    formulario.add(cantidad);

    formulario.add(new Button("enviar") {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void onSubmit() {
            String desc = (String) descripcion.getModelObject();
            String nomb = (String) nombre.getModelObject();
            Integer cant = cantidad.getModelObject();
            Connection conn = null;
            try {

                conn = CirtockConnection.getConection("cirtock", "cirtock", "cirtock");
                Insumo ins = new Insumo();
                ins.setDescripcion(desc);
                ins.setNombre(nomb);
                ins.setCantidad(cant);
                ins.insert("", conn);

            } catch (CirtockException e) {
                System.out.println("Error al acceder a la base de datos");
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    ;
                }
            }
            setResponsePage(InsumoPage.class);
        };
    });

    add(formulario);
}

From source file:au.org.theark.study.web.component.managestudy.StudyLogoValidator.java

License:Open Source License

public void validate(IValidatable<List<FileUpload>> pValidatable) {

    List<FileUpload> fileUploadList = pValidatable.getValue();

    for (FileUpload fileUploadImage : fileUploadList) {

        String fileExtension = StringUtils.getFilenameExtension(fileUploadImage.getClientFileName());
        ValidationError error = new ValidationError();

        try {//  w ww  . j a va  2s  .c o  m
            // Check extension ok
            if (fileExtension != null && !fileExtensions.contains(fileExtension.toLowerCase())) {
                error.addMessageKey("study.studyLogoFileType");
                error.setVariable("extensions", fileExtensions.toString());
                pValidatable.error(error);
            } // Check size ok
            else if (fileUploadImage.getSize() > fileSize.bytes()) {
                error.addMessageKey("study.studyLogoFileSize");
                pValidatable.error(error);
            } else {
                // Read image, to work out width and height
                image = new SerializableBufferedImage(ImageIO.read(fileUploadImage.getInputStream()));

                if (image.getHeight() > 100) {
                    error.addMessageKey("study.studyLogoPixelSize");
                    pValidatable.error(error);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            error.addMessageKey("study.studyLogoImageError");
            pValidatable.error(error);
        }

    }

}

From source file:com.alfredmuponda.lostandfound.util.ItemNumberValidator.java

License:Apache License

public void error(IValidatable validatable, String errorKey) {
    ValidationError error = new ValidationError();
    error.addKey(getClass().getSimpleName() + "." + errorKey);
    validatable.error(error);//w  w w.  j  a  va2s . c o m
}

From source file:com.chitek.ignition.drivers.generictcp.meta.config.ui.MessageConfigUI.java

License:Apache License

private void handleOnUpload(InputStream inputStream) {

    try {/*  w w  w.  ja  v  a2 s  .co  m*/
        StringBuilder sb = new StringBuilder();

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = br.readLine()) != null)
            sb.append(line);
        br.close();

        MessageConfig importConfig = MessageConfig.fromXMLString(sb.toString());

        // Increment imported message ID if necessary to make it unique
        int newMessageId = getNextMessageId(importConfig.getMessageId() - 1);
        if (newMessageId != importConfig.getMessageId()) {
            importConfig.setMessageId(newMessageId);
            warn(new StringResourceModel("warn.importIdChanged", this, null, currentMessageId).getString());
        }
        getConfig().addMessageConfig(importConfig);
        currentMessage = importConfig;
        currentMessageId = importConfig.getMessageId();

        // Refresh the model data in the list editor
        currentMessageIdDropdown.clearInput();
        messageIdTextField.clearInput();
        messageAliasTextField.clearInput();
        editor.reloadModel();

        // Make sure the new alias is unique (can't be done in the validator)
        for (MessageConfig message : getConfig().getMessageList()) {
            if (importConfig.getMessageAlias().equalsIgnoreCase(message.getMessageAlias())) {
                ValidationError error = new ValidationError();
                error.addKey(UniqueMessageAliasValidator.messageKey);
                messageAliasTextField.error(error);
                break;
            }
        }

        info(new StringResourceModel("info.import", this, null, currentMessageId).getString());

    } catch (Exception e) {
        error(getString("import.error") + " Exception: " + e.toString());
    }

}

From source file:com.chitek.wicket.listeditor.UniqueListItemValidator.java

License:Apache License

/**
 * Validator for items in {@link ListEditor}. Validates the input to be unique among all
 * entrys in the list. /*from   w  w w .  j  a  v  a  2  s . c o  m*/
 */
@SuppressWarnings("rawtypes")
@Override
public void validate(IValidatable<T> validatable) {

    ListEditor<?> editor = parent.findParent(ListEditor.class);
    String id = parent.getId();

    int count = 0;
    List<FormComponent> fields = editor.getComponentsById(id, FormComponent.class);

    String parentValue = getValue(validatable);

    if (filter != null && caseSensitive && !filter.contains(parentValue))
        return;
    if (filter != null && !caseSensitive && !filter.contains(parentValue.toLowerCase()))
        return;
    if (filter != null && !caseSensitive && !filter.contains(parentValue.toUpperCase()))
        return;

    for (FormComponent field : fields) {
        String value = field.getRawInput() != null ? field.getRawInput().toString() : null;

        if (value != null
                && (caseSensitive ? value.equals(parentValue) : value.equalsIgnoreCase(parentValue))) {
            count++;
        }
    }

    if (count > 1) {
        ValidationError error = new ValidationError();
        error.addKey(messageKey);
        validatable.error(error);
    }
}

From source file:com.chitek.wicket.NonMatchStringValidator.java

License:Apache License

@Override
public void validate(IValidatable<String> validatable) {
    String value = validatable.getValue();
    for (String match : Arrays.asList(matches)) {
        if (value.equalsIgnoreCase(match)) {
            ValidationError error = new ValidationError();
            error.addKey("StringValidator.noMatch");
            validatable.error(error);//from w  w  w.j a  v  a 2s. c o  m
        }
    }
}

From source file:com.cubeia.backoffice.web.wallet.AccountList.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//from   w  w  w .  j  a  v  a  2 s .  com
*            Page parameters
*/
public AccountList(final PageParameters parameters) {
    Form<AccountList> searchForm = new Form<AccountList>("searchForm",
            new CompoundPropertyModel<AccountList>(this));
    TextField<Long> idField = new TextField<Long>("userId");
    searchForm.add(idField);
    TextField<Long> userNameField = new TextField<Long>("accountId");
    searchForm.add(userNameField);

    final CheckBoxMultipleChoice<AccountStatus> statusesChoice = new CheckBoxMultipleChoice<AccountStatus>(
            "includeStatuses", Arrays.asList(AccountStatus.values()));
    statusesChoice.setSuffix(" ");
    statusesChoice.add(new IValidator<Collection<AccountStatus>>() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(IValidatable<Collection<AccountStatus>> validatable) {
            if (statusesChoice.getInputAsArray() == null) {
                ValidationError error = new ValidationError().setMessage("Select one or more status");
                validatable.error(error);
            }
        }

    });

    searchForm.add(statusesChoice);

    CheckBoxMultipleChoice<AccountType> typesChoice = new CheckBoxMultipleChoice<AccountType>("includeTypes",
            asList(AccountType.values()));
    typesChoice.setSuffix(" ");
    searchForm.add(typesChoice);

    add(searchForm);
    add(new FeedbackPanel("feedback"));

    ISortableDataProvider<Account, String> dataProvider = new AccountDataProvider();
    ArrayList<IColumn<Account, String>> columns = new ArrayList<IColumn<Account, String>>();

    columns.add(new AbstractColumn<Account, String>(new Model<String>("Account Id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "" + accountId,
                    "details for account id " + accountId, AccountDetails.class,
                    params(AccountDetails.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.ID.name();
        }
    });

    columns.add(new AbstractColumn<Account, String>(new Model<String>("User id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long userId = account.getUserId();
            Component panel = new LabelLinkPanel(componentId, "" + userId, UserSummary.class,
                    params(UserSummary.PARAM_USER_ID, userId)).setVisible(userId != null);
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.USER_ID.name();
        }
    });

    columns.add(new PropertyColumn<Account, String>(new Model<String>("Account name"),
            AccountsOrder.ACCOUNT_NAME.name(), "information.name"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Status"), AccountsOrder.STATUS.name(),
            "status"));
    columns.add(
            new PropertyColumn<Account, String>(new Model<String>("Type"), AccountsOrder.TYPE.name(), "type"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Currency"), "currencyCode"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Creation date"),
            AccountsOrder.CREATION_DATE.name(), "created"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Close date"),
            AccountsOrder.CLOSE_DATE.name(), "closed"));
    columns.add(new AbstractColumn<Account, String>(new Model<String>("Actions")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "transactions",
                    "transactions involving account id " + accountId, TransactionList.class,
                    params(TransactionList.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }
    });

    AjaxFallbackDefaultDataTable<Account, String> userTable = new AjaxFallbackDefaultDataTable<Account, String>(
            "accountTable", columns, dataProvider, 20);
    add(userTable);
}

From source file:com.cubeia.games.poker.admin.wicket.pages.wallet.AccountList.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//from w ww .j  a v a  2s.com
*            Page parameters
*/
public AccountList(final PageParameters parameters) {
    super(parameters);
    Form<AccountList> searchForm = new Form<AccountList>("searchForm",
            new CompoundPropertyModel<AccountList>(this));
    TextField<Long> idField = new TextField<Long>("userId");
    searchForm.add(idField);
    TextField<Long> userNameField = new TextField<Long>("accountId");
    searchForm.add(userNameField);

    final CheckBoxMultipleChoice<AccountStatus> statusesChoice = new CheckBoxMultipleChoice<AccountStatus>(
            "includeStatuses", Arrays.asList(AccountStatus.values()));
    statusesChoice.setSuffix(" ");
    statusesChoice.add(new IValidator<Collection<AccountStatus>>() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(IValidatable<Collection<AccountStatus>> validatable) {
            if (statusesChoice.getInputAsArray() == null) {
                ValidationError error = new ValidationError().setMessage("Select one or more status");
                validatable.error(error);
            }
        }

    });

    searchForm.add(statusesChoice);

    CheckBoxMultipleChoice<AccountType> typesChoice = new CheckBoxMultipleChoice<AccountType>("includeTypes",
            asList(AccountType.values()));
    typesChoice.setSuffix(" ");
    searchForm.add(typesChoice);

    add(searchForm);
    add(new FeedbackPanel("feedback"));

    ISortableDataProvider<Account, String> dataProvider = new AccountDataProvider();
    ArrayList<IColumn<Account, String>> columns = new ArrayList<IColumn<Account, String>>();

    columns.add(new AbstractColumn<Account, String>(new Model<String>("Account Id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "" + accountId,
                    "details for account id " + accountId, AccountDetails.class,
                    params(AccountDetails.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.ID.name();
        }
    });

    columns.add(new AbstractColumn<Account, String>(new Model<String>("User id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long userId = account.getUserId();
            Component panel = new LabelLinkPanel(componentId, "" + userId, UserSummary.class,
                    params(UserSummary.PARAM_USER_ID, userId)).setVisible(userId != null);
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.USER_ID.name();
        }
    });

    columns.add(new PropertyColumn<Account, String>(new Model<String>("Account name"),
            AccountsOrder.ACCOUNT_NAME.name(), "information.name"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Status"), AccountsOrder.STATUS.name(),
            "status"));
    columns.add(
            new PropertyColumn<Account, String>(new Model<String>("Type"), AccountsOrder.TYPE.name(), "type"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Currency"), "currencyCode"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Creation date"),
            AccountsOrder.CREATION_DATE.name(), "created"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Close date"),
            AccountsOrder.CLOSE_DATE.name(), "closed"));
    columns.add(new AbstractColumn<Account, String>(new Model<String>("Actions")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "transactions",
                    "transactions involving account id " + accountId, TransactionList.class,
                    params(TransactionList.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }
    });

    AjaxFallbackDefaultDataTable<Account, String> userTable = new AjaxFallbackDefaultDataTable<Account, String>(
            "accountTable", columns, dataProvider, 20);
    add(userTable);
}

From source file:com.doculibre.constellio.wicket.panels.admin.relevance.collection.rules.AddEditBoostRulePanel.java

License:Open Source License

public AddEditBoostRulePanel(String id, BoostRule boostRule, Integer boostRuleListPosition) {
    super(id, true);

    this.boostRuleListPosition = boostRuleListPosition;
    this.boostRuleDTO = new BoostRuleDTO(boostRule);

    Form form = getForm();//from  w w  w.j a v  a  2 s .com
    form.setModel(new CompoundPropertyModel(boostRuleDTO));// pr eviter les repetitions

    TextField regex = new TextField("regex");// grace a setModel plus besoin de : new PropertyModel(this, "regex")
    regex.add(new IValidator() {
        @Override
        public void validate(IValidatable validatable) {
            String regex = (String) validatable.getValue();
            String errorMessage = FormElementValidationService.validateContent(new StringBuilder(regex),
                    FormElementValidationService.ContentType.REGEX, ConstellioSession.get().getLocale());
            if (!errorMessage.isEmpty()) {
                validatable.error(new ValidationError().setMessage(errorMessage));
            }
        }

    });
    form.add(regex);

    TextField boost = new TextField("boost", Double.class);
    boost.setRequired(true);
    form.add(boost);
}

From source file:com.doculibre.constellio.wicket.panels.admin.relevance.indexField.EditIndexFieldRelevancePanel.java

License:Open Source License

public EditIndexFieldRelevancePanel(String id, IModel indexField) {
    super(id, true);

    this.indexField = indexField;
    setName(((IndexField) indexField.getObject()).getName());
    setIndexBoost(((IndexField) indexField.getObject()).getBoost().toString());

    Form form = getForm();/* www  .j  a v  a  2  s . co m*/
    form.setModel(new CompoundPropertyModel(this));// a cause de repetitions

    Label name = new Label("name");// grace a setModel plus besoin de : new PropertyModel(this, "regex")
    form.add(name);

    TextField indexBoost = new TextField("boost");
    indexBoost.add(new IValidator() {
        @Override
        public void validate(IValidatable validatable) {
            String indexBoost = (String) validatable.getValue();
            String errorMessage = FormElementValidationService.validateContent(new StringBuilder(indexBoost),
                    FormElementValidationService.ContentType.DOUBLE, ConstellioSession.get().getLocale());
            if (!errorMessage.isEmpty()) {
                validatable.error(new ValidationError().setMessage(errorMessage));
            } else {
                double boostTodouble = Double.parseDouble(indexBoost);
                if (boostTodouble < 0) {
                    validatable.error(new ValidationError().setMessage(indexBoost + " < 0"));
                }
            }
        }
    });
    form.add(indexBoost);
}