/** tests timer behavior in a WebPage. */
  @Test
  public void addToWebPage() {
    Duration dur = Duration.seconds(20);
    final MyAjaxSelfUpdatingTimerBehavior timer = new MyAjaxSelfUpdatingTimerBehavior(dur);
    final MockPageWithLinkAndComponent page = new MockPageWithLinkAndComponent();
    Label label = new Label(MockPageWithLinkAndComponent.COMPONENT_ID, "Hello");
    page.add(label);
    page.add(
        new Link<Void>(MockPageWithLinkAndComponent.LINK_ID) {
          private static final long serialVersionUID = 1L;

          @Override
          public void onClick() {
            // do nothing, link is just used to simulate a roundtrip
          }
        });
    label.setOutputMarkupId(true);
    label.add(timer);

    tester.startPage(page);

    validate(timer, true);

    tester.clickLink(MockPageWithLinkAndComponent.LINK_ID);

    validate(timer, true);
  }
  public ContributionCommentSuccessPage(PageParameters parameters) {
    super(parameters);

    contributionId = parameters.getInt("contribution");

    boolean success =
        HibernateUtils.wrapTransaction(
            getHibernateSession(),
            new HibernateTask() {
              public boolean run(Session session) {
                contribution =
                    (Contribution)
                        session
                            .createQuery("select c from Contribution as c where c.id = :id")
                            .setInteger("id", contributionId)
                            .uniqueResult();
                return true;
              }
            });

    if (!success) {
      logger.info("unknown contribution of id " + contributionId);
      throw new RestartResponseAtInterceptPageException(NotFoundPage.class);
    }

    initializeLocation(getNavMenu().getLocationByKey("teacherIdeas"));

    add(
        new LocalizedText(
            "comment-header",
            "contribution.comment.success",
            new Object[] {HtmlUtils.encode(contribution.getTitle())}));

    add(
        new LocalizedText(
            "comment-success",
            "contribution.comment.successRedirection",
            new Object[] {
              ContributionPage.getLinker(contributionId).getHref(getPageContext(), getPhetCycle()),
              REDIRECTION_DELAY_SECONDS
            }));

    Label redirector = new Label("redirector", "");
    redirector.add(
        new AttributeModifier(
            "content",
            true,
            new Model<String>(
                REDIRECTION_DELAY_SECONDS
                    + ";url="
                    + ContributionPage.getLinker(contributionId)
                        .getRawUrl(getPageContext(), getPhetCycle()))));
    add(redirector);

    setTitle(
        StringUtils.messageFormat(
            PhetLocalizer.get().getString("contribution.comment.success", this),
            new Object[] {HtmlUtils.encode(contribution.getTitle())}));
  }
Beispiel #3
0
 /**
  * Return a component with a list of steps.
  *
  * @param model wizard model
  * @return a RepeatingView with step list
  */
 private RepeatingView getStepList(IWizardModel model) {
   Iterator<IWizardStep> it = model.stepIterator();
   RepeatingView view = new RepeatingView("repeater");
   while (it.hasNext()) {
     IWizardStep step = it.next();
     Label label = new Label(view.newChildId(), new PropertyModel<WizardStep>(step, "title"));
     if (step.equals(model.getActiveStep())) {
       label.add(new AttributeModifier("class", new Model<String>("selectedStep")));
     }
     view.add(label);
   }
   return view;
 }
  public ConfirmEmailLandingPanel(
      String id,
      PageContext context,
      PhetUser user,
      String destination,
      boolean wasPreviouslyConfirmed,
      boolean changedEmail) {
    super(id, context);

    if (changedEmail) {
      add(new LocalizedText("now-subscribed", "newsletter.emailChanged"));
      add(new InvisibleComponent("redirector"));
      add(new InvisibleComponent("now-registered"));
      destination = null;
      PhetSession.get().signOut();
    } else if (user.isNewsletterOnlyAccount() || wasPreviouslyConfirmed) {
      add(new LocalizedText("now-subscribed", "newsletter.nowSubscribed"));
      add(new InvisibleComponent("redirector"));
      add(new InvisibleComponent("now-registered"));
    } else {
      add(new InvisibleComponent("now-subscribed"));

      if (destination != null) {
        Label redirector = new Label("redirector", "");
        redirector.add(
            new AttributeModifier(
                "content",
                true,
                new Model<String>(REDIRECTION_DELAY_SECONDS + ";url=" + destination)));
        add(redirector);
      } else {
        add(new InvisibleComponent("redirector"));
      }

      add(new LocalizedText("now-registered", "newsletter.nowRegistered"));
    }

    if (destination != null) {
      add(new LocalizedText("redirection", "newsletter.redirection"));
    } else {
      add(new InvisibleComponent("redirection"));
    }
  }
 private static Label createRowSpanLabel(
     final String pId, final String pLabel, final AttributeModifier pRowSpan) {
   final Label ret = new Label(pId, pLabel);
   ret.add(pRowSpan);
   return ret;
 }
Beispiel #6
0
  @Override
  protected void onBeforeRender() {

    boolean showSave = false;
    String savePercent = "";
    final String lang = getLocale().getLanguage();

    BigDecimal priceToFormat = productPriceModel.getRegularPrice();
    String cssModificator = "regular";
    if (productPriceModel.getSalePrice() != null
        && MoneyUtils.isFirstBiggerThanSecond(
            productPriceModel.getRegularPrice(), productPriceModel.getSalePrice())) {
      priceToFormat = productPriceModel.getSalePrice();
      cssModificator = "sale";
      showSave = this.showSavings;
      if (showSave) {
        final BigDecimal save =
            MoneyUtils.getDiscountDisplayValue(
                productPriceModel.getRegularPrice(), productPriceModel.getSalePrice());
        savePercent = save.toString();
      }
    }
    final String[] formatted = getFormattedPrice(priceToFormat);

    addOrReplace(
        new Label(WHOLE_LABEL, formatted[0])
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_WHOLE)));
    addOrReplace(
        new Label(DOT_LABEL, ".")
            .setVisible(
                StringUtils.isNotBlank(formatted[0]) || StringUtils.isNotBlank(formatted[1]))
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_DOT)));
    addOrReplace(
        new Label(DECIMAL_LABEL, formatted[1])
            .setVisible(
                StringUtils.isNotBlank(formatted[0]) || StringUtils.isNotBlank(formatted[1]))
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_DECIMAL)));

    final Pair<String, Boolean> symbol =
        currencySymbolService.getCurrencySymbol(productPriceModel.getCurrency());

    addOrReplace(
        new Label(CURRENCY_LABEL, symbol.getFirst())
            .setVisible(showCurrencySymbol && !symbol.getSecond())
            .setEscapeModelStrings(false)
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_CURRENCY)));

    addOrReplace(
        new Label(CURRENCY2_LABEL, symbol.getFirst())
            .setVisible(showCurrencySymbol && symbol.getSecond())
            .setEscapeModelStrings(false)
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_CURRENCY)));

    final Map<String, Object> tax = new HashMap<String, Object>();
    if (this.showTaxAmount) {
      tax.put(
          "tax",
          this.productPriceModel.getPriceTax() != null
              ? this.productPriceModel.getPriceTax().toPlainString()
              : Total.ZERO.toPlainString());
    } else {
      tax.put(
          "tax",
          this.productPriceModel.getPriceTaxRate() != null
              ? this.productPriceModel.getPriceTaxRate().stripTrailingZeros().toPlainString() + "%"
              : "0%");
    }
    tax.put("code", this.productPriceModel.getPriceTaxCode());

    final String taxNote = this.showTaxNet ? "taxNoteNet" : "taxNoteGross";

    addOrReplace(
        new Label(TAX_LABEL, WicketUtil.createStringResourceModel(this, taxNote, tax))
            .setVisible(this.showTax)
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_TAX)));

    final Label discount =
        new Label(
            SAVE_LABEL,
            WicketUtil.createStringResourceModel(
                this,
                "savePercent",
                Collections.<String, Object>singletonMap("discount", savePercent)));

    discount.setVisible(showSave);
    discount.add(new AttributeModifier(HTML_CLASS, "sale-price-save"));

    if (showSave && StringUtils.isNotBlank(promos)) {

      final Map<String, ProductPromotionModel> promoModels =
          productServiceFacade.getPromotionModel(promos);

      final StringBuilder details = new StringBuilder();
      for (final ProductPromotionModel model : promoModels.values()) {

        final String name = model.getName().getValue(lang);
        final String desc = model.getDescription().getValue(lang);

        details.append(name);
        if (model.getCouponCode() != null) {
          details.append(" (").append(model.getCouponCode()).append(")");
        }

        if (StringUtils.isNotBlank(desc)) {
          details.append(": ").append(desc);
        }
        details.append("\n");
      }

      discount.add(new AttributeModifier("title", details.toString()));
    } else {
      discount.add(
          new AttributeModifier(
              "title", WicketUtil.createStringResourceModel(this, "savePercentTitle")));
    }

    addOrReplace(discount);

    addOrReplace(
        new Label(PROMO_LABEL, promos)
            .setVisible(StringUtils.isNotBlank(promos))
            .add(new AttributeModifier(HTML_CLASS, "sale-price-save sale-price-save-details")));

    super.onBeforeRender();
  }
Beispiel #7
0
  public HomePage() {
    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);
    add(hiddenContainersInfoPanel = new WebMarkupContainer("hiddenContainer"));
    hiddenContainersInfoPanel.setOutputMarkupId(true);
    hiddenContainersInfoPanel.add(new WebMarkupContainer(INFOPANEL));

    final GEventHandler closeClickHandler =
        new GEventHandler() {
          private static final long serialVersionUID = 1L;

          @Override
          public void onEvent(AjaxRequestTarget target) {
            info("InfoWindow " + infoWindow.getId() + " was closed");
            target.add(feedback);
          }
        };

    map = new GMap("bottomPanel");
    map.setOutputMarkupId(true);
    map.setMapType(GMapType.SATELLITE);
    map.setScrollWheelZoomEnabled(true);
    map.add(
        new ClickListener() {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onClick(AjaxRequestTarget target, GLatLng gLatLng) {
            if (gLatLng != null) {
              if (infoWindow != null) {
                infoWindow.close();
              }
              // Create the infoPanel
              Component c = new InfoPanel(INFOPANEL, i);
              i++;
              c.setOutputMarkupId(true);

              // Add or replace it on the hiddenContainer
              hiddenContainersInfoPanel.addOrReplace(c);

              infoWindow = new GInfoWindow(gLatLng, c);
              map.addOverlay(infoWindow);
              feedback.info("InfoWindow " + infoWindow.getId() + " was added");
              target.add(feedback);

              // add the hiddenContainer to be repainted
              target.add(hiddenContainersInfoPanel);
              // IMPORTANT: you must have the InfoWindow already added to the map
              // before you can add any listeners
              infoWindow.addListener(GEvent.closeclick, closeClickHandler);
            }
          }
        });

    add(map);

    lbInfoWindow = new Label("infoWindow", "openInfoWindow");
    lbInfoWindow.add(
        new AjaxEventBehavior("onclick") {
          private static final long serialVersionUID = 1L;

          /**
           * @see
           *     org.apache.wicket.ajax.AjaxEventBehavior#onEvent(org.apache.wicket.ajax.AjaxRequestTarget)
           */
          @Override
          protected void onEvent(AjaxRequestTarget target) {
            GInfoWindow tmpInfoWindow =
                new GInfoWindow(
                    new GLatLng(
                        37.5 * (0.9995 + Math.random() / 1000),
                        -122.1 * (0.9995 + Math.random() / 1000)),
                    "Opened via button");
            map.addOverlay(tmpInfoWindow);
            // IMPORTANT: you must have the InfoWindow already added to the map
            // before you can add any listeners
            GEventHandler closeClickHandler =
                new GEventHandler() {
                  private static final long serialVersionUID = 1L;

                  @Override
                  public void onEvent(AjaxRequestTarget target) {
                    feedback.info("InfoWindow which was opened via a button was closed");
                    target.add(feedback);
                  }
                };
            tmpInfoWindow.addListener(GEvent.closeclick, closeClickHandler);
            feedback.info("InfoWindow was opened via button");
            target.add(feedback);
          }
        });
    add(lbInfoWindow);
  }
 private Component thLabel(String id) {
   Label label = new Label(id, new ResourceModel(id));
   label.add(new AttributeModifier("title", new ResourceModel(id + ".title", "")));
   return label;
 }
  private void initLayout(final boolean oldPasswordVisible) {
    model = (LoadableModel<MyPasswordsDto>) getModel();

    Label oldPasswordLabel =
        new Label(
            ID_OLD_PASSWORD_LABEL, createStringResource("PageSelfCredentials.oldPasswordLabel"));
    add(oldPasswordLabel);
    oldPasswordLabel.add(
        new VisibleEnableBehaviour() {

          private static final long serialVersionUID = 1L;

          @Override
          public boolean isVisible() {
            return oldPasswordVisible;
          }
        });

    Label passwordLabel =
        new Label(ID_PASSWORD_LABEL, createStringResource("PageSelfCredentials.passwordLabel1"));
    add(passwordLabel);

    PasswordTextField oldPasswordField =
        new PasswordTextField(
            ID_OLD_PASSWORD_FIELD, new PropertyModel<String>(model, MyPasswordsDto.F_OLD_PASSWORD));
    oldPasswordField.setRequired(false);
    oldPasswordField.setResetPassword(false);
    add(oldPasswordField);
    oldPasswordField.add(
        new VisibleEnableBehaviour() {

          private static final long serialVersionUID = 1L;

          public boolean isVisible() {
            return oldPasswordVisible;
          };
        });

    PasswordPanel passwordPanel =
        new PasswordPanel(
            ID_PASSWORD_PANEL,
            new PropertyModel<ProtectedStringType>(model, MyPasswordsDto.F_PASSWORD));
    passwordPanel.getBaseFormComponent().add(new AttributeModifier("autofocus", ""));
    add(passwordPanel);

    WebMarkupContainer accountContainer = new WebMarkupContainer(ID_ACCOUNTS_CONTAINER);

    List<IColumn<PasswordAccountDto, String>> columns = initColumns();
    ListDataProvider<PasswordAccountDto> provider =
        new ListDataProvider<PasswordAccountDto>(
            this, new PropertyModel<List<PasswordAccountDto>>(model, MyPasswordsDto.F_ACCOUNTS));
    TablePanel accounts = new TablePanel(ID_ACCOUNTS_TABLE, provider, columns);
    accounts.setItemsPerPage(30);
    accounts.setShowPaging(false);
    if (model.getObject().getPropagation() != null
        && model
            .getObject()
            .getPropagation()
            .equals(CredentialsPropagationUserControlType.MAPPING)) {
      accountContainer.setVisible(false);
    }
    accountContainer.add(accounts);

    AjaxLink help =
        new AjaxLink(ID_BUTTON_HELP) {
          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(AjaxRequestTarget target) {
            showHelpPerformed(target);
          }
        };
    accountContainer.add(help);

    add(accountContainer);
  }
  private void initLayout(
      final IModel<String> label, final String labelSize, final String textSize) {

    Label l = new Label(ID_LABEL, label);
    l.setVisible(getLabelVisibility());
    if (StringUtils.isNotEmpty(labelSize)) {
      l.add(AttributeAppender.prepend("class", labelSize));
    }
    add(l);

    WebMarkupContainer addFirstContainer = new WebMarkupContainer(ID_ADD_FIRST_CONTAINER);
    addFirstContainer.setOutputMarkupId(true);
    addFirstContainer.setOutputMarkupPlaceholderTag(true);
    addFirstContainer.add(
        new VisibleEnableBehaviour() {

          @Override
          public boolean isVisible() {
            return getModelObject().isEmpty();
          }
        });
    add(addFirstContainer);

    AjaxLink addFirst =
        new AjaxLink(ID_ADD_FIRST) {

          @Override
          public void onClick(AjaxRequestTarget target) {
            addFirstPerformed(target);
          }
        };
    addFirstContainer.add(addFirst);

    ListView repeater =
        new ListView<T>(ID_REPEATER, getModel()) {

          @Override
          protected void populateItem(final ListItem<T> listItem) {
            WebMarkupContainer textWrapper = new WebMarkupContainer(ID_TEXT_WRAPPER);
            textWrapper.add(
                AttributeAppender.prepend(
                    "class",
                    new AbstractReadOnlyModel<String>() {

                      @Override
                      public String getObject() {
                        StringBuilder sb = new StringBuilder();
                        if (StringUtils.isNotEmpty(textSize)) {
                          sb.append(textSize).append(' ');
                        }
                        if (listItem.getIndex() > 0 && StringUtils.isNotEmpty(getOffsetClass())) {
                          sb.append(getOffsetClass()).append(' ');
                          sb.append(CLASS_MULTI_VALUE);
                        }
                        return sb.toString();
                      }
                    }));
            listItem.add(textWrapper);

            TextField text = new TextField<>(ID_TEXT, createTextModel(listItem.getModel()));
            text.add(
                new AjaxFormComponentUpdatingBehavior("blur") {
                  @Override
                  protected void onUpdate(AjaxRequestTarget ajaxRequestTarget) {}
                });
            text.setEnabled(false);
            text.add(AttributeAppender.replace("placeholder", label));
            text.setLabel(label);
            textWrapper.add(text);

            FeedbackPanel feedback =
                new FeedbackPanel(ID_FEEDBACK, new ComponentFeedbackMessageFilter(text));
            textWrapper.add(feedback);

            WebMarkupContainer buttonGroup = new WebMarkupContainer(ID_BUTTON_GROUP);
            buttonGroup.add(
                AttributeAppender.append(
                    "class",
                    new AbstractReadOnlyModel<String>() {

                      @Override
                      public String getObject() {
                        if (listItem.getIndex() > 0 && StringUtils.isNotEmpty(labelSize)) {
                          return CLASS_MULTI_VALUE;
                        }

                        return null;
                      }
                    }));

            AjaxLink edit =
                new AjaxLink(ID_EDIT) {

                  @Override
                  public void onClick(AjaxRequestTarget target) {
                    editValuePerformed(target, listItem.getModel());
                  }
                };
            textWrapper.add(edit);

            listItem.add(buttonGroup);

            initButtons(buttonGroup, listItem);
          }
        };

    add(repeater);
  }
Beispiel #11
0
  protected void initLayout() {
    final ValueModel valueModel = model.getObject();
    FieldDisplayType display = valueModel.getDefaultDisplay();

    // todo help
    Label label =
        new Label("label", new StringResourceModel(display.getLabel(), null, display.getLabel()));
    label.add(
        new AttributeModifier(
            "style",
            new AbstractReadOnlyModel<String>() {

              @Override
              public String getObject() {
                if (valueModel.getVisibleValueIndex() > 0) {
                  return "visibility: hidden;";
                }
                return null;
              }
            }));

    if (StringUtils.isNotEmpty(display.getTooltip())) {
      label.add(
          new AttributeModifier(
              "title", new StringResourceModel(display.getTooltip(), null, display.getTooltip())));
    }
    add(label);

    FieldToken fieldToken = valueModel.getField().getToken();
    UiWidget widget = initWidget(fieldToken.getWidget(), display.getProperty());
    add(widget);

    FeedbackPanel feedback = new FeedbackPanel("feedback");
    feedback.setFilter(new ComponentFeedbackMessageFilter(widget.getBaseFormComponent()));
    feedback.setOutputMarkupId(true);
    add(feedback);

    AjaxLink addButton =
        new AjaxLink("addButton") {

          @Override
          public void onClick(AjaxRequestTarget target) {
            addValue(target);
          }
        };
    addButton.add(
        new VisibleEnableBehaviour() {

          @Override
          public boolean isVisible() {
            return valueModel.isAddButtonVisible();
          }
        });
    add(addButton);

    AjaxLink removeButton =
        new AjaxLink("removeButton") {

          @Override
          public void onClick(AjaxRequestTarget target) {
            removeValue(target);
          }
        };
    removeButton.add(
        new VisibleEnableBehaviour() {

          @Override
          public boolean isVisible() {
            return valueModel.isRemoveButtonVisible();
          }
        });
    add(removeButton);
  }
  private void initLayout(final IModel<TaskDto> taskDtoModel) {

    WebMarkupContainer threadsConfigurationPanel =
        new WebMarkupContainer(ID_THREADS_CONFIGURATION_PANEL);
    add(threadsConfigurationPanel);

    threadsConfigurationPanel.add(
        new VisibleEnableBehaviour() {
          @Override
          public boolean isVisible() {
            return taskDtoModel.getObject().configuresWorkerThreads();
          }
        });

    final TextField<Integer> workerThreads =
        new TextField<>(
            ID_WORKER_THREADS, new PropertyModel<Integer>(taskDtoModel, TaskDto.F_WORKER_THREADS));
    workerThreads.setOutputMarkupId(true);
    workerThreads.add(
        new VisibleEnableBehaviour() {
          @Override
          public boolean isEnabled() {
            return parentPage.isEdit();
          }
        });
    threadsConfigurationPanel.add(workerThreads);

    VisibleEnableBehaviour hiddenWhenEditingOrNoSubtasks =
        new VisibleEnableBehaviour() {
          @Override
          public boolean isVisible() {
            return !parentPage.isEdit() && !taskDtoModel.getObject().getSubtasks().isEmpty();
          }
        };

    Label subtasksLabel =
        new Label(ID_SUBTASKS_LABEL, new ResourceModel("pageTaskEdit.subtasksLabel"));
    subtasksLabel.add(hiddenWhenEditingOrNoSubtasks);
    add(subtasksLabel);
    SubtasksPanel subtasksPanel =
        new SubtasksPanel(
            ID_SUBTASKS_PANEL,
            new PropertyModel<List<TaskDto>>(taskDtoModel, TaskDto.F_SUBTASKS),
            parentPage.getWorkflowManager().isEnabled());
    subtasksPanel.add(hiddenWhenEditingOrNoSubtasks);
    add(subtasksPanel);

    VisibleEnableBehaviour hiddenWhenNoSubtasks =
        new VisibleEnableBehaviour() {
          @Override
          public boolean isVisible() {
            TaskDto taskDto = taskDtoModel.getObject();
            return taskDto != null && !taskDto.getTransientSubtasks().isEmpty();
          }
        };

    Label workerThreadsTableLabel =
        new Label(ID_WORKER_THREADS_TABLE_LABEL, new ResourceModel("TaskStatePanel.workerThreads"));
    workerThreadsTableLabel.add(hiddenWhenNoSubtasks);
    add(workerThreadsTableLabel);
    List<IColumn<WorkerThreadDto, String>> columns = new ArrayList<>();
    columns.add(
        new PropertyColumn(
            createStringResourceStatic(this, "TaskStatePanel.subtaskName"),
            WorkerThreadDto.F_NAME));
    columns.add(
        new EnumPropertyColumn<WorkerThreadDto>(
            createStringResourceStatic(this, "TaskStatePanel.subtaskState"),
            WorkerThreadDto.F_EXECUTION_STATUS));
    columns.add(
        new PropertyColumn(
            createStringResourceStatic(this, "TaskStatePanel.subtaskObjectsProcessed"),
            WorkerThreadDto.F_PROGRESS));
    ISortableDataProvider<WorkerThreadDto, String> threadsProvider =
        new ListDataProvider<>(
            this,
            new AbstractReadOnlyModel<List<WorkerThreadDto>>() {
              @Override
              public List<WorkerThreadDto> getObject() {
                List<WorkerThreadDto> rv = new ArrayList<>();
                TaskDto taskDto = taskDtoModel.getObject();
                if (taskDto != null) {
                  for (TaskDto subtaskDto : taskDto.getTransientSubtasks()) {
                    rv.add(new WorkerThreadDto(subtaskDto));
                  }
                }
                return rv;
              }
            });
    TablePanel<WorkerThreadDto> workerThreadsTablePanel =
        new TablePanel<>(ID_WORKER_THREADS_TABLE, threadsProvider, columns);
    workerThreadsTablePanel.add(hiddenWhenNoSubtasks);
    add(workerThreadsTablePanel);
  }
  /**
   * Validates the response, then makes sure the timer injects itself again when called. Tests
   * {@link AbstractAjaxTimerBehavior#restart(AjaxRequestTarget)} method
   *
   * <p>WICKET-1525, WICKET-2152
   */
  public void testRestartMethod() {
    final Integer labelInitialValue = Integer.valueOf(0);

    final Label label =
        new Label(MockPageWithLinkAndComponent.COMPONENT_ID, new Model<Integer>(labelInitialValue));

    // the duration doesn't matter because we manually trigger the behavior
    final AbstractAjaxTimerBehavior timerBehavior =
        new AbstractAjaxTimerBehavior(Duration.seconds(2)) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onTimer(AjaxRequestTarget target) {
            // increment the label's model object
            label.setDefaultModelObject(((Integer) label.getDefaultModelObject()) + 1);
            target.add(label);
          }
        };

    final MockPageWithLinkAndComponent page = new MockPageWithLinkAndComponent();
    page.add(label);
    page.add(
        new AjaxLink<Void>(MockPageWithLinkAndComponent.LINK_ID) {
          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(AjaxRequestTarget target) {
            if (timerBehavior.isStopped()) {
              timerBehavior.restart(target);
            } else {
              timerBehavior.stop(target);
            }
          }
        });

    label.setOutputMarkupId(true);
    label.add(timerBehavior);

    tester.startPage(page);

    final String labelPath = MockPageWithLinkAndComponent.COMPONENT_ID;

    // assert label == initial value (i.e. 0)
    tester.assertLabel(labelPath, String.valueOf(labelInitialValue));

    // increment to 1
    tester.executeBehavior(timerBehavior);

    // assert label == 1
    tester.assertLabel(labelPath, String.valueOf(labelInitialValue + 1));

    // stop the timer
    tester.clickLink(MockPageWithLinkAndComponent.LINK_ID);

    // trigger it, but it is stopped
    tester.executeBehavior(timerBehavior);

    // assert label is still 1
    tester.assertLabel(labelPath, String.valueOf(labelInitialValue + 1));

    // restart the timer
    tester.clickLink(MockPageWithLinkAndComponent.LINK_ID);

    // increment to 2
    tester.executeBehavior(timerBehavior);

    // assert label is now 2
    tester.assertLabel(labelPath, String.valueOf(labelInitialValue + 2));
  }