Example usage for org.apache.wicket.markup.html.form Form visitFormComponents

List of usage examples for org.apache.wicket.markup.html.form Form visitFormComponents

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.form Form visitFormComponents.

Prototype

public final <R> R visitFormComponents(final IVisitor<FormComponent<?>, R> visitor) 

Source Link

Document

Convenient and typesafe way to visit all the form components on a form.

Usage

From source file:com.francetelecom.clara.cloud.presentation.designer.EditServiceIT.java

License:Apache License

@Test
public void testEditShowsValues() {

    for (final LogicalService service : logicalDeployment.listLogicalServices()) {

        DeleteEditObjects.editServiceAtRow(myTester, GetObjectsUtils.getPositionForItem(myTester, service));

        myTester.assertVisible(NavigationUtils.designerParamFormPath);
        Form form = GetObjectsUtils.getParamsForm(myTester);
        form.visitFormComponents(new IVisitor<FormComponent, Void>() {
            @Override/*from   ww  w  .  jav a2 s .  c  om*/
            public void component(FormComponent formComponent, IVisit<Void> visit) {

                if (!(formComponent instanceof Button)) {
                    String name = ((FormComponent) formComponent).getInputName();
                    // We don't test complex fields, such as maven reference
                    // parameters
                    // Full Validation field don't need to be tested
                    if (!name.contains(".") && !name.equals("fullvalidationContent:fullvalidation")) {
                        try {
                            Field field = GetObjectsUtils.getAnyField(service.getClass(), name);
                            field.setAccessible(true);
                            if (field.get(service) != null) {
                                Assert.assertEquals(field.get(service).toString(),
                                        ((FormComponent) formComponent).getDefaultModelObject().toString());
                            }
                        } catch (NoSuchFieldException e) {
                            Assert.fail("field " + name + " could not be found");
                        } catch (IllegalAccessException e) {
                            Assert.fail("illegal access on " + name + " field");
                        }
                    }
                }
                visit.dontGoDeeper();
            }
        });

        NavigationUtils.submitParamsForm(myTester);
    }
}

From source file:com.francetelecom.clara.cloud.presentation.designer.EditServiceIT.java

License:Apache License

@Test
public void testEditReadOnly() {

    try {/*from  w  w w .  ja  v  a 2  s  .c  o  m*/
        ApplicationRelease release = manageApplicationRelease.findApplicationReleaseByUID(
                myTester.getLastRenderedPage().getPageParameters().get("releaseUid").toString());
        release.validate();
        release.lock();
        manageApplicationRelease.updateApplicationRelease(release);
    } catch (ObjectNotFoundException e) {
        Assert.fail("could not find application release with id "
                + myTester.getLastRenderedPage().getPageParameters().get("releaseUid").toString());
    }

    // go on designer step one page to access internal services
    NavigationUtils.goOnDesignerPage(myTester, releaseUid);
    myTester.assertRenderedPage(DesignerPage.class);
    for (final LogicalService service : logicalDeployment.listLogicalServices()) {
        // When: I try to edit the service

        int index = GetObjectsUtils.getPositionForItem(myTester, service);
        Assert.assertFalse("service not found in architecture matrix", -1 == index);
        myTester.assertVisible(NavigationUtils.getPathForCell(index, 0) + ":cell-view");
        DeleteEditObjects.viewServiceAtRow(myTester, index);
        myTester.assertVisible(NavigationUtils.modalPath);
        // Then: all displayed fields are read-only
        Form form = GetObjectsUtils.getModalParamsForm(myTester);

        form.visitFormComponents(new IVisitor<FormComponent, Void>() {
            @Override
            public void component(FormComponent formComponent, IVisit<Void> visit) {
                if (!(formComponent instanceof Button)) {
                    TagTester tagTester = myTester.getTagByWicketId(((FormComponent) formComponent).getId());
                    if (tagTester != null) {
                        Assert.assertNotNull(tagTester.getAttribute("disabled"));
                    }
                } else {
                    if ("addUpdateButton".equals(((Button) formComponent).getId())) {
                        Assert.assertFalse("add/update button should not be visible",
                                ((Button) formComponent).isVisible());
                    } else if ("cancelCloseButton".equals(((Button) formComponent).getId())) {
                        Label buttonLabel = (Label) ((FormComponent) formComponent).get("cancelLabel");
                        Assert.assertTrue("cancel/close button should display \"close\"",
                                "close".equals(buttonLabel.getDefaultModelObjectAsString()));
                    }
                }
                visit.dontGoDeeper();
            }
        });
    }
    for (final ProcessingNode node : logicalDeployment.listProcessingNodes()) {
        // When: I try to edit the node

        int index = GetObjectsUtils.getPositionForItem(myTester, node);
        Assert.assertFalse("node not found in architecture matrix", -1 == index);
        myTester.assertVisible(NavigationUtils.getPathForCell(0, index) + ":cell-view");
        DeleteEditObjects.viewNodeAtCol(myTester, index);
        myTester.assertVisible(NavigationUtils.modalPath);
        // Then: all displayed fields are read-only
        Form form = GetObjectsUtils.getModalParamsForm(myTester);
        form.visitFormComponents(new IVisitor<FormComponent, Void>() {
            @Override
            public void component(FormComponent object, IVisit<Void> visit) {
                if (!(object instanceof Button)) {
                    // Assert.assertFalse(((FormComponent)formComponent).getInputName()
                    // + " should be disabled",
                    // ((FormComponent)formComponent).isEnabled());
                }
                visit.dontGoDeeper();
            }
        });
    }
}

From source file:com.francetelecom.clara.cloud.presentation.designer.FieldConstraintsTest.java

License:Apache License

@Test
public void testPreviewFields() {

    // go on designer step one page to access internal services
    NavigationUtils.goOnDesignerPage(myTester, releaseUid);

    List<LogicalModelItem> externalItems = logicalServicesHelper.getExternalServices();

    for (LogicalModelItem item : externalItems) {
        // When: I ask add to add an external service
        final Class<? extends LogicalModelItem> serviceClass = item.getClass();
        if (!serviceClass.getAnnotation(GuiClassMapping.class).status()
                .equals(GuiClassMapping.StatusType.PREVIEW)) {

            CreateObjectsWithGUI.selectService(myTester, serviceClass);

            // Then: Preview fields have a default value
            // I'm prevented to change the default value for these fields
            Form form = GetObjectsUtils.getParamsForm(myTester);
            form.visitFormComponents(new IVisitor<FormComponent, Void>() {
                @Override//  w  w w . j av a 2  s.co m
                public void component(FormComponent formComponent, IVisit<Void> visit) {
                    if (!(formComponent instanceof Button)) {
                        String name = ((FormComponent) formComponent).getInputName();
                        // We don't test complex fields, such as maven reference parameters
                        if (!name.contains(".") && !name.equals("fullvalidationContent:fullvalidation")) {
                            try {
                                GuiMapping annotation = GetObjectsUtils.getAnyField(serviceClass, name)
                                        .getAnnotation(GuiMapping.class);
                                if (annotation.status().equals(GuiMapping.StatusType.READ_ONLY)) {
                                    TagTester tagTester = myTester
                                            .getTagByWicketId(((FormComponent) formComponent).getId());
                                    if (tagTester != null) {
                                        Assert.assertNotNull(tagTester.getAttribute("disabled"));
                                    }
                                    //                                        Assert.assertFalse("field " + name + " should be disabled", ((FormComponent) formComponent).isEnabled());
                                    Assert.assertTrue("field " + name + " should be have a default value",
                                            ((FormComponent) formComponent).getDefaultModelObject() != null);
                                }
                            } catch (NoSuchFieldException e) {
                                Assert.fail("field " + name + " not found for service " + serviceClass);
                            }
                        }
                    }
                    visit.dontGoDeeper();
                }
            });
        }
    }

    NavigationUtils.goOnNextStep(myTester);

    List<LogicalModelItem> internalItems = logicalServicesHelper.getInternalServices();

    for (LogicalModelItem item : internalItems) {
        // When: I ask add to add an external service
        final Class<? extends LogicalModelItem> serviceClass = item.getClass();
        if (!serviceClass.getAnnotation(GuiClassMapping.class).status()
                .equals(GuiClassMapping.StatusType.PREVIEW)) {

            CreateObjectsWithGUI.selectService(myTester, serviceClass);

            // Then: Preview fields have a default value
            // I'm prevented to change the default value for these fields
            Form form = GetObjectsUtils.getParamsForm(myTester);
            form.visitFormComponents(new IVisitor<FormComponent, Void>() {
                @Override
                public void component(FormComponent formComponent, IVisit<Void> visit) {
                    if (!(formComponent instanceof Button)) {
                        String name = ((FormComponent) formComponent).getInputName();
                        // We don't test complex fields, such as maven reference parameters
                        if (!name.contains(".") && !name.equals("fullvalidationContent:fullvalidation")) {
                            try {
                                GuiMapping annotation = GetObjectsUtils.getAnyField(serviceClass, name)
                                        .getAnnotation(GuiMapping.class);
                                if (annotation.status().equals(GuiMapping.StatusType.READ_ONLY)) {
                                    TagTester tagTester = myTester
                                            .getTagByWicketId(((FormComponent) formComponent).getId());

                                    if (tagTester != null) {
                                        Assert.assertNotNull(tagTester.getAttribute("disabled"));
                                    }
                                    Assert.assertTrue("field " + name + " should be have a default value",
                                            ((FormComponent) formComponent).getDefaultModelObject() != null);
                                }
                            } catch (NoSuchFieldException e) {
                                Assert.fail("field " + name + " not found for service " + serviceClass);
                            }
                        }
                    }
                    visit.dontGoDeeper();
                }
            });
        }
    }
}

From source file:com.przemo.projectmanagementweb.pages.TaskPage.java

private void disableTaskForm(Form form, IModel<Task> model) {
    form.visitFormComponents((Object t, IVisit ivisit) -> {
        if (t instanceof TextField || t instanceof TextArea) {
            ((Component) t).setEnabled(false);
        }//from   ww w  .  j ava 2s . com
    });
}

From source file:cz.zcu.kiv.eegdatabase.wui.components.utils.WicketUtils.java

License:Apache License

/**
 * Adds labels and feedback panels for input fields to the given form
 * The label ids are of the form <original id>.label
 * The feedback ids are of the form <original id>.feedback
 *
 * FormComponentPanel instances wont get a label or a feedback unless they
 * implement ISingleLabelFormComponentPanel interface.
 * If they do, their children dont get any labels or feedbacks.
 *
 * @param form//from ww  w . java2 s  . c o  m
 */
public static void addLabelsAndFeedback(Form<?> form) {
    final Set<String> ids = new HashSet<String>();
    final Map<String, MarkupContainer> parents = new HashMap<String, MarkupContainer>();
    final Map<String, ComponentFeedbackPanel> feedbacks = new HashMap<String, ComponentFeedbackPanel>();
    final Map<String, FormComponentLabel> labels = new HashMap<String, FormComponentLabel>();

    form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() {

        @Override
        public void component(FormComponent<?> object, IVisit<Void> visit) {
            if (object instanceof FormComponent && !(object instanceof Button)
                    && object.findParent(FormComponentPanel.class) == null) {
                ids.add(object.getId());
                parents.put(object.getId(), object.getParent());
                //create a feedback panel for the component
                ComponentFeedbackPanel temp = new ComponentFeedbackPanel(object.getId() + ".feedback", object);
                temp.setVisible(object.isVisible()); //do not display component if field is not visible
                feedbacks.put(object.getId(), temp);

                if (object.isRequired()) {
                    String lab = object.getLabel().getObject();
                    object.setLabel(new Model<String>(lab.concat("*")));
                }
                FormComponentLabel lab = new MyFormComponentLabel(object.getId() + ".label", object);
                lab.setVisible(object.isVisible());
                labels.put(object.getId(), lab);
            }
        }
    });

    for (String id : ids) {
        parents.get(id).addOrReplace(labels.get(id));
        parents.get(id).addOrReplace(feedbacks.get(id));
    }
}

From source file:guru.mmp.application.web.template.components.FormDialog.java

License:Apache License

/**
 * Constructs a new <code>FormDialog</code>.
 *
 * @param id         the non-null id of this component
 * @param title      the title for the form dialog
 * @param submitText the text to display on the "submit" button
 * @param cancelText the text to display on the "cancel" button
 *//*w w  w . j  ava 2s  . com*/
public FormDialog(String id, String title, String submitText, String cancelText) {
    super(id);

    this.title = title;
    this.submitText = submitText;
    this.cancelText = cancelText;

    Label titleLabel = new Label("title", new PropertyModel<String>(this, "title"));
    titleLabel.setRenderBodyOnly(true);
    add(titleLabel);

    alerts = new Alerts("alerts", id);
    add(alerts);

    form = new Form<>("form");
    add(form);

    AjaxButton submitButton = new AjaxButton("submitButton", form) {
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            super.onError(target, form);

            if (target != null) {
                // Visit each form component and if it is visible re-render it.
                // NOTE: We have to re-render every component to remove stale validation error messages.
                form.visitFormComponents((formComponent, iVisit) -> {
                    if ((formComponent.getParent() != null) && formComponent.getParent().isVisible()
                            && formComponent.isVisible()) {
                        target.add(formComponent);
                    }
                });
            }

            FormDialog.this.onError(target, FormDialog.this.getForm());
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (target != null) {
                resetFeedbackMessages(target);
            }

            if (FormDialog.this.onSubmit(target, FormDialog.this.getForm())) {
                hide(target);
            } else {
                target.add(getAlerts());
            }
        }
    };
    submitButton.setDefaultFormProcessing(true);
    add(submitButton);

    Label submitTextLabel = new Label("submitText", new PropertyModel<String>(this, "submitText"));
    submitTextLabel.setRenderBodyOnly(true);
    submitButton.add(submitTextLabel);

    AjaxLink cancelLink = new AjaxLink("cancelLink") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            FormDialog.this.onCancel(target, getForm());

            hide(target);
        }
    };
    add(cancelLink);

    Label cancelTextLabel = new Label("cancelText", new PropertyModel<String>(this, "cancelText"));
    cancelTextLabel.setRenderBodyOnly(true);
    cancelLink.add(cancelTextLabel);
}

From source file:org.webical.web.component.behavior.FormComponentValidationStyleBehavior.java

License:Open Source License

@Override
public void bind(Component component) {

    // Only visit children if we bind this behavior to a form
    if (component instanceof Form) {
        Form form = (Form) component;
        form.visitFormComponents(new FormComponent.AbstractVisitor() {
            @Override// w w  w  .j a v a  2s .  c  om
            protected void onFormComponent(FormComponent formComponent) {
                if (!(formComponent instanceof Button)) {
                    formComponent.add(new FormComponentValidationStyleBehavior());
                }
            }
        });
    }
}

From source file:org.wickedsource.wickedforms.wicket6.components.fields.AbstractInputFieldPanel.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void rerenderComponents(final AjaxRequestTarget target, Form form,
        final List<AbstractFormElementModel> changedModels) {
    form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() {
        @Override// www . j a  va 2  s.c  o  m
        public void component(FormComponent<?> component, IVisit<Void> visit) {
            String id = component.getMetaData(AbstractFormElementPanel.COMPONENT_ID_KEY);
            for (AbstractFormElementModel model : changedModels) {
                if (model.getId().equals(id)) {
                    if (model instanceof AbstractInputFieldModel) {
                        component.setEnabled(((AbstractInputFieldModel) model).isEnabled());
                    }
                    component.setVisible(model.isVisible());
                    target.add(component);
                }
            }
        }
    });
}

From source file:org.wickedsource.wickedforms.wicket6.components.fields.AbstractInputFieldPanel.java

License:Apache License

/**
 * Iterates through all form components within the given Wicket form and
 * writes the value of the form component into the Wicked Forms Model.
 * <p/>/*from  w  w w  .  jav  a  2  s.c om*/
 * TODO: the input is converted from raw input to objects somewhat manually
 * here, so that not all input field types are automatically supported,
 * which is bad. There must be a better way in which to let Wicket do the
 * dirty conversion work.
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private void updateUserInput(Form form, final List<AbstractInputFieldModel<?>> sourceFieldModels) {
    form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() {
        @Override
        public void component(FormComponent<?> component, IVisit<Void> visit) {
            String id = component.getMetaData(AbstractFormElementPanel.COMPONENT_ID_KEY);
            for (AbstractInputFieldModel model : sourceFieldModels) {
                if (model.getId().equals(id)) {
                    IConverter<?> converter;

                    if (component instanceof AbstractSingleSelectChoice) {
                        List choices = ((AbstractSingleSelectChoice) component).getChoices();
                        converter = new DefaultListChoiceConverter(choices);
                    } else {
                        converter = component.getConverter(model.getModelClass());
                    }

                    if (converter != null) {
                        Object convertedInput = converter.convertToObject(component.getInput(),
                                AbstractInputFieldPanel.this.getLocale());
                        model.setUserInput(convertedInput);
                    } else {
                        throw new RuntimeException(String.format(
                                "%s does not support type conversion that is necessary for supporting Wicked Forms actions!",
                                model.getClass().getName()));
                    }
                    visit.stop();
                }
            }
        }
    });
}

From source file:org.wicketstuff.mbeanview.panels.OperationsPanel.java

License:Apache License

private WebMarkupContainer newMethodCallButton(final String id, final MBeanOperationInfo operation) {
    final AjaxButton button = new IndicatingAjaxButton(id) {
        private static final long serialVersionUID = 1L;

        private Object[] collectParameters(final Form<?> form) {
            final SortedMap<Integer, Object> parameters = new TreeMap<Integer, Object>();
            form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() {
                @Override//from w  ww .j a  va2s .  c  o m
                public void component(final FormComponent<?> object, final IVisit<Void> visit) {
                    final Integer index = object.getMetaData(PARAMETER_INDEX);
                    if (index != null) {
                        assert !parameters.containsKey(index) : "Duplicate parameter index [" + index + "].";
                        parameters.put(index, object.getModelObject());
                    }
                }

            });

            return parameters.values().toArray();
        }

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final InvokeOperationEvent event = new InvokeOperationEvent(operation,
                    this.collectParameters(form));
            this.send(this, Broadcast.BUBBLE, event);

            final Object result;
            if (event.getException() != null) {
                operationOutput.setTitle(String.format("Problem invoking %s", operation.getName()));
                result = event.getException();
            } else {
                operationOutput.setTitle("Operation invoked successfully.");
                result = event.getResult();
            }

            final ClassInfo ci = ClassInfo.of(operation.getReturnType());
            operationOutput
                    .setContent(new ResultPanel(operationOutput.getContentId(), result, ci.getClassType()));
            operationOutput.show(target);
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            operationOutput.setContent(new FeedbackPanel(operationOutput.getContentId()));
            operationOutput.show(target);
        }

    };

    button.add(new Label("methodName", operation.getName()));
    return button;
}