Example usage for org.apache.wicket.model CompoundPropertyModel bind

List of usage examples for org.apache.wicket.model CompoundPropertyModel bind

Introduction

In this page you can find the example usage for org.apache.wicket.model CompoundPropertyModel bind.

Prototype

public <S> IModel<S> bind(String property) 

Source Link

Document

Binds this model to a special property by returning a model that has this compound model as its nested/wrapped model and the property which should be evaluated.

Usage

From source file:com.cubeia.backoffice.web.user.EditUser.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//  w w w.j  a  v  a2  s  .  com
*            Page parameters
*/
public EditUser(PageParameters params) {
    if (!assertValidUserid(params)) {
        return;
    }

    final Long userId = params.get(PARAM_USER_ID).toLongObject();
    loadFormData(userId);

    if (getUser() == null || getUser().getStatus() == UserStatus.REMOVED) {
        log.debug("user is removed, id = " + userId);
        setInvalidUserResponsePage(userId);
        return;
    }

    add(createBlockActionLink(userId));

    add(new Link<Void>("removeActionLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            userService.setUserStatus(userId, UserStatus.REMOVED);
            setInvalidUserResponsePage(userId);
        }
    });

    Form<?> userForm = new Form<Void>("userForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            userService.updateUser(user);
            info("User updated, id = " + user.getUserId());
            loadFormData(userId);
        }
    };

    CompoundPropertyModel<?> cpm = new CompoundPropertyModel<EditUser>(this);

    userForm.add(new Label(PARAM_USER_ID, cpm.bind("user.userId")));
    userForm.add(new Label("status", cpm.bind("user.status")));
    userForm.add(new TextField<Long>("operatorId", cpm.<Long>bind("user.operatorId")).setEnabled(false));
    userForm.add(new TextField<String>("externalUserId", cpm.<String>bind("user.externalUserId")));
    userForm.add(new TextField<String>("userName", cpm.<String>bind("user.userName")));
    userForm.add(new TextField<String>("firstName", cpm.<String>bind("user.userInformation.firstName")));
    userForm.add(new TextField<String>("lastName", cpm.<String>bind("user.userInformation.lastName")));
    userForm.add(new TextField<String>("email", cpm.<String>bind("user.userInformation.email"))
            .add(EmailAddressValidator.getInstance()));
    userForm.add(new TextField<String>("title", cpm.<String>bind("user.userInformation.title")));
    userForm.add(new TextField<String>("city", cpm.<String>bind("user.userInformation.city")));
    userForm.add(
            new TextField<String>("billingAddress", cpm.<String>bind("user.userInformation.billingAddress")));
    userForm.add(new TextField<String>("fax", cpm.<String>bind("user.userInformation.fax")));
    userForm.add(new TextField<String>("cellphone", cpm.<String>bind("user.userInformation.cellphone")));
    userForm.add(new DropDownChoice<String>("country", cpm.<String>bind("user.userInformation.country"),
            Arrays.asList(Locale.getISOCountries()), new IChoiceRenderer<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getDisplayValue(String isoCountry) {
                    return new Locale(Locale.ENGLISH.getLanguage(), (String) isoCountry)
                            .getDisplayCountry(Locale.ENGLISH);
                }

                @Override
                public String getIdValue(String isoCountry, int id) {
                    return "" + id;
                }
            }));

    userForm.add(new TextField<String>("zipcode", cpm.<String>bind("user.userInformation.zipcode")));
    userForm.add(new TextField<String>("state", cpm.<String>bind("user.userInformation.state")));
    userForm.add(new TextField<String>("phone", cpm.<String>bind("user.userInformation.phone")));
    userForm.add(new TextField<String>("workphone", cpm.<String>bind("user.userInformation.workphone")));
    userForm.add(new DropDownChoice<Gender>("gender", cpm.<Gender>bind("user.userInformation.gender"),
            Arrays.asList(Gender.values())));
    userForm.add(createAttributesListView());
    add(userForm);

    Form<?> addAttributeForm = new Form<Void>("addAttrForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            if (user.getAttributes() == null) {
                user.setAttributes(new HashMap<String, String>());
            }
            if (getNewAttributeKey() != null) {
                user.getAttributes().put("" + getNewAttributeKey(), "" + getNewAttributeValue());
            }
            setNewAttributeKey(null);
            setNewAttributeValue(null);
        }
    };
    addAttributeForm.add(new SubmitLink("addAttrLink").add(new Label("addAttrLabel", "Add attribute")));
    addAttributeForm.add(new TextField<String>("newAttrKey", cpm.<String>bind("newAttributeKey")));
    addAttributeForm.add(new TextField<String>("newAttrValue", cpm.<String>bind("newAttributeValue")));
    userForm.add(addAttributeForm);

    Form<?> pwdForm = new Form<Void>("changePasswordForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            userService.updatePassword(user.getUserId(), getPassword1());
            setPassword1(null);
            setPassword2(null);
        }
    };
    PasswordTextField pwd1 = new PasswordTextField("password1", cpm.<String>bind("password1"));
    PasswordTextField pwd2 = new PasswordTextField("password2", cpm.<String>bind("password2"));
    pwdForm.add(new EqualPasswordInputValidator(pwd1, pwd2));
    pwdForm.add(pwd1);
    pwdForm.add(pwd2);
    add(pwdForm);

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

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

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param params/*  w  w  w .j  av a 2s  . c o  m*/
*            Page parameters
*/
public AccountDetails(PageParameters params) {
    Long accountId = params.get(PARAM_ACCOUNT_ID).toLongObject();
    account = walletService.getAccountById(accountId);

    if (getAccount() == null) {
        setInvalidAccountResponsePage(accountId);
        return;
    }

    Long accountUserId = getAccount().getUserId();

    add(new LabelLinkPanel("editAccount", "edit", EditAccount.class,
            ParamBuilder.params(EditAccount.PARAM_ACCOUNT_ID, accountId)));

    CompoundPropertyModel<?> cpm = new CompoundPropertyModel<AccountDetails>(this);
    add(new Label("balance", cpm.bind("balance")));
    add(new Label(PARAM_ACCOUNT_ID, cpm.bind("account.id")));
    add(new Label("userId", cpm.bind("account.userId")));
    add(new Label("name", cpm.bind("account.information.name")));
    add(new Label("currency", cpm.bind("account.currencyCode")));
    add(new Label("status", cpm.bind("account.status")));
    add(new Label("created", cpm.bind("account.created")));
    add(new Label("closed", cpm.bind("account.closed")));
    add(new Label("gameId", cpm.bind("account.information.gameId")));
    add(new Label("objectId", cpm.bind("account.information.objectId")));
    add(new Label("type", cpm.bind("account.type")));
    add(new Label("negativeAmountAllowed", cpm.bind("account.negativeAmountAllowed")));

    add(new LabelLinkPanel("editUser", "edit", EditUser.class,
            ParamBuilder.params(EditUser.PARAM_USER_ID, accountUserId)));

    ISortableDataProvider<Entry, String> dataProvider = new EntriesDataProvider();
    List<IColumn<Entry, String>> columns = new ArrayList<IColumn<Entry, String>>();

    columns.add(
            new PropertyColumn<Entry, String>(Model.of("Tx id"), TransactionsOrder.ID.name(), "transactionId") {
                private static final long serialVersionUID = 1L;

                @Override
                public void populateItem(Item<ICellPopulator<Entry>> item, String componentId,
                        IModel<Entry> rowModel) {
                    Long txId = rowModel.getObject().getTransactionId();
                    PageParameters pageParams = new PageParameters();
                    pageParams.set("transactionId", txId);
                    item.add(new LabelLinkPanel(componentId, "" + txId, TransactionInfo.class, pageParams));
                }
            });

    columns.add(new PropertyColumn<Entry, String>(Model.of("Date"), "timestamp") {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Entry>> item, String componentId, IModel<Entry> model) {
            item.add(new Label(componentId, formatDate(model.getObject().getTimestamp())));
        }
    });

    columns.add(new PropertyColumn<Entry, String>(Model.of("Comment"), "transactionComment"));
    columns.add(new PropertyColumn<Entry, String>(Model.of("Amount"), "amount"));
    columns.add(new PropertyColumn<Entry, String>(Model.of("Resulting balance"), "resultingBalance"));

    AjaxFallbackDefaultDataTable<Entry, String> entryTable = new AjaxFallbackDefaultDataTable<Entry, String>(
            "entryTable", columns, dataProvider, 20);
    add(entryTable);
}

From source file:com.cubeia.games.poker.admin.wicket.pages.user.EditUser.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//from  w w w . j  av a2s.  co m
*            Page parameters
*/
public EditUser(PageParameters parameters) {
    super(parameters);
    if (!assertValidUserid(parameters)) {
        return;
    }

    final Long userId = parameters.get(PARAM_USER_ID).toLongObject();
    loadFormData(userId);

    if (getUser() == null || getUser().getStatus() == UserStatus.REMOVED) {
        log.debug("user is removed, id = " + userId);
        setInvalidUserResponsePage(userId);
        return;
    }

    add(createBlockActionLink(userId));

    add(new Link<Void>("removeActionLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            userService.setUserStatus(userId, UserStatus.REMOVED);
            setInvalidUserResponsePage(userId);
        }
    });

    Form<?> userForm = new Form<Void>("userForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            userService.updateUser(user);
            info("User updated, id = " + user.getUserId());
            loadFormData(userId);
        }
    };

    CompoundPropertyModel<?> cpm = new CompoundPropertyModel<EditUser>(this);

    userForm.add(new Label(PARAM_USER_ID, cpm.bind("user.userId")));
    userForm.add(new Label("status", cpm.bind("user.status")));
    userForm.add(new TextField<Long>("operatorId", cpm.<Long>bind("user.operatorId")).setEnabled(false));
    userForm.add(new TextField<String>("externalUserId", cpm.<String>bind("user.externalUserId")));
    userForm.add(new TextField<String>("userName", cpm.<String>bind("user.userName")));
    userForm.add(new TextField<String>("firstName", cpm.<String>bind("user.userInformation.firstName")));
    userForm.add(new TextField<String>("lastName", cpm.<String>bind("user.userInformation.lastName")));
    userForm.add(new TextField<String>("email", cpm.<String>bind("user.userInformation.email"))
            .add(EmailAddressValidator.getInstance()));
    userForm.add(new TextField<String>("title", cpm.<String>bind("user.userInformation.title")));
    userForm.add(new TextField<String>("city", cpm.<String>bind("user.userInformation.city")));
    userForm.add(
            new TextField<String>("billingAddress", cpm.<String>bind("user.userInformation.billingAddress")));
    userForm.add(new TextField<String>("fax", cpm.<String>bind("user.userInformation.fax")));
    userForm.add(new TextField<String>("cellphone", cpm.<String>bind("user.userInformation.cellphone")));
    userForm.add(new DropDownChoice<String>("country", cpm.<String>bind("user.userInformation.country"),
            Arrays.asList(Locale.getISOCountries()), new IChoiceRenderer<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getDisplayValue(String isoCountry) {
                    return new Locale(Locale.ENGLISH.getLanguage(), (String) isoCountry)
                            .getDisplayCountry(Locale.ENGLISH);
                }

                @Override
                public String getIdValue(String isoCountry, int id) {
                    return "" + id;
                }
            }));

    userForm.add(new TextField<String>("zipcode", cpm.<String>bind("user.userInformation.zipcode")));
    userForm.add(new TextField<String>("state", cpm.<String>bind("user.userInformation.state")));
    userForm.add(new TextField<String>("phone", cpm.<String>bind("user.userInformation.phone")));
    userForm.add(new TextField<String>("workphone", cpm.<String>bind("user.userInformation.workphone")));
    userForm.add(new DropDownChoice<Gender>("gender", cpm.<Gender>bind("user.userInformation.gender"),
            Arrays.asList(Gender.values())));
    userForm.add(createAttributesListView());
    add(userForm);

    Form<?> addAttributeForm = new Form<Void>("addAttrForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            if (user.getAttributes() == null) {
                user.setAttributes(new HashMap<String, String>());
            }
            if (getNewAttributeKey() != null) {
                user.getAttributes().put("" + getNewAttributeKey(), "" + getNewAttributeValue());
            }
            setNewAttributeKey(null);
            setNewAttributeValue(null);
        }
    };
    addAttributeForm.add(new SubmitLink("addAttrLink").add(new Label("addAttrLabel", "Add attribute")));
    addAttributeForm.add(new TextField<String>("newAttrKey", cpm.<String>bind("newAttributeKey")));
    addAttributeForm.add(new TextField<String>("newAttrValue", cpm.<String>bind("newAttributeValue")));
    userForm.add(addAttributeForm);

    Form<?> pwdForm = new Form<Void>("changePasswordForm") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            userService.updatePassword(user.getUserId(), getPassword1());
            setPassword1(null);
            setPassword2(null);
        }
    };
    PasswordTextField pwd1 = new PasswordTextField("password1", cpm.<String>bind("password1"));
    PasswordTextField pwd2 = new PasswordTextField("password2", cpm.<String>bind("password2"));
    pwdForm.add(new EqualPasswordInputValidator(pwd1, pwd2));
    pwdForm.add(pwd1);
    pwdForm.add(pwd2);
    add(pwdForm);

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

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

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param params/*  w  ww .  ja  va2 s  .c  o m*/
*            Page parameters
*/
public AccountDetails(PageParameters params) {
    super(params);
    Long accountId = params.get(PARAM_ACCOUNT_ID).toLongObject();
    account = walletService.getAccountById(accountId);

    if (getAccount() == null) {
        setInvalidAccountResponsePage(accountId);
        return;
    }

    Long accountUserId = getAccount().getUserId();

    add(new LabelLinkPanel("editAccount", "edit", EditAccount.class,
            params(EditAccount.PARAM_ACCOUNT_ID, accountId)));

    CompoundPropertyModel<?> cpm = new CompoundPropertyModel<AccountDetails>(this);
    add(new Label("balance", cpm.bind("balance")));
    add(new Label(PARAM_ACCOUNT_ID, cpm.bind("account.id")));
    add(new Label("userId", cpm.bind("account.userId")));
    add(new Label("name", cpm.bind("account.information.name")));
    add(new Label("currency", cpm.bind("account.currencyCode")));
    add(new Label("status", cpm.bind("account.status")));
    add(new Label("created", cpm.bind("account.created")));
    add(new Label("closed", cpm.bind("account.closed")));
    add(new Label("gameId", cpm.bind("account.information.gameId")));
    add(new Label("objectId", cpm.bind("account.information.objectId")));
    add(new Label("type", cpm.bind("account.type")));
    add(new Label("negativeAmountAllowed", cpm.bind("account.negativeAmountAllowed")));

    add(new LabelLinkPanel("editUser", "edit", EditUser.class, params(EditUser.PARAM_USER_ID, accountUserId)));

    ISortableDataProvider<Entry, String> dataProvider = new EntriesDataProvider();
    List<IColumn<Entry, String>> columns = new ArrayList<IColumn<Entry, String>>();

    columns.add(
            new PropertyColumn<Entry, String>(Model.of("Tx id"), TransactionsOrder.ID.name(), "transactionId") {
                private static final long serialVersionUID = 1L;

                @Override
                public void populateItem(Item<ICellPopulator<Entry>> item, String componentId,
                        IModel<Entry> rowModel) {
                    Long txId = rowModel.getObject().getTransactionId();
                    PageParameters pageParams = new PageParameters();
                    pageParams.set("transactionId", txId);
                    item.add(new LabelLinkPanel(componentId, "" + txId, TransactionInfo.class, pageParams));
                }
            });

    columns.add(new PropertyColumn<Entry, String>(Model.of("Date"), "timestamp") {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Entry>> item, String componentId, IModel<Entry> model) {
            item.add(new Label(componentId, formatDate(model.getObject().getTimestamp())));
        }
    });

    columns.add(new PropertyColumn<Entry, String>(Model.of("Comment"), "transactionComment"));
    columns.add(new PropertyColumn<Entry, String>(Model.of("Amount"), "amount"));
    columns.add(new PropertyColumn<Entry, String>(Model.of("Resulting balance"), "resultingBalance"));

    AjaxFallbackDefaultDataTable<Entry, String> entryTable = new AjaxFallbackDefaultDataTable<Entry, String>(
            "entryTable", columns, dataProvider, 20);
    add(entryTable);
}

From source file:gr.abiss.calipso.wicket.CustomFieldsFormPanel.java

License:Open Source License

@SuppressWarnings("serial")
private void addComponents(final CompoundPropertyModel model, final Metadata metadata, final List<Field> fields,
        final Map<String, FileUploadField> fileUploadFields) {
    //final AbstractItem item = (AbstractItem) model.getObject();
    List<FieldGroup> fieldGroupsList = metadata.getFieldGroups();
    @SuppressWarnings("unchecked")
    ListView fieldGroups = new ListView("fieldGroups", fieldGroupsList) {

        @Override/*from  w w  w  . ja  v a  2s  .c  om*/
        protected void populateItem(ListItem listItem) {
            FieldGroup fieldGroup = (FieldGroup) listItem.getModelObject();
            listItem.add(new Label("fieldGroupLabel", fieldGroup.getName()));
            List<Field> groupFields = fieldGroup.getFields();
            List<Field> editableGroupFields = new LinkedList<Field>();

            if (CollectionUtils.isNotEmpty(groupFields)) {
                for (Field field : groupFields) {
                    // is editable?
                    if (fields.contains(field)) {
                        editableGroupFields.add(field);
                    }
                }
            }
            ListView listView = new ListView("fields", editableGroupFields) {

                @Override
                @SuppressWarnings("deprecation")
                protected void populateItem(ListItem listItem) {
                    boolean preloadExistingValue = true;
                    final Field field = (Field) listItem.getModelObject();
                    // preload custom attribute
                    if (field.getCustomAttribute() == null) {
                        field.setCustomAttribute(getCalipso().loadItemCustomAttribute(getCurrentSpace(),
                                field.getName().getText()));
                    }
                    // preload value?
                    if (preloadExistingValue) {
                        AbstractItem history = (AbstractItem) model.getObject();
                        history.setValue(field.getName(), item.getValue(field.getName()));
                    }
                    // return the value for the field (see abstract item getCustomValue method)
                    Object fieldLastCustomValue = null;

                    String i18nedFieldLabelResourceKey = item.getSpace()
                            .getPropertyTranslationResourceKey(field.getName().getText());

                    if (item != null && !editMode) {
                        if (field.getName().isFile()) {
                            Set<Attachment> tmpAttachments = item.getAttachments();
                            if (tmpAttachments != null && tmpAttachments.size() > 0) {
                                for (Attachment attachment : tmpAttachments) {
                                    if (field.getLabel()
                                            .equals(AttachmentUtils.getBaseName(attachment.getFileName()))) {
                                        fieldLastCustomValue = attachment.getFileName();
                                        break;
                                    }
                                }
                            }

                        } else {
                            fieldLastCustomValue = item.getValue(field.getName());
                        }

                    }

                    // Decide whether the field is mandatory

                    boolean valueRequired = false;
                    //logger.info("fieldLastCustomValue for field " + field.getLabel() +": "+fieldLastCustomValue);
                    if (field.getMask() == State.MASK_MANDATORY
                            || (field.getMask() == State.MASK_MANDATORY_IF_EMPTY
                                    && (fieldLastCustomValue == null
                                            || StringUtils.isBlank(fieldLastCustomValue.toString())))) {
                        valueRequired = true; // value required
                    }

                    // go over custom fields
                    WebMarkupContainer labelContainer = new WebMarkupContainer("labelContainer");
                    listItem.add(labelContainer);

                    SimpleFormComponentLabel label = null;
                    if (field.getName().isDropDownType()) {
                        String autoValue;
                        final Map<String, String> options = field.getOptions();
                        if (field.getFieldType().equals(Field.FIELD_TYPE_DROPDOWN_HIERARCHICAL)) {
                            Fragment f = new Fragment("field", "treeField", CustomFieldsFormPanel.this);
                            // add HTML description through velocity
                            addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                    field.getCustomAttribute().getHtmlDescription(), null, true);
                            ItemFieldCustomAttribute customAttribute = field.getCustomAttribute();
                            //                        if(customAttribute == null){
                            //                           customAttribute = getCalipso().loadCustomAttribute(getCurrentSpace(), field.getName().getText());
                            //                           field.setCustomAttribute(customAttribute);
                            //                        }

                            // preload existing value
                            if (field.getCustomAttribute() != null && customAttribute.getLookupValue() == null
                                    && item.getCustomValue(field) != null) {
                                logger.info("preloading custom attribute for field: " + field.getLabel());
                                customAttribute.setLookupValue(getCalipso().loadCustomAttributeLookupValue(
                                        NumberUtils.createLong(item.getCustomValue(field).toString())));
                                customAttribute.setAllowedLookupValues(
                                        getCalipso().findActiveLookupValuesByCustomAttribute(customAttribute));
                            } else {
                                logger.info(
                                        "SKIPPED preloading custom attribute for field: " + field.getLabel());
                                customAttribute.setAllowedLookupValues(
                                        getCalipso().findActiveLookupValuesByCustomAttribute(customAttribute));
                            }
                            TreeChoice choice = new TreeChoice("field",
                                    new PropertyModel<CustomAttributeLookupValue>(field,
                                            "customAttribute.lookupValue"),
                                    customAttribute.getAllowedLookupValues(), customAttribute);

                            // TODO: temp, make configurable in space field form for 1520
                            int attrId = customAttribute.getId().intValue();
                            choice.setVisibleMenuLinks(
                                    attrId == 3 || attrId == 4 || attrId == 16 || attrId == 17);
                            //choice.setType(Long.class);
                            choice.setRequired(valueRequired);
                            // i18n
                            choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                            WebMarkupContainer border = new WebMarkupContainer("border");
                            f.add(border);
                            //border.add(new ErrorHighlighter(choice));
                            border.add(choice);
                            //choice.setModel(model.bind(field.getName().getText()));
                            //border.add(model.bind(choice, field.getName().getText()));
                            listItem.add(f.setRenderBodyOnly(true));
                            label = new SimpleFormComponentLabel("label", choice);
                        }
                        // get the type of component that will render the choices
                        else if (field.getFieldType().equals(Field.FIELD_TYPE_AUTOSUGGEST)) {

                            renderAutoSuggest(model, listItem, field, i18nedFieldLabelResourceKey,
                                    valueRequired, options);

                        } else {
                            // normal drop down
                            label = renderDropDown(model, listItem, field, i18nedFieldLabelResourceKey,
                                    valueRequired, options);

                        }

                    } else if (field.getName().equals(Field.Name.ASSIGNABLE_SPACES)) {
                        Fragment f = new Fragment("field", "dropDown", CustomFieldsFormPanel.this);

                        // add HTML description through velocity
                        addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                field.getCustomAttribute().getHtmlDescription(), null, true);

                        List assignableSpaces = loadAssignableSpaces(field);
                        final Map options = new LinkedHashMap();

                        // Replace value from space id to space description for
                        // reasons of appearance.
                        for (int i = 0; i < assignableSpaces.size(); i++) {
                            Space space = (Space) assignableSpaces.get(i);
                            if (!space.equals(getCurrentSpace())) {
                                options.put(space.getId(), localize(space.getNameTranslationResourceKey()));
                            } // if
                        } // for

                        final List keys = new ArrayList(options.keySet());

                        AssignableSpacesDropDownChoice choice = new AssignableSpacesDropDownChoice("field",
                                keys, new IChoiceRenderer() {
                                    @Override
                                    public Object getDisplayValue(Object o) {
                                        return o;
                                    };

                                    @Override
                                    public String getIdValue(Object o, int i) {
                                        return o.toString();
                                    };
                                });

                        choice.setNullValid(true);
                        // i18n
                        choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));

                        choice.setRequired(valueRequired);
                        choice.add(new Behavior() {
                            @Override
                            public void renderHead(Component component, IHeaderResponse response) {
                                response.renderJavaScript(new JavaScripts().setAssignableSpacesId.asString(),
                                        "setAssignableSpacesId");
                            }
                        });
                        choice.add(new AjaxFormComponentUpdatingBehavior("onChange") {
                            @Override
                            protected void onUpdate(AjaxRequestTarget target) {
                                if (statusChoice != null
                                        && !statusChoice.getDefaultModelObjectAsString().equals("")
                                        && !statusChoice.getDefaultModelObjectAsString().equals("-1")) {
                                    // if
                                    // (statusChoice.getValue().equals(String.valueOf(State.MOVE_TO_OTHER_SPACE))){
                                    // assignedToChoice.setChoices(getAssignableSpaceUsers());
                                    // assignedToChoice.setNullValid(false);
                                    // assignedToChoice.setVisible(true);
                                    // }//if
                                } // if
                                target.appendJavaScript("assignableSpacesId=" + "'"
                                        + assignableSpacesDropDownChoice.getMarkupId() + "';");
                                // This can happen at the creation of a new item
                                // where makes no sense to be moved to other space
                                if (assignedToChoice != null) {
                                    target.addComponent(assignedToChoice);
                                }
                            }// onUpdate

                            @Override
                            protected void onError(AjaxRequestTarget arg0, RuntimeException arg1) {
                                // Do nothing.
                                // It happens only if the choice be set to NULL by
                                // the user.
                                // The exception occurs because the model binds to
                                // space id that is from (primitive) type
                                // long and its value can not be set to NULL.
                            }

                        });

                        choice.setOutputMarkupId(true);
                        assignableSpacesDropDownChoice = choice;

                        if (itemViewFormPanel != null) {
                            itemViewFormPanel.getItemViewForm()
                                    .setAssignableSpacesDropDownChoice(assignableSpacesDropDownChoice);
                        } // if

                        WebMarkupContainer border = new WebMarkupContainer("border");
                        f.add(border);
                        border.add(new ErrorHighlighter(choice));
                        // Set field name explicitly to avoid runtime error
                        //border.add(model.bind(choice, field.getName() + ".id"));
                        choice.setModel(model.bind(field.getName() + ".id"));
                        border.add(choice);
                        listItem.add(f.setRenderBodyOnly(true));
                        border.setVisible(!CustomFieldsFormPanel.this.editMode);
                        label = new SimpleFormComponentLabel("label", choice);
                    } else if (field.getName().getType() == 6) {
                        // date picker
                        Fragment fragment = new Fragment("field", "dateFragment", CustomFieldsFormPanel.this);
                        // add HTML description through velocity
                        addVelocityTemplatePanel(fragment, "htmlDescriptionContainer", "htmlDescription",
                                field.getCustomAttribute().getHtmlDescription(), null, true);

                        if (item.getId() == 0 && item.getValue(field.getName()) == null
                                && field.getDefaultValueExpression() != null
                                && field.getDefaultValueExpression().equalsIgnoreCase("now")) {
                            item.setValue(field.getName(), new Date());
                        }
                        DateField calendar = new DateField("field",
                                preloadExistingValue
                                        ? new PropertyModel(model.getObject(), field.getName().getText())
                                        : new PropertyModel(model, field.getName().getText())) {

                            @Override
                            protected String getDateFormat() {
                                // TODO Auto-generated method stub
                                return metadata.getDateFormats().get(Metadata.DATE_FORMAT_SHORT);
                            }

                        };
                        calendar.setRequired(valueRequired);
                        // i8n
                        calendar.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));

                        fragment.add(calendar);
                        listItem.add(fragment.setRenderBodyOnly(true));
                        label = new SimpleFormComponentLabel("label", calendar);

                    }
                    // TODO: Creating new space item - users custom field
                    else if (field.getName().isOrganization()) { // is organization
                        // Get users list
                        Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this);
                        // add HTML description through velocity
                        addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                field.getCustomAttribute().getHtmlDescription(), null, true);

                        Organization organization = (Organization) item.getValue(field.getName());
                        // logger.debug("Item organization field has value: "+organization);
                        final List<Organization> allOrganizationsList = getCalipso().findAllOrganizations();
                        DropDownChoice organizationChoice = new DropDownChoice("field", allOrganizationsList,
                                new IChoiceRenderer() {
                                    // user's choice renderer
                                    // display value user's name
                                    @Override
                                    public Object getDisplayValue(Object object) {
                                        return ((Organization) object).getName();
                                    }

                                    @Override
                                    public String getIdValue(Object object, int index) {
                                        // id value user's id
                                        return index + "";
                                    }
                                });

                        organizationChoice.add(new ErrorHighlighter());

                        organizationChoice.setRequired(valueRequired);
                        // i18n
                        organizationChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                        //f.add(model.bind(organizationChoice, field.getName().getText()));
                        organizationChoice.setModel(model.bind(field.getName().getText()));
                        f.add(organizationChoice);
                        listItem.add(f.setRenderBodyOnly(true));
                        label = new SimpleFormComponentLabel("label", organizationChoice);
                    }

                    else if (field.getName().isFile()) {
                        // File
                        addFileInputField(model, fileUploadFields, listItem, field, i18nedFieldLabelResourceKey,
                                valueRequired);

                    }
                    // TODO: Creating new space item - organizations custom field
                    else if (field.getName().isUser()) { // is user

                        Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this);
                        // add HTML description through velocity
                        addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                field.getCustomAttribute().getHtmlDescription(), null, true);

                        // find organization id from field's options

                        String strOrgId = field.getOptions().get("organizationId");
                        Long orgId = Long.valueOf(strOrgId);
                        // load organization from database

                        Organization selectedOrg = getCalipso().loadOrganization(orgId);
                        // TODO: load all users from organization
                        // add new list of selected organizations
                        List<Organization> selectedOrganization = new ArrayList<Organization>();
                        // add selected organization
                        selectedOrganization.add(selectedOrg);

                        final List<User> usersFromOrganization = getCalipso()
                                .findUsersInOrganizations(selectedOrganization);

                        // TODO: dropdown of all organization

                        DropDownChoice usersFromOrganizationChoice = new DropDownChoice("field",
                                usersFromOrganization, new UserChoiceRenderer());
                        usersFromOrganizationChoice.setNullValid(false);
                        usersFromOrganizationChoice.setRequired(valueRequired);
                        // i18n
                        usersFromOrganizationChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                        //f.add(model.bind(usersFromOrganizationChoice, field.getName().getText()));
                        usersFromOrganizationChoice.setModel(model.bind(field.getName().getText()));
                        f.add(usersFromOrganizationChoice);
                        listItem.add(f.setRenderBodyOnly(true));
                        label = new SimpleFormComponentLabel("label", usersFromOrganizationChoice);

                    } else if (field.getName().isCountry()) {
                        // organization fragment holds a dropDown of countries
                        final List<Country> allCountriesList = getCalipso().findAllCountries();
                        Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this);
                        // add HTML description through velocity
                        addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                field.getCustomAttribute().getHtmlDescription(), null, true);

                        listItem.add(f.setRenderBodyOnly(true));
                        DropDownChoice countryChoice = getCountriesDropDown("field", allCountriesList);
                        countryChoice.add(new ErrorHighlighter());

                        countryChoice.setRequired(valueRequired);
                        // i18n
                        countryChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));

                        //f.add(model.bind(countryChoice, field.getName().getText()));
                        countryChoice.setModel(model.bind(field.getName().getText()));
                        f.add(countryChoice);
                        label = new SimpleFormComponentLabel("label", countryChoice);

                    }

                    else {
                        if (logger.isDebugEnabled())
                            logger.debug("model.getObject(): " + model.getObject());
                        if (logger.isDebugEnabled())
                            logger.debug(
                                    "model.getObject().getClass(): " + model.getObject().getClass().getName());
                        if (logger.isDebugEnabled())
                            logger.debug("field.getName().getText(): " + field.getName().getText());
                        //if(logger.isDebugEnabled()) logger.debug("((Item)model.getObject()).getCusStr01(): "+((Item)model.getObject()).getCusStr01());
                        FormComponent textField;
                        Fragment f;

                        if (field.isMultivalue()) {
                            f = new Fragment("field", "multipleValuesTextField", CustomFieldsFormPanel.this);
                            // add HTML description through velocity
                            addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                    field.getCustomAttribute().getHtmlDescription(), null, true);

                            if (logger.isDebugEnabled())
                                logger.debug("model.getObject(): " + model.getObject());
                            if (logger.isDebugEnabled())
                                logger.debug("field.getName().getText(): " + field.getName().getText());
                            textField = preloadExistingValue
                                    ? new MultipleValuesTextField("field",
                                            new PropertyModel(model.getObject(), field.getName().getText()),
                                            field.getXmlConfig())
                                    : new MultipleValuesTextField("field", field.getXmlConfig());
                        } else if (field.getLineCount() == 1) {
                            f = new Fragment("field", "textField", CustomFieldsFormPanel.this);
                            // add HTML description through velocity
                            addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                    field.getCustomAttribute().getHtmlDescription(), null, true);
                            textField = preloadExistingValue
                                    ? new TextField("field",
                                            new PropertyModel(model.getObject(), field.getName().getText()))
                                    : new TextField("field");
                        } else {
                            f = new Fragment("field", "textareaField", CustomFieldsFormPanel.this);
                            // add HTML description through velocity
                            addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                                    field.getCustomAttribute().getHtmlDescription(), null, true);
                            textField = preloadExistingValue ? new TextArea("field",
                                    new PropertyModel(model.getObject(), field.getName().getText())) {
                                @Override
                                protected void onComponentTag(ComponentTag tag) {
                                    super.onComponentTag(tag);
                                    tag.put("rows", field.getLineCount().toString());
                                }
                            } : new TextArea("field") {
                                @Override
                                protected void onComponentTag(ComponentTag tag) {
                                    super.onComponentTag(tag);
                                    tag.put("rows", field.getLineCount().toString());
                                }
                            };
                        }

                        // any validations for this field?
                        ValidationExpression validationExpression = getCalipso()
                                .loadValidationExpression(field.getValidationExpressionId());
                        if (validationExpression != null) {
                            textField.add(new ValidationExpressionValidator(validationExpression));
                        }

                        // TODO: do we need these two?
                        if (field.getName().getType() == 4) {
                            textField.setType(Double.class);
                        } else if (field.getName().isDecimalNumber()) {
                            textField.add(new PositiveNumberValidator());
                        }

                        textField.add(new ErrorHighlighter());
                        textField.setRequired(valueRequired);
                        // i18n
                        textField.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                        if (preloadExistingValue) {
                            f.add(textField);
                        } else {
                            //f.add(model.bind(textField, field.getName().getText()));
                            textField.setModel(model.bind(field.getName().getText()));
                            f.add(textField);
                        }
                        // f.add(textField);
                        listItem.add(f.setRenderBodyOnly(true));
                        label = new SimpleFormComponentLabel("label", textField);

                        // styles
                        FieldUtils.appendFieldStyles(field.getXmlConfig(), textField);
                    }

                    // add label
                    labelContainer.add(label != null ? label : new Label("label", ""));
                    if (field.getCustomAttribute() != null
                            && StringUtils.isBlank(field.getCustomAttribute().getHtmlDescription())) {
                        labelContainer.add(new SimpleAttributeModifier("class", "labelContainer"));
                    }
                    // mandatory?

                    // mark as mandatory in the UI?
                    labelContainer
                            .add(new Label("star", valueRequired ? "* " : " ").setEscapeModelStrings(false));
                }

                private SimpleFormComponentLabel renderAutoSuggest(final IModel model, ListItem listItem,
                        final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired,
                        final Map<String, String> options) {
                    SimpleFormComponentLabel label = null;
                    Fragment f = new Fragment("field", "autoCompleteFragment", CustomFieldsFormPanel.this);
                    // add HTML description through velocity
                    addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                            field.getCustomAttribute().getHtmlDescription(), null, true);

                    final List<String> autoKeys = new ArrayList<String>(
                            options != null ? new ArrayList<String>(options.keySet())
                                    : new ArrayList<String>());

                    // the autocomplet textField
                    // TODO: fix to render values instead of integer
                    AbstractAutoCompleteRenderer autoRenderer = new AbstractAutoCompleteRenderer() {

                        @Override
                        protected String getTextValue(Object object) {
                            // TODO Auto-generated method stub
                            return object.toString();
                        }

                        @Override
                        protected void renderChoice(Object object, Response response, String criteria) {
                            response.write(object.toString());
                        }

                    };

                    autoTextField = new AutoCompleteTextField("field",
                            new PropertyModel(field, "customAttribute.lookupValue")) {

                        // TODO: the list
                        @Override
                        protected Iterator<String> getChoices(String input) {

                            if (Strings.isEmpty(input)) {
                                List<String> emptyList = Collections.emptyList();
                                return emptyList.iterator();
                            }
                            List<String> searchResults = new ArrayList<String>();

                            for (String s : options.values()) {
                                if (s.startsWith(input)) {
                                    searchResults.add(s);
                                }
                            }
                            return searchResults.iterator();
                        }

                    };
                    autoTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") {

                        @Override
                        protected void onUpdate(AjaxRequestTarget target) {
                            // TODO Auto-generated method stub
                            List<String> searchResults = new ArrayList<String>();
                            for (String s : options.values()) {
                                if (s.startsWith((String) autoTextField.getModelObject())) {
                                    searchResults.add(s);
                                }
                            }
                            target.addComponent(autoTextField);
                        }
                    });
                    // i18n
                    autoTextField.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                    String componentValue = (String) ((autoTextField != null
                            && autoTextField.getModelObject() != null) ? autoTextField.getModelObject() : null);

                    autoTextField.setRequired(valueRequired);
                    WebMarkupContainer border = new WebMarkupContainer("border");
                    f.add(border);
                    border.add(new ErrorHighlighter(autoTextField));
                    autoTextField.setModel(new PropertyModel(model.getObject(), field.getName().getText()));
                    //border.add(model.bind(autoTextField, field.getName().getText()));
                    border.add(autoTextField);
                    if (logger.isDebugEnabled() && autoTextField != null
                            && autoTextField.getDefaultModelObjectAsString() != null) {
                        if (logger.isDebugEnabled())
                            logger.debug(
                                    "Auto complete value is :" + autoTextField.getDefaultModelObjectAsString());
                    }
                    listItem.add(f.setRenderBodyOnly(true));
                    label = new SimpleFormComponentLabel("label", autoTextField);
                    return label;

                    // -------------------------
                }

                private SimpleFormComponentLabel addFileInputField(final CompoundPropertyModel model,
                        final Map<String, FileUploadField> fileUploadFields, ListItem listItem,
                        final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired) {
                    SimpleFormComponentLabel label = null;
                    Fragment f = new Fragment("field", "fileField", CustomFieldsFormPanel.this);
                    // add HTML description through velocity
                    addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                            field.getCustomAttribute().getHtmlDescription(), null, true);

                    FileUploadField fileField = new FileUploadField("field");
                    fileUploadFields.put(field.getLabel(), fileField);
                    fileField.add(new ErrorHighlighter());

                    fileField.setRequired(valueRequired);
                    // i18n
                    fileField.setLabel(new ResourceModel(
                            StringUtils.isNotBlank(i18nedFieldLabelResourceKey) ? i18nedFieldLabelResourceKey
                                    : Field.FIELD_TYPE_SIMPLE_ATTACHEMENT));//field.getName().getText().equalsIgnoreCase(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT) ? Field.FIELD_TYPE_SIMPLE_ATTACHEMENT : i18nedFieldLabelResourceKey));

                    //f.add(model.bind(fileField, field.getName().getText()));
                    fileField.setModel(new Model());
                    // List<FileUpload> fileUploads = new LinkedList<FileUpload>();
                    f.add(fileField);
                    listItem.add(f.setRenderBodyOnly(true));
                    label = new SimpleFormComponentLabel("label", fileField);
                    return label;
                }

                /**
                 * @param model
                 * @param listItem
                 * @param field
                 * @param i18nedFieldLabelResourceKey
                 * @param valueRequired
                 * @param options
                 */
                private SimpleFormComponentLabel renderDropDown(final IModel model, ListItem listItem,
                        final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired,
                        final Map<String, String> options) {
                    SimpleFormComponentLabel label = null;
                    /*
                     final List<CustomAttributeLookupValue> lookupValues = getCalipso().findLookupValuesByCustomAttribute(field.getCustomAttribute());
                          TreeChoice choice = new TreeChoice("field", new PropertyModel(field, "customAttribute.lookupValue"), lookupValues);
                          choice.setType(CustomAttributeLookupValue.class);
                          //choice.setType(Long.class);
                          choice.setRequired(valueRequired);
                          // i18n
                          choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                          WebMarkupContainer border = new WebMarkupContainer("border");
                          f.add(border);
                          //border.add(new ErrorHighlighter(choice));
                          border.add(choice);
                                  
                     */

                    // drop down list
                    final Fragment fragment = new Fragment("field", "dropDown", CustomFieldsFormPanel.this);
                    if (field.getCustomAttribute() == null) {
                        field.setCustomAttribute(getCalipso().loadItemCustomAttribute(getCurrentSpace(),
                                field.getName().getText()));
                    }
                    // add HTML description through velocity
                    logger.info("field name:" + field.getName() + ", custom atribute: "
                            + field.getCustomAttribute());
                    addVelocityTemplatePanel(fragment, "htmlDescriptionContainer", "htmlDescription",
                            field.getCustomAttribute() != null ? field.getCustomAttribute().getHtmlDescription()
                                    : "",
                            null, true);

                    final List<CustomAttributeLookupValue> lookupValues = getCalipso()
                            .findActiveLookupValuesByCustomAttribute(field.getCustomAttribute());
                    // preselect previous user choice from DB if available
                    Object preselected = item.getValue(field.getName());
                    if (preselected != null) {
                        String sPreselectedId = preselected.toString();
                        if (CollectionUtils.isNotEmpty(lookupValues)) {
                            for (CustomAttributeLookupValue value : lookupValues) {
                                if ((value.getId() + "").equals(sPreselectedId)) {
                                    field.getCustomAttribute().setLookupValue(value);
                                    break;
                                }
                            }
                        }
                    }
                    // else set using the default string value instead, if any
                    // TODO: move this into a LookupValueDropDownChoice class
                    else {
                        String defaultStringValue = field.getCustomAttribute() != null
                                ? field.getCustomAttribute().getDefaultStringValue()
                                : null;
                        if (defaultStringValue != null && CollectionUtils.isNotEmpty(lookupValues)) {
                            for (CustomAttributeLookupValue value : lookupValues) {
                                if (value.getValue().equals(defaultStringValue)) {
                                    field.getCustomAttribute().setLookupValue(value);
                                    break;
                                }
                            }
                        }
                    }
                    DropDownChoice choice = new DropDownChoice("field",
                            new PropertyModel(field, "customAttribute.lookupValue"), lookupValues,
                            new IChoiceRenderer<CustomAttributeLookupValue>() {
                                @Override
                                public Object getDisplayValue(CustomAttributeLookupValue o) {
                                    return fragment.getString(o.getNameTranslationResourceKey());
                                }

                                @Override
                                public String getIdValue(CustomAttributeLookupValue o, int index) {
                                    return String.valueOf(index);
                                }
                            });
                    choice.setNullValid(true);

                    // i18n
                    choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                    choice.setRequired(valueRequired);
                    WebMarkupContainer border = new WebMarkupContainer("border");
                    fragment.add(border);
                    border.add(new ErrorHighlighter(choice));
                    //border.add(model.bind(choice, field.getName().getText()));
                    border.add(choice);
                    listItem.add(fragment.setRenderBodyOnly(true));
                    label = new SimpleFormComponentLabel("label", choice);
                    return label;
                }

                /**
                 * @param model
                 * @param listItem
                 * @param field
                 * @param i18nedFieldLabelResourceKey
                 * @param valueRequired
                 * @param options
                 */
                private SimpleFormComponentLabel renderPeriodPartDropDown(final CompoundPropertyModel model,
                        ListItem listItem, final Field field, String i18nedFieldLabelResourceKey,
                        boolean valueRequired, final List<Date> options) {
                    SimpleFormComponentLabel label = null;
                    // drop down list
                    Fragment f = new Fragment("field", "dropDown", CustomFieldsFormPanel.this);

                    // add HTML description through velocity
                    addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription",
                            field.getCustomAttribute().getHtmlDescription(), null, true);

                    DropDownChoice choice = new DropDownChoice("field", options, new IChoiceRenderer() {
                        @Override
                        public Object getDisplayValue(Object o) {
                            return DateUtils.format((Date) o);
                        };

                        @Override
                        public String getIdValue(Object o, int i) {
                            return String.valueOf(i);
                        };
                    });
                    choice.setNullValid(true);
                    // i18n
                    choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey));
                    choice.setRequired(valueRequired);
                    WebMarkupContainer border = new WebMarkupContainer("border");
                    f.add(border);
                    border.add(new ErrorHighlighter(choice));
                    //border.add(model.bind(choice, field.getName().getText()));
                    choice.setModel(model.bind(field.getName().getText()));
                    border.add(choice);
                    listItem.add(f.setRenderBodyOnly(true));
                    label = new SimpleFormComponentLabel("label", choice);
                    return label;
                }
            };
            if (editableGroupFields.isEmpty()) {
                listItem.setVisible(false);
            }
            listView.setReuseItems(true);
            listItem.add(listView.setRenderBodyOnly(true));

        }

    };
    add(fieldGroups.setReuseItems(true));

    // 
}

From source file:hsa.awp.admingui.edit.DrawProcedurePanel.java

License:Open Source License

/**
 * Constructor for {@link DrawProcedurePanel}. This is the setup for the
 * panel and here are all components registered.
 *
 * @param id       wicket:id which connects markup with code.
 * @param drawProc the draw procedure which have to be edit
 *//*w  w  w. j  a v  a2s .  c  om*/
public DrawProcedurePanel(String id, final DrawProcedure drawProc) {

    super(id);

    final DrawProcedure drawProcedure;

    if (drawProc == null) {
        drawProcedure = DrawProcedure.getInstance(controller.getActiveMandator(getSession()));
    } else {
        drawProcedure = drawProc;
    }

    CompoundPropertyModel<DrawProcedure> cpm = new CompoundPropertyModel<DrawProcedure>(drawProcedure);
    final Form<Object> form = new Form<Object>("form");
    form.setDefaultModel(cpm);
    feedbackPanel.setOutputMarkupId(true);
    form.setOutputMarkupId(true);
    // TODO Sprache:
    add(panelLabel.setDefaultModel(new Model<String>("Los-Prozedur bearbeiten")));

    // add validators
    drawName.setRequired(true);
    startDate.setRequired(true);
    endDate.setRequired(true);
    drawDate.setRequired(true);
    maximumPriorityListItems.setRequired(true);
    maximumPriorityLists.setRequired(true);

    // get&add default values
    drawName.setDefaultModel(cpm.bind("name"));
    startDate.setModelObject(drawProcedure.getStartDate().getTime());
    endDate.setModelObject(drawProcedure.getEndDate().getTime());
    drawDate.setModelObject(drawProcedure.getDrawDate().getTime());
    maximumPriorityListItems.setModelObject(Integer.toString(drawProcedure.getMaximumPriorityListItems()));
    maximumPriorityLists.setModelObject(Integer.toString(drawProcedure.getMaximumPriorityLists()));

    if (drawProcedure.getRuleBased() == 0)
        selected = TYPES.get(0);
    else if (drawProcedure.getRuleBased() == 1)
        selected = TYPES.get(1);

    form.add(drawName);

    form.add(startDate);

    form.add(endDate);

    form.add(drawDate);

    form.add(maximumPriorityListItems);

    form.add(maximumPriorityLists);

    form.add(ruleBasedTypes);

    form.add(new AjaxButton("submit") {
        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);

            Calendar sD = Calendar.getInstance();
            sD.setTime(startDate.getModelObject());

            Calendar eD = Calendar.getInstance();
            eD.setTime(endDate.getModelObject());

            Calendar dD = Calendar.getInstance();
            dD.setTime(drawDate.getModelObject());

            try {
                DrawProcedure draw = controller.getDrawProcedureById(drawProcedure.getId());
                if (draw == null) {
                    draw = drawProcedure;
                }

                if (selected == TYPES.get(0))
                    draw.setRuleBased(0);
                else if (selected == TYPES.get(1))
                    draw.setRuleBased(1);

                draw.setInterval(sD, eD);
                draw.setDrawDate(dD);
                draw.setMaximumPriorityListItems(Integer.valueOf(maximumPriorityListItems.getModelObject()));
                draw.setMaximumPriorityLists(Integer.valueOf(maximumPriorityLists.getModelObject()));

                // controller writeDrawProcedure to DB

                controller.writeDrawProcedure(draw);
                // setResponsePage(new OnePanelPage(new
                // ConfirmedEditPanel(OnePanelPage.getPanelIdOne())));
                // TODO Sprache:
                feedbackPanel.info("Eingaben bernommen.");
                this.setVisible(false);
            } catch (NumberFormatException nf) {
                // TODO Sprache:
                feedbackPanel.error("Zahl erwartet.");
            } catch (IllegalArgumentException iae) {
                // TODO Sprache:
                feedbackPanel.fatal("Prozedur kann nicht bearbeitet werden.");
            }
        }
    });
    add(feedbackPanel);
    add(form);
}

From source file:hsa.awp.admingui.edit.FifoProcedurePanel.java

License:Open Source License

/**
 * Constructor for {@link FifoProcedurePanel}. This is the setup for the panel and here are all components registered.
 *
 * @param id       wicket:id which connects markup with code.
 * @param fifoProc the existing FifoProcedure which have to be edit
 *//*from  w ww. j av a2s . c  om*/
public FifoProcedurePanel(String id, final FifoProcedure fifoProc) {

    super(id);

    final FifoProcedure fifoProcedure;

    if (fifoProc == null) {
        fifoProcedure = FifoProcedure.getInstance(controller.getActiveMandator(getSession()));
    } else {
        fifoProcedure = fifoProc;
    }

    CompoundPropertyModel<FifoProcedure> cpm = new CompoundPropertyModel<FifoProcedure>(fifoProcedure);
    final Form<Object> form = new Form<Object>("form");
    form.setDefaultModel(cpm);
    form.setOutputMarkupId(true);
    feedbackPanel.setOutputMarkupId(true);
    // add validators
    fifoName.setRequired(true);
    startDate.setRequired(true);
    endDate.setRequired(true);

    // get&add default values
    fifoName.setDefaultModel(cpm.bind("name"));
    startDate.setModelObject(fifoProcedure.getStartDate().getTime());
    endDate.setModelObject(fifoProcedure.getEndDate().getTime());
    //TODO Sprache:
    add(panelLabel.setDefaultModel(new Model<String>("Fifo-Prozedur bearbeiten")));

    form.add(fifoName);

    form.add(startDate);

    form.add(endDate);

    form.add(new AjaxButton("submit") {
        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) {

            Calendar sD = Calendar.getInstance();
            sD.setTime(startDate.getModelObject());

            Calendar eD = Calendar.getInstance();
            eD.setTime(endDate.getModelObject());

            try {
                fifoProcedure.setInterval(sD, eD);
                controller.writeFifoProcedure(fifoProcedure);
                //                    setResponsePage(new OnePanelPage(new ConfirmedEditPanel(OnePanelPage.getPanelIdOne())));
                //TODO Sprache:
                feedbackPanel.info("Eingaben \u00e4bernommen.");
                this.setVisible(false);

                target.addComponent(this);
                target.addComponent(feedbackPanel);
            } catch (IllegalArgumentException iae) {
                //TODO Sprache:
                feedbackPanel.fatal("Prozedur kann nicht bearbeitet werden.");
            }
        }
    });
    add(feedbackPanel);
    add(form);
}

From source file:org.apache.karaf.webconsole.core.form.MapEditForm.java

License:Apache License

public MapEditForm(String id, CompoundPropertyModel<Map<K, V>> model) {
    super(id, model);

    RepeatingView repeatingView = new RepeatingView("entries");

    for (K key : model.getObject().keySet()) {
        IModel<V> bind = model.bind("[" + key + "]");
        repeatingView.add(populateItem(repeatingView.newChildId(), key, bind));
    }//from  www . j  ava2 s  .com
    add(repeatingView);
}

From source file:org.apache.karaf.webconsole.osgi.log.OptionsForm.java

License:Apache License

@SuppressWarnings("serial")
public OptionsForm(String id, CompoundPropertyModel<Options> model) {
    super(id, model);

    IModel<Priority> priority = model.bind("priority");
    Select<Priority> select = new Select<Priority>("priority", priority);
    select.add(new SelectOptions<Priority>("options", Arrays.asList(Priority.values()),
            new IOptionRenderer<Priority>() {
                public String getDisplayValue(Priority object) {
                    return object.name();
                }/*ww w. j  a  va 2  s .c om*/

                public IModel<Priority> getModel(Priority value) {
                    return Model.of(value);
                }
            }));

    add(select);
    add(new TextField<Long>("dateFrom", Long.class));
    add(new TextField<Long>("dateTo", Long.class));
    add(new TextField<String>("messageFragment", String.class));
    add(new TextField<String>("bundleNameFragment", String.class));

    add(new SubmitLink("submit"));
}

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

License:Open Source License

/**
 * @param id/*from  ww  w  .  jav  a  2 s  .com*/
 * @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);

}