Ejemplo n.º 1
0
  private void initLayout(
      IModel<String> label, Form form, String valueCssClass, String inputCssClass) {
    // container
    WebMarkupContainer valueContainer = new WebMarkupContainer(ID_VALUE_CONTAINER);
    valueContainer.setOutputMarkupId(true);
    valueContainer.add(new AttributeModifier("class", valueCssClass));
    add(valueContainer);

    // feedback
    FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK);
    feedback.setOutputMarkupId(true);
    add(feedback);

    // input
    Panel input = createInputComponent(ID_INPUT, label, form);
    input.add(new AttributeModifier("class", inputCssClass));
    if (input instanceof InputPanel) {
      initAccessBehaviour((InputPanel) input);
      feedback.setFilter(
          new ComponentFeedbackMessageFilter(((InputPanel) input).getBaseFormComponent()));
    }
    valueContainer.add(input);

    // buttons
    AjaxLink addButton =
        new AjaxLink("addButton") {

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

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

    AjaxLink removeButton =
        new AjaxLink("removeButton") {

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

          @Override
          public boolean isVisible() {
            return isRemoveButtonVisible();
          }
        });
    valueContainer.add(removeButton);
  }
  public AjaxDropDownPage() {
    Form<Void> form = new Form<Void>("form");
    this.add(form);

    // FeedbackPanel //
    final FeedbackPanel feedback = new JQueryFeedbackPanel("feedback");
    form.add(feedback.setOutputMarkupId(true));

    // ComboBox //
    final DropDownList<String> dropdown =
        new AjaxDropDownList<String>("select", new Model<String>(), new ListModel<String>(GENRES)) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSelectionChanged(AjaxRequestTarget target, Form<?> form) {
            String choice = this.getModelObject();

            this.info(choice != null ? choice : "no choice");
            target.add(feedback);
          }
        };

    form.add(dropdown);
  }
  public EntitlementPurchaseModalPanel(
      CustomModalWindow purchaseTransactionModal, EntitlementLookup entilement) {
    super(purchaseTransactionModal.getContentId());
    this.purchaseTransactionWindow = purchaseTransactionModal;

    final Form<Object> purchaseHistoryForm = new Form<Object>("purchaseHistoryForm");
    purchaseHistoryForm.setOutputMarkupPlaceholderTag(true);
    add(purchaseHistoryForm);

    final FeedbackMessageFilter filter = new FeedbackMessageFilter("PurchaseHistory");
    filter.setAcceptAllUnspecifiedComponents(false);
    filter.addFilterInComponent(purchaseHistoryForm);

    final FeedbackPanel purchaseHistoryFeedback =
        new FeedbackPanel("purchaseHistoryFeedback", filter);
    purchaseHistoryFeedback.setOutputMarkupPlaceholderTag(true);
    add(purchaseHistoryFeedback);

    purchaseHistoryForm.add(
        new PurchaseHistoryTabPanel(
            "gspPurchaseHistoryTabPanel",
            purchaseHistoryFeedback,
            purchaseHistoryForm,
            filter,
            TabId.ALL));

    PurchaseSelectTabPanel purchaseSelectTabPanel =
        new PurchaseSelectTabPanel("purchaseSelectTabPanel", entilement);
    purchaseHistoryForm.add(purchaseSelectTabPanel);
  }
Ejemplo n.º 4
0
  private void initialize() {
    final Form<Void> form = new Form<Void>("form");
    this.add(form);

    // FeedbackPanel //
    final FeedbackPanel feedback = new JQueryFeedbackPanel("feedback");
    form.add(feedback.setOutputMarkupId(true));

    // Sliders //
    final Label label =
        new Label("label", this.model); // the supplied model allows the initial display
    form.add(label);

    form.add(
        new AjaxSlider("slider", this.model, label) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onValueChanged(IPartialPageRequestHandler handler) {
            AjaxSliderPage.this.info(this);
            handler.add(feedback); // do never add 'this' or the form here!
          }
        });
  }
Ejemplo n.º 5
0
  /** Constructor */
  public RadioChoicePage() {
    final Input input = new Input();
    setDefaultModel(new CompoundPropertyModel<Input>(input));

    // Add a FeedbackPanel for displaying our messages
    final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupId(true);
    add(feedbackPanel);

    // Add a form with an onSumbit implementation that sets a message
    Form<?> form =
        new Form("form") {
          @Override
          protected void onSubmit() {
            info("input: " + input);
          }
        };
    add(form);

    // Add a radio choice component that uses Input's 'site' property to
    // designate the
    // current selection, and that uses the SITES list for the available
    // options.
    RadioChoice<String> sites = new RadioChoice<String>("site", SITES);
    sites.add(
        new AjaxFormChoiceComponentUpdatingBehavior() {
          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            info("Selected: " + getComponent().getDefaultModelObjectAsString());
            target.add(feedbackPanel);
          }
        });
    form.add(sites);
  }
  private void initialize() {
    // FeedbackPanel //
    final FeedbackPanel feedback = new JQueryFeedbackPanel("feedback");
    this.add(feedback.setOutputMarkupId(true));

    // EventObjects //
    RepeatingView view = new RepeatingView("object");
    this.add(view);

    for (MyEvent event : this.objects) {
      view.add(
          new EventObject(view.newChildId(), event.toString()) {

            private static final long serialVersionUID = 1L;

            @Override
            public void onConfigure(JQueryBehavior behavior) {
              super.onConfigure(behavior);

              // draggable options //
              behavior.setOption("revert", true);
              behavior.setOption("revertDuration", 0);
            }
          });
    }

    // Calendar //
    this.add(
        new Calendar("calendar", this.newCalendarModel(), new Options("theme", true)) {

          private static final long serialVersionUID = 1L;

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

          @Override
          public void onObjectDrop(
              AjaxRequestTarget target, String title, LocalDateTime date, boolean allDay) {
            CalendarEvent event = new CalendarEvent(0, title, date);
            event.setAllDay(allDay);

            events.add(event); // adds to DAO
            this.refresh(target);

            this.info(String.format("Added %s on %s", event.getTitle(), event.getStart()));
            target.add(feedback);
          }
        });
  }
Ejemplo n.º 7
0
  private void initialize(String titleKey) {
    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);

    Label titleLabel = new Label("pageTitle", getString(titleKey, null, titleKey));
    titleLabel.setRenderBodyOnly(true);
    add(titleLabel);

    Link<Object> plLangLink =
        new Link<Object>("plLang") {
          private static final long serialVersionUID = 3288754396147822387L;

          @Override
          public void onClick() {
            getSession().setLocale(new Locale("pl", "pl_PL"));
            setResponsePage(getPage().getClass());
          }
        };
    add(plLangLink);

    Link<Object> enLangLink =
        new Link<Object>("enLang") {
          private static final long serialVersionUID = 4601930920670566466L;

          @Override
          public void onClick() {
            getSession().setLocale(Locale.ENGLISH);
            setResponsePage(getPage().getClass());
          }
        };
    add(enLangLink);

    ((Application) getApplication()).getMenuLoader().addMenuPanel(BasePage.this);
  }
Ejemplo n.º 8
0
  public ImageUploadContentPanel(String pId, String customUploadFolderPath) {
    super(pId);
    setOutputMarkupId(true);
    this.uploadFolderPath = customUploadFolderPath;
    Form<?> form = new Form<Void>("form");
    final FeedbackPanel feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    form.add(feedback);
    final FileUploadField fileUploadField = new FileUploadField("file");
    fileUploadField.setLabel(new ResourceModel("required.label"));
    fileUploadField.setRequired(true);
    fileUploadField.add(FILE_EXTENSION_VALIDATOR);
    form.add(fileUploadField);
    form.add(
        new AjaxButton("uploadButton", form) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget pTarget, Form<?> pForm) {
            FileUpload fileUpload = fileUploadField.getFileUpload();
            String fileName = fileUpload.getClientFileName();
            try {
              File currentEngineerDir = new File(uploadFolderPath);
              if (!currentEngineerDir.exists()) {
                currentEngineerDir.mkdir();
              }
              fileUpload.writeTo(new File(currentEngineerDir, fileName));
            } catch (Exception ex) {
              log.error("Can't upload attachment: " + ex.getMessage(), ex);
              ImageUploadContentPanel.this.error("Can't upload attachment");
              pTarget.add(feedback);
              return;
            } finally {
              fileUpload.closeStreams();
            }
            ImageFileDescription imageFileDescription = new ImageFileDescription(fileName);
            imageFileDescription.setContentType(fileUpload.getContentType());
            onImageUploaded(imageFileDescription, pTarget);
          }

          @Override
          protected void onError(AjaxRequestTarget pTarget, Form<?> pForm) {
            pTarget.add(feedback);
          }
        });
    add(form);
  }
Ejemplo n.º 9
0
  /** Constructor */
  public FormPage() {
    // create feedback panel to show errors
    final FeedbackPanel feedbackErrors =
        new FeedbackPanel(
            "feedbackErrors", new ExactLevelFeedbackMessageFilter(FeedbackMessage.ERROR));
    feedbackErrors.setOutputMarkupId(true);
    add(feedbackErrors);

    // create feedback panel to show info message
    final FeedbackPanel feedbackSuccess =
        new FeedbackPanel(
            "feedbackSuccess", new ExactLevelFeedbackMessageFilter(FeedbackMessage.INFO));
    feedbackSuccess.setOutputMarkupId(true);
    add(feedbackSuccess);

    // add form with markup id setter so it can be updated via ajax
    addInstantValidationForm();

    addPreventEnterSubmitForm();
  }
  public DefaultComboBoxPage() {
    Form<Void> form = new Form<Void>("form");
    this.add(form);

    // FeedbackPanel //
    final FeedbackPanel feedbackPanel = new JQueryFeedbackPanel("feedback");
    form.add(feedbackPanel.setOutputMarkupId(true));

    // ComboBox //
    final ComboBox<String> dropdown =
        new ComboBox<String>(
            "combobox",
            new Model<String>(),
            GENRES); // new WildcardListModel(GENRES) can be used (but not ListModel)
    form.add(dropdown);

    // Buttons //
    form.add(
        new Button("submit") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            DefaultComboBoxPage.this.info(dropdown);
          }
        });

    form.add(
        new AjaxButton("button") {

          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            DefaultComboBoxPage.this.info(dropdown);
            target.add(feedbackPanel);
          }
        });
  }
Ejemplo n.º 11
0
  @Override
  public void delete(IModel<Preference>[] fields) {
    FeedbackPanel feed = (FeedbackPanel) getPage().get("feedback");

    try {
      PortletRegistry registry =
          ((AbstractAdminWebApplication) getApplication()).getServiceLocator().getPortletRegistry();
      PortletApplication app = registry.getPortletApplication(paNodeBean.getApplicationName());
      PortletDefinition def = PortletApplicationUtils.getPortletOrClone(app, paNodeBean.getName());
      PortletPreferencesProvider prefProvider =
          (PortletPreferencesProvider)
              ((AbstractAdminWebApplication) getApplication())
                  .getServiceLocator()
                  .getService(CommonPortletServices.CPS_PORTLET_PREFERENCES_PROVIDER);

      for (IModel<Preference> field : fields) {
        prefProvider.removeDefaults(def, field.getObject().getName());
      }

      StringResourceModel resModel =
          new StringResourceModel(
              "pam.details.action.status.portlet.saveOK",
              this,
              null,
              new Object[] {paNodeBean.getName()});
      feed.info(resModel.getString());
    } catch (Exception e) {
      logger.error("Failed to remove portlet default preference.", e);
      StringResourceModel resModel =
          new StringResourceModel(
              "pam.details.action.status.portlet.saveFailure",
              this,
              null,
              new Object[] {paNodeBean.getName(), e.getMessage()});
      feed.info(resModel.getString());
    }
  }
 @Override
 protected void onInitialize() {
   super.onInitialize();
   Form<Document> form = new Form<Document>("form");
   form.add(getNumberTextfield());
   form.add(getDesignationTextfield().setRequired(true));
   form.add(getStatusChoice());
   form.add(getDocumentDateDatefield());
   form.add(getClientCompleteComponent());
   form.add(saveLink());
   feedbackpanel = new FeedbackPanel("feedback");
   add(feedbackpanel.setOutputMarkupId(true));
   add(new Label("salvation", documentModel.getDocument().getDocumentType().getDesignation()));
   add(form);
 }
Ejemplo n.º 13
0
  private void setupUserInterfaceFields() {

    form = new Form("form");
    form.setOutputMarkupId(true);
    add(form);
    setMarkupContainer(form);

    addTextField("categoryID", new PropertyModel<String>(this, "categoryNew.categoryID"));
    addTextField("name", new PropertyModel<String>(this, "categoryNew.name"));
    addCheckboxField(
        "promiseCategory", new PropertyModel<Boolean>(this, "categoryNew.promiseCategory"));
    addCheckboxField(
        "belongsToGroup1", new PropertyModel<Boolean>(this, "categoryNew.belongsToGroup1"));
    addCheckboxField(
        "belongsToGroup2", new PropertyModel<Boolean>(this, "categoryNew.belongsToGroup2"));

    add(feedbackPanel = new BootstrapFeedbackPanel("feedbackPanel"));
    feedbackPanel.setOutputMarkupId(true);
  }
Ejemplo n.º 14
0
  public HomePage(final PageParameters parameters) {
    super(parameters);

    feedbackPanel = new FeedbackPanel("feedBack");
    feedbackPanel.setOutputMarkupPlaceholderTag(true);

    add(feedbackPanel);

    add(
        new EditableGrid<Person, String>(
            "grid",
            getColumns(),
            new EditableListDataProvider<Person, String>(getPersons()),
            5,
            Person.class) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onError(AjaxRequestTarget target) {
            target.add(feedbackPanel);
          }

          @Override
          protected void onCancel(AjaxRequestTarget target) {
            target.add(feedbackPanel);
          }

          @Override
          protected void onDelete(AjaxRequestTarget target, IModel<Person> rowModel) {
            target.add(feedbackPanel);
          }

          @Override
          protected void onSave(AjaxRequestTarget target, IModel<Person> rowModel) {
            target.add(feedbackPanel);
          }
        });
  }
Ejemplo n.º 15
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);
  }
Ejemplo n.º 16
0
  public AdminPatientPage(PageParameters parameters) {
    super();

    final Patient patient;
    final PatientUser patientUser;

    StringValue idValue = parameters.get(PARAM_ID);
    patientUser = userManager.getPatientUser(idValue.toLong());
    patient = patientManager.getPatientByRadarNumber(patientUser.getRadarNumber());

    CompoundPropertyModel<PatientUser> patientUserModel =
        new CompoundPropertyModel<PatientUser>(patientUser);

    final FeedbackPanel feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    feedback.setOutputMarkupPlaceholderTag(true);
    add(feedback);

    final Form<PatientUser> userForm =
        new Form<PatientUser>("patientForm", patientUserModel) {
          protected void onSubmit() {
            try {
              userManager.savePatientUser(getModelObject());
            } catch (Exception e) {
              error("Could not save patient: " + e.toString());
            }
          }
        };
    add(userForm);

    userForm.add(new Label("radarNo", patientUser.getRadarNumber().toString()));
    userForm.add(new Label("forename", patient.getForename()));
    userForm.add(new Label("surname", patient.getSurname()));
    userForm.add(new RequiredTextField("username"));
    userForm.add(new Label("dob", patientUser.getDateOfBirth().toString()));
    userForm.add(new Label("dateRegistered", patientUser.getDateRegistered().toString()));

    userForm.add(
        new AjaxSubmitLink("updateTop") {
          protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            setResponsePage(AdminPatientsPage.class);
          }

          protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(feedback);
          }
        });

    userForm.add(
        new AjaxLink("cancelTop") {
          public void onClick(AjaxRequestTarget ajaxRequestTarget) {
            setResponsePage(AdminPatientsPage.class);
          }
        });

    userForm.add(
        new AjaxSubmitLink("updateBottom") {
          protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            setResponsePage(AdminPatientsPage.class);
          }

          protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(feedback);
          }
        });

    userForm.add(
        new AjaxLink("cancelBottom") {
          public void onClick(AjaxRequestTarget ajaxRequestTarget) {
            setResponsePage(AdminPatientsPage.class);
          }
        });
  }
Ejemplo n.º 17
0
    public BookNewCargoForm() {
      List<String> locations = new CommonQueries().unLocodes();

      final FeedbackPanel feedback = new FeedbackPanel("feedback");
      add(feedback.setOutputMarkupId(true));

      final SelectorInForm originSelector =
          new SelectorInForm("origin", "Origin", locations, this, "destination");
      originSelector.setRequired(true);

      final ComponentFeedbackPanel originFeedback =
          new ComponentFeedbackPanel("originFeedback", originSelector);
      add(originFeedback.setOutputMarkupId(true));

      final SelectorInForm destinationSelector =
          new SelectorInForm("destination", "Destinatin", locations, this, "origin");
      destinationSelector.setRequired(true);

      final ComponentFeedbackPanel destinationFeedback =
          new ComponentFeedbackPanel("destinationFeedback", destinationSelector);
      add(destinationFeedback.setOutputMarkupId(true));

      // Disable equal locations
      originSelector.add(
          new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
              // Exclude origin in destination drop down
              target.add(originSelector, originFeedback, destinationSelector);
              focusFirstError(target);
            }
          });

      destinationSelector.add(
          new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
              // Exclude destination in origin drop down
              target.add(destinationSelector, destinationFeedback, originSelector);
              focusFirstError(target);
            }
          });

      // Deadline
      final DateTextFieldWithPicker deadlineField =
          new DateTextFieldWithPicker("deadline", "Arrival deadline", this);
      deadlineField.earliestDate(new LocalDate().plusDays(1));

      final ComponentFeedbackPanel deadlineFeedback =
          new ComponentFeedbackPanel("deadlineFeedback", deadlineField);
      add(deadlineFeedback.setOutputMarkupId(true));

      add(originSelector, destinationSelector, deadlineField);

      add(
          new AjaxFallbackButton("book", this) {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
              try {
                // Perform use case
                TrackingId trackingId = new BookNewCargo(origin, destination, deadline).book();

                // Add new tracking id to list in session
                PrevNext.addId(Session.get(), trackingId.id().get());

                // Show created cargo
                setResponsePage(
                    CargoDetailsPage.class, new PageParameters().set(0, trackingId.id().get()));
              } catch (Exception e) {
                logger.warn("Problem booking a new cargo: " + e.getMessage());
                feedback.error(e.getMessage());
                target.add(feedback);
              }
            }

            @Override
            protected void onError(final AjaxRequestTarget target, Form<?> form) {
              target.add(originFeedback, destinationFeedback, deadlineFeedback);
              focusFirstError(target);
            }
          });
    }
Ejemplo n.º 18
0
  @SuppressWarnings("serial")
  public GeoServerBasePage() {
    // lookup for a pluggable favicon
    PackageResourceReference faviconReference = null;
    List<HeaderContribution> cssContribs =
        getGeoServerApplication().getBeansOfType(HeaderContribution.class);
    for (HeaderContribution csscontrib : cssContribs) {
      try {
        if (csscontrib.appliesTo(this)) {
          PackageResourceReference ref = csscontrib.getFavicon();
          if (ref != null) {
            faviconReference = ref;
          }
        }
      } catch (Throwable t) {
        LOGGER.log(Level.WARNING, "Problem adding header contribution", t);
      }
    }

    // favicon
    if (faviconReference == null) {
      faviconReference = new PackageResourceReference(GeoServerBasePage.class, "favicon.ico");
    }
    String faviconUrl = RequestCycle.get().urlFor(faviconReference, null).toString();
    add(new ExternalLink("faviconLink", faviconUrl, null));

    // page title
    add(
        new Label(
            "pageTitle",
            new LoadableDetachableModel<String>() {

              @Override
              protected String load() {
                return getPageTitle();
              }
            }));

    // login form
    WebMarkupContainer loginForm =
        new WebMarkupContainer("loginform") {
          protected void onComponentTag(org.apache.wicket.markup.ComponentTag tag) {
            String path = getRequest().getUrl().getPath();
            StringBuilder loginPath = new StringBuilder();
            if (path.isEmpty()) {
              // home page
              loginPath.append("../j_spring_security_check");
            } else {
              // boomarkable page of sorts
              String[] pathElements = path.split("/");
              for (String pathElement : pathElements) {
                if (!pathElement.isEmpty()) {
                  loginPath.append("../");
                }
              }
              loginPath.append("j_spring_security_check");
            }
            tag.put("action", loginPath);
          };
        };
    add(loginForm);
    final Authentication user = GeoServerSession.get().getAuthentication();
    final boolean anonymous = user == null || user instanceof AnonymousAuthenticationToken;
    loginForm.setVisible(anonymous);

    WebMarkupContainer logoutForm = new WebMarkupContainer("logoutform");
    logoutForm.setVisible(!anonymous);

    add(logoutForm);
    logoutForm.add(new Label("username", anonymous ? "Nobody" : user.getName()));

    // home page link
    add(
        new BookmarkablePageLink("home", GeoServerHomePage.class)
            .add(new Label("label", new StringResourceModel("home", (Component) null, null))));

    // dev buttons
    DeveloperToolbar devToolbar = new DeveloperToolbar("devButtons");
    add(devToolbar);
    devToolbar.setVisible(
        RuntimeConfigurationType.DEVELOPMENT.equals(getApplication().getConfigurationType()));

    final Map<Category, List<MenuPageInfo>> links =
        splitByCategory(filterByAuth(getGeoServerApplication().getBeansOfType(MenuPageInfo.class)));

    List<MenuPageInfo> standalone =
        links.containsKey(null) ? links.get(null) : new ArrayList<MenuPageInfo>();
    links.remove(null);

    List<Category> categories = new ArrayList<>(links.keySet());
    Collections.sort(categories);

    add(
        new ListView<Category>("category", categories) {
          public void populateItem(ListItem<Category> item) {
            Category category = item.getModelObject();
            item.add(
                new Label(
                    "category.header",
                    new StringResourceModel(category.getNameKey(), (Component) null, null)));
            item.add(
                new ListView<MenuPageInfo>("category.links", links.get(category)) {
                  public void populateItem(ListItem<MenuPageInfo> item) {
                    MenuPageInfo info = item.getModelObject();
                    BookmarkablePageLink<Page> link =
                        new BookmarkablePageLink<>("link", info.getComponentClass());
                    link.add(
                        AttributeModifier.replace(
                            "title",
                            new StringResourceModel(
                                info.getDescriptionKey(), (Component) null, null)));
                    link.add(
                        new Label(
                            "link.label",
                            new StringResourceModel(info.getTitleKey(), (Component) null, null)));
                    Image image;
                    if (info.getIcon() != null) {
                      image =
                          new Image(
                              "link.icon",
                              new PackageResourceReference(
                                  info.getComponentClass(), info.getIcon()));
                    } else {
                      image =
                          new Image(
                              "link.icon",
                              new PackageResourceReference(
                                  GeoServerBasePage.class, "img/icons/silk/wrench.png"));
                    }
                    image.add(
                        AttributeModifier.replace(
                            "alt", new ParamResourceModel(info.getTitleKey(), null)));
                    link.add(image);
                    item.add(link);
                  }
                });
          }
        });

    add(
        new ListView<MenuPageInfo>("standalone", standalone) {
          public void populateItem(ListItem<MenuPageInfo> item) {
            MenuPageInfo info = item.getModelObject();
            BookmarkablePageLink<Page> link =
                new BookmarkablePageLink<>("link", info.getComponentClass());
            link.add(
                AttributeModifier.replace(
                    "title",
                    new StringResourceModel(info.getDescriptionKey(), (Component) null, null)));
            link.add(
                new Label(
                    "link.label",
                    new StringResourceModel(info.getTitleKey(), (Component) null, null)));
            item.add(link);
          }
        });

    add(feedbackPanel = new FeedbackPanel("feedback"));
    feedbackPanel.setOutputMarkupId(true);

    // ajax feedback image
    add(
        new Image(
            "ajaxFeedbackImage",
            new PackageResourceReference(GeoServerBasePage.class, "img/ajax-loader.gif")));

    add(new WebMarkupContainer(HEADER_PANEL));

    // allow the subclasses to initialize before getTitle/getDescription are called
    add(
        new Label(
            "gbpTitle",
            new LoadableDetachableModel<String>() {

              @Override
              protected String load() {
                return getTitle();
              }
            }));
    add(
        new Label(
            "gbpDescription",
            new LoadableDetachableModel<String>() {

              @Override
              protected String load() {
                return getDescription();
              }
            }));

    // node id handling
    WebMarkupContainer container = new WebMarkupContainer("nodeIdContainer");
    add(container);
    String id = getNodeInfo().getId();
    Label label = new Label("nodeId", id);
    container.add(label);
    NODE_INFO.customize(container);
    if (id == null) {
      container.setVisible(false);
    }
  }
Ejemplo n.º 19
0
  public HNF1BMiscPanel(final String id, final Demographics demographics) {
    super(id);

    setOutputMarkupId(true);
    setOutputMarkupPlaceholderTag(true);

    HNF1BMisc hnf1BMisc = null;

    if (demographics.hasValidId()) {
      hnf1BMisc = hnf1BMiscManager.get(demographics.getId());
    }

    if (hnf1BMisc == null) {
      hnf1BMisc = new HNF1BMisc();
      hnf1BMisc.setRadarNo(demographics.getId());
    }

    // main model for this tab
    IModel<HNF1BMisc> model = new Model<HNF1BMisc>(hnf1BMisc);

    // components to update on ajax refresh
    final List<Component> componentsToUpdateList = new ArrayList<Component>();

    // general feedback for messages that are not to do with a certain component in the form
    final FeedbackPanel formFeedback = new FeedbackPanel("formFeedbackPanel");
    formFeedback.setOutputMarkupId(true);
    formFeedback.setOutputMarkupPlaceholderTag(true);
    componentsToUpdateList.add(formFeedback);

    Form<HNF1BMisc> form =
        new Form<HNF1BMisc>("form", new CompoundPropertyModel<HNF1BMisc>(model)) {
          @Override
          protected void onSubmit() {
            HNF1BMisc hnf1BMisc = getModelObject();

            // check all the radio buttons have values
            if (hnf1BMisc.getRenalCysts() == null
                || hnf1BMisc.getSingleKidney() == null
                || hnf1BMisc.getOtherRenalMalformations() == null
                || hnf1BMisc.getDiabetes() == null
                || hnf1BMisc.getGout() == null
                || hnf1BMisc.getGenitalMalformation() == null) {
              error("Please select a value for each radio button");

            } else {
              // if all the radios are complete check that we have any additional required data
              if (hnf1BMisc.getOtherRenalMalformations().equals(YesNo.YES)
                  && !StringUtils.hasText(hnf1BMisc.getOtherRenalMalformationsDetails())) {
                error("Please provide other renal malformation details");
              }

              if (hnf1BMisc.getGenitalMalformation().equals(YesNo.YES)
                  && !StringUtils.hasText(hnf1BMisc.getGenitalMalformationDetails())) {
                error("Please provide genital malformation details");
              }
            }

            if (!hasError()) {
              hnf1BMisc.setRadarNo(demographics.getId());
              hnf1BMiscManager.save(hnf1BMisc);
            }
          }
        };

    add(form);

    int maxAge = 90;
    int minAge = 1;

    // the list has to be strings so we can have the first one as N/A
    List<String> ages = new ArrayList<String>();
    ages.add("N/A");

    for (int x = minAge; x <= maxAge; x++) {
      ages.add(Integer.toString(x));
    }

    // have to set the generic feedback panel to only pick up msgs for them form
    ComponentFeedbackMessageFilter filter = new ComponentFeedbackMessageFilter(form);
    formFeedback.setFilter(filter);
    form.add(formFeedback);

    // add the patient detail bar to the tab
    PatientDetailPanel patientDetail =
        new PatientDetailPanel("patientDetail", demographics, "HNF1B Misc");
    patientDetail.setOutputMarkupId(true);
    form.add(patientDetail);
    componentsToUpdateList.add(patientDetail);

    RadioGroup<YesNo> renalCystsRadioGroup = new RadioGroup<YesNo>("renalCysts");
    form.add(renalCystsRadioGroup);
    renalCystsRadioGroup.add(new Radio<YesNo>("renalCystsNo", new Model<YesNo>(YesNo.NO)));
    renalCystsRadioGroup.add(new Radio<YesNo>("renalCystsYes", new Model<YesNo>(YesNo.YES)));

    RadioGroup<YesNo> singleKidneyRadioGroup = new RadioGroup<YesNo>("singleKidney");
    form.add(singleKidneyRadioGroup);
    singleKidneyRadioGroup.add(new Radio<YesNo>("singleKidneyNo", new Model<YesNo>(YesNo.NO)));
    singleKidneyRadioGroup.add(new Radio<YesNo>("singleKidneyYes", new Model<YesNo>(YesNo.YES)));

    RadioGroup<YesNo> otherRenalMalformationsRadioGroup =
        new RadioGroup<YesNo>("otherRenalMalformations");
    form.add(otherRenalMalformationsRadioGroup);
    otherRenalMalformationsRadioGroup.add(
        new Radio<YesNo>("otherRenalMalformationsNo", new Model<YesNo>(YesNo.NO)));
    otherRenalMalformationsRadioGroup.add(
        new Radio<YesNo>("otherRenalMalformationsYes", new Model<YesNo>(YesNo.YES)));

    TextArea otherClinicianAndContactInfo = new TextArea("otherRenalMalformationsDetails");
    form.add(otherClinicianAndContactInfo);

    RadioGroup<YesNo> diabetesRadioGroup = new RadioGroup<YesNo>("diabetes");
    form.add(diabetesRadioGroup);
    diabetesRadioGroup.add(new Radio<YesNo>("diabetesNo", new Model<YesNo>(YesNo.NO)));
    diabetesRadioGroup.add(new Radio<YesNo>("diabetesYes", new Model<YesNo>(YesNo.YES)));

    DropDownChoice<String> ageAtDiabetesDiagnosisDropDown =
        new DropDownChoice<String>(
            "ageAtDiabetesDiagnosis",
            new PropertyModel<String>(model, "ageAtDiabetesDiagnosisAsString"),
            ages);
    form.add(ageAtDiabetesDiagnosisDropDown);

    RadioGroup<YesNo> goutRadioGroup = new RadioGroup<YesNo>("gout");
    form.add(goutRadioGroup);
    goutRadioGroup.add(new Radio<YesNo>("goutNo", new Model<YesNo>(YesNo.NO)));
    goutRadioGroup.add(new Radio<YesNo>("goutYes", new Model<YesNo>(YesNo.YES)));

    DropDownChoice<String> ageAtGoutDiagnosisDropDown =
        new DropDownChoice<String>(
            "ageAtGoutDiagnosis",
            new PropertyModel<String>(model, "ageAtGoutDiagnosisAsString"),
            ages);
    form.add(ageAtGoutDiagnosisDropDown);

    RadioGroup<YesNo> genitalMalformationRadioGroup = new RadioGroup<YesNo>("genitalMalformation");
    form.add(genitalMalformationRadioGroup);
    genitalMalformationRadioGroup.add(
        new Radio<YesNo>("genitalMalformationNo", new Model<YesNo>(YesNo.NO)));
    genitalMalformationRadioGroup.add(
        new Radio<YesNo>("genitalMalformationYes", new Model<YesNo>(YesNo.YES)));

    TextArea genitalMalformationDetails = new TextArea("genitalMalformationDetails");
    form.add(genitalMalformationDetails);

    final Label successMessageTop =
        RadarComponentFactory.getSuccessMessageLabel(
            "successMessageTop", form, componentsToUpdateList);
    Label errorMessageTop =
        RadarComponentFactory.getErrorMessageLabel("errorMessageTop", form, componentsToUpdateList);

    final Label successMessageBottom =
        RadarComponentFactory.getSuccessMessageLabel(
            "successMessageBottom", form, componentsToUpdateList);
    Label errorMessageBottom =
        RadarComponentFactory.getErrorMessageLabel(
            "errorMessageBottom", form, componentsToUpdateList);

    form.add(
        new AjaxSubmitLink("saveTop") {
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
            target.add(formFeedback);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.add(formFeedback);
          }
        });

    form.add(
        new AjaxSubmitLink("saveBottom") {
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
            target.add(formFeedback);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.add(formFeedback);
          }
        });
  }
Ejemplo n.º 20
0
  /**
   * Constructor.
   *
   * @param parameters the current page parameters
   */
  public MailTemplate(final PageParameters parameters) {
    super(parameters);

    final FeedbackPanel feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    add(feedback);

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

    TextField<String> nameTextField =
        new TextField<>("name", new PropertyModel<String>(MailTemplate.this, "name"));
    nameTextField.setOutputMarkupId(true);
    form.add(nameTextField);

    final MultiLineLabel result = new MultiLineLabel("result", new Model<>());
    result.setOutputMarkupId(true);
    add(result);

    AjaxSubmitLink basedOnPageLink =
        new AjaxSubmitLink("pageBasedLink", form) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            PageParameters parameters = new PageParameters();
            parameters.set("name", name);
            PageProvider pageProvider = new PageProvider(TemplateBasedOnPage.class, parameters);
            CharSequence pageHtml = ComponentRenderer.renderPage(pageProvider);

            updateResult(result, pageHtml, target);
            target.add(feedback);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedback);
          }
        };

    AjaxSubmitLink basedOnPanelLink =
        new AjaxSubmitLink("panelBasedLink", form) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            CharSequence panelHtml =
                ComponentRenderer.renderComponent(
                    new MailTemplatePanel(
                        "someId", new PropertyModel<String>(MailTemplate.this, "name")));

            updateResult(result, panelHtml, target);
            target.add(feedback);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedback);
          }
        };

    AjaxSubmitLink basedOnTextTemplateLink =
        new AjaxSubmitLink("textTemplateBasedLink", form) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            Map<String, Object> variables = new HashMap<>();
            variables.put("name", name);

            CharSequence relativeUrl =
                urlFor(new PackageResourceReference(MailTemplate.class, "resource.txt"), null);
            String href =
                getRequestCycle().getUrlRenderer().renderFullUrl(Url.parse(relativeUrl.toString()));
            variables.put("downloadLink", href);

            PackageTextTemplate template =
                new PackageTextTemplate(MailTemplate.class, "mail-template.tmpl");
            CharSequence templateHtml = template.asString(variables);
            updateResult(result, templateHtml, target);
            target.add(feedback);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedback);
          }
        };

    add(basedOnPageLink, basedOnPanelLink, basedOnTextTemplateLink);
  }
Ejemplo n.º 21
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);
  }
Ejemplo n.º 22
0
  private void doMainLayout() {
    Fragment mainContent = new Fragment("main-content", "normal", this);
    final ModalWindow popup = new ModalWindow("popup");
    mainContent.add(popup);
    mainContent.add(new Label("style.name", new PropertyModel(style, "name")));
    mainContent.add(new Label("layer.name", new PropertyModel(layer, "name")));
    mainContent.add(
        new AjaxLink("change.style", new ParamResourceModel("CssDemoPage.changeStyle", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose style to edit"));
            popup.setContent(new StyleChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink("change.layer", new ParamResourceModel("CssDemoPage.changeLayer", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose layer to edit"));
            popup.setContent(new LayerChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink("create.style", new ParamResourceModel("CssDemoPage.createStyle", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(200);
            popup.setInitialWidth(300);
            popup.setTitle(new Model("Choose name for new style"));
            popup.setContent(new LayerNameInput(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink(
            "associate.styles", new ParamResourceModel("CssDemoPage.associateStyles", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose layers to associate"));
            popup.setContent(new MultipleLayerChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });

    final IModel<String> sldModel =
        new AbstractReadOnlyModel<String>() {
          public String getObject() {
            File file = findStyleFile(style.getFilename());
            if (file != null && file.isFile()) {
              BufferedReader reader = null;
              try {
                reader = new BufferedReader(new FileReader(file));
                StringBuilder builder = new StringBuilder();
                char[] line = new char[4096];
                int len = 0;
                while ((len = reader.read(line, 0, 4096)) >= 0) builder.append(line, 0, len);
                return builder.toString();
              } catch (IOException e) {
                throw new WicketRuntimeException(e);
              } finally {
                try {
                  if (reader != null) reader.close();
                } catch (IOException e) {
                  throw new WicketRuntimeException(e);
                }
              }
            } else {
              return "No SLD file found for this style. One will be generated automatically if you save the CSS.";
            }
          }
        };

    final CompoundPropertyModel model = new CompoundPropertyModel<CssDemoPage>(CssDemoPage.this);
    List<ITab> tabs = new ArrayList<ITab>();
    tabs.add(
        new PanelCachingTab(
            new AbstractTab(new Model("Generated SLD")) {
              public Panel getPanel(String id) {
                SLDPreviewPanel panel = new SLDPreviewPanel(id, sldModel);
                sldPreview = panel.getLabel();
                return panel;
              }
            }));
    tabs.add(
        new PanelCachingTab(
            new AbstractTab(new Model("Map")) {
              public Panel getPanel(String id) {
                return map = new OpenLayersMapPanel(id, layer, style);
              }
            }));
    if (layer.getResource() instanceof FeatureTypeInfo) {
      tabs.add(
          new PanelCachingTab(
              new AbstractTab(new Model("Data")) {
                public Panel getPanel(String id) {
                  try {
                    return new DataPanel(id, model, (FeatureTypeInfo) layer.getResource());
                  } catch (IOException e) {
                    throw new WicketRuntimeException(e);
                  }
                };
              }));
    } else if (layer.getResource() instanceof CoverageInfo) {
      tabs.add(
          new PanelCachingTab(
              new AbstractTab(new Model("Data")) {
                public Panel getPanel(String id) {
                  return new BandsPanel(id, (CoverageInfo) layer.getResource());
                };
              }));
    }
    tabs.add(
        new AbstractTab(new Model("CSS Reference")) {
          public Panel getPanel(String id) {
            return new DocsPanel(id);
          }
        });

    FeedbackPanel feedback2 = new FeedbackPanel("feedback-low");
    feedback2.setOutputMarkupId(true);
    mainContent.add(feedback2);

    String cssSource = style.getFilename().replaceFirst("(\\.sld)?$", ".css");

    mainContent.add(
        new StylePanel("style.editing", model, CssDemoPage.this, getFeedbackPanel(), cssSource));

    mainContent.add(new AjaxTabbedPanel("context", tabs));

    add(mainContent);
  }
Ejemplo n.º 23
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public DigitalRecSheetPage(
      Recommendation recommendation, final MobileSalesWorkspacePage mswPage) {
    final DailyRhythmPortalSession drpSession = getDailyRhythmPortalSession();

    if (recommendation == null) {
      recommendation = new Recommendation(); // check for null!
    }
    model = new DigitalRecSheetModel(recommendation);

    final boolean transferToBeast = recommendation.isTransferFlag();

    form.add(
        new Image(
            "transfer-to-beast", new ContextRelativeResource("/css/img/transfer-to-beast.png")) {

          private static final long serialVersionUID = 1L;

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

    formChanged = false;

    FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupPlaceholderTag(true);
    add(feedbackPanel);

    DrpUser user = drpSession.getDrpUser();

    model.setUser(user);

    // Tools Menu components:
    final ModalWindow coverageCheckModal = new ModalWindow("coverageCheckModal");

    // tools menu links:
    form.add(new BookmarkablePageLink("toolsLink1", CustomerDashboardPage.class));

    AjaxLink alink =
        new AjaxLink("toolsLink2") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(AjaxRequestTarget target) {

            coverageCheckModal.setContent(
                new CoverageCheckPanel(coverageCheckModal.getContentId(), coverageCheckModal));
            coverageCheckModal.show(target);
          }
        };
    add(coverageCheckModal);
    form.add(alink);

    // no-contract coverage maps link.
    AjaxLink ppcmLink =
        new AjaxLink("toolsLink3") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(AjaxRequestTarget target) {
            coverageCheckModal.setContent(
                new NoContractCoveragePanel(coverageCheckModal.getContentId(), coverageCheckModal));
            coverageCheckModal.show(target);
          }
        };
    form.add(ppcmLink);

    Map<LengthProperty, Integer> fieldLengths = this.getLengthProperties();

    final ModalWindow printOrEmailModal = new ModalWindow("printOrEmailModal");
    printOrEmailModal.setHeightUnit("px");
    printOrEmailModal.setInitialHeight(Util.getInt(getString("printOrEmailPopup.height"), 220));
    printOrEmailModal.setWidthUnit("px");
    printOrEmailModal.setInitialWidth(Util.getInt(getString("printOrEmailPopup.width"), 440));
    printOrEmailModal.setResizable(false);
    printOrEmailModal.setWindowClosedCallback(
        new WindowClosedCallback() {

          private static final long serialVersionUID = 1L;

          @Override
          public void onClose(AjaxRequestTarget target) {
            target.add(form);
          }
        });

    /**
     * Launches dialog to perform either a print or email of the current recommendation worksheet
     */
    final AjaxButton printOrEmail =
        new AjaxButton("printOrEmailBtn") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            logger.debug("in print or email handler");
            saveRecSheet();
            printOrEmailModal.show(target);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            // TODO Implement me!
          }
        };
    form.add(printOrEmail);
    printOrEmail.setOutputMarkupPlaceholderTag(true);

    // print or email modal dialog
    add(printOrEmailModal);
    printOrEmailModal.setPageCreator(
        new ModalWindow.PageCreator() {

          private static final long serialVersionUID = 1L;

          public Page createPage() {
            return new PrintOrEmailDialog(model.getObject());
          }
        });

    printOrEmailModal.setCloseButtonCallback(
        new ModalWindow.CloseButtonCallback() {

          public boolean onCloseButtonClicked(AjaxRequestTarget target) {
            target.prependJavaScript("doLoad();");
            return true;
          }
        });

    /** Saves the rec sheet */
    final Button saveButton =
        new Button("saveBtn") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            logger.debug("saving recsheet by button request");
            saveRecSheet();
          }
        };

    // save rec sheet button
    form.add(saveButton);
    saveButton.setOutputMarkupPlaceholderTag(true);

    // === Clear screen prompt and components ===
    final ModalWindow clearModal = new ModalWindow("clearModal");
    final AjaxButton clearButton =
        new AjaxButton("clearButton") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form<?> form) {

            String message =
                "Clear customer data?\n\nThis will apply to both the Dashboard and the Recommendation Sheet.";

            final YesNoPanel clearPanel =
                new YesNoPanel(clearModal.getContentId(), message, clearModal);
            // changing button text.
            clearPanel.setYesButtonText("Clear");
            clearPanel.setNoButtonText("Back");

            clearModal.setContent(clearPanel);

            clearModal.setWindowClosedCallback(
                new ModalWindow.WindowClosedCallback() {

                  private static final long serialVersionUID = 1L;

                  @Override
                  public void onClose(AjaxRequestTarget target) {
                    if (clearPanel.getDialogResult()) {
                      logger.debug("clearing customer from recsheet.");
                      DailyRhythmPortalSession session = getDailyRhythmPortalSession();
                      session.clearBestBuyCustomer();
                      session.clearSearchCustomer();
                      session.clearCarrierCustomer();
                      Recommendation rec = new Recommendation();
                      rec.setCreatedOn(new Date());
                      rec.setCreatedBy(session.getDrpUser().getUserId());
                      rec.setTransferFlag(false);
                      DigitalRecSheetPage drsPage = new DigitalRecSheetPage(rec, mswPage);
                      setResponsePage(drsPage);
                    }
                  }
                });

            clearModal.show(target);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            // TODO Implement me!
          }
        };

    clearButton.setDefaultFormProcessing(false);
    form.add(clearButton);
    add(clearModal);
    // === END of Clear Components ===

    /*
     * Search Rec Sheet button Navigates back to rec sheet search page
     */

    // close button exit point with popup.
    final ModalWindow exitWithoutSavingModal = new ModalWindow("exitWithoutSavingModal");
    String message = "Are you sure you want to exit without saving your changes?";

    final YesNoPanel exitPanel =
        new YesNoPanel(exitWithoutSavingModal.getContentId(), message, exitWithoutSavingModal);
    exitWithoutSavingModal.setContent(exitPanel);

    exitWithoutSavingModal.setWindowClosedCallback(
        new ModalWindow.WindowClosedCallback() {

          private static final long serialVersionUID = 1L;

          @Override
          public void onClose(AjaxRequestTarget target) {
            if (exitPanel.getDialogResult()) {
              setResponsePage(mswPage);
            }
          }
        });
    add(exitWithoutSavingModal);

    /*
     * ===== Search Rec Sheet Button ===== Search Rec Sheet button Navigates
     * back to rec sheet search page
     */
    final AjaxButton searchButton =
        new AjaxButton("searchBtn") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form<?> form) {

            logger.debug("closing recSheet by return to search button request.");
            PageParameters parameters = mswPage.getPageParameters();
            setResponsePage(new MobileSalesWorkspacePage(parameters));
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            // TODO Implement me!
          }
        };

    // this is a pure navigation button so we do not want form validation to
    // occur
    searchButton.setDefaultFormProcessing(false);
    closeForm.add(searchButton);

    /*
     * ===== Close Rec Sheet Button ===== Close Rec Sheet button Navigates
     * back to rec sheet search page
     */
    final AjaxButton closeButton =
        new AjaxButton("closeBtn") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            logger.debug("closing recSheet by close button request.");
            if (drpSession.getCustomer() == null) {
              setResponsePage(CustomerDashboardSearchPage.class);
            } else {
              setResponsePage(CustomerDashboardPage.class);
            }
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            // TODO Implement me!
          }
        };

    closeButton.setDefaultFormProcessing(false);
    closeForm.add(closeButton);
    form.add(closeForm);

    closeButton.setOutputMarkupPlaceholderTag(true);

    // if recommendation comes in blank, the model creates a new one...
    // Therefore we shouldn't mess with it until we retrieve it from the
    // model.
    Recommendation r = model.getRecommendation();
    String phoneNum = user.getLocationPhoneNum() == null ? "" : user.getLocationPhoneNum();
    if (r.getId() == 0) { // new rec sheet
      r.setSpecialistContactInfo(user.getFirstName() + " " + phoneNum);
      r.setEmpCrtFrstNm(user.getFirstName());
      r.setEmpCrtLastNm(user.getLastName());
    } else {
      r.setEmpAltFrstNm(user.getFirstName());
      r.setEmpAltLastNm(user.getLastName());
    }
    Essentials e = r.getEssentials();

    // first name
    TextField fldFirstname =
        new RequiredTextField("firstName", new PropertyModel<String>(r, "firstName"));
    fldFirstname.add(
        new StringValidator.LengthBetweenValidator(
            fieldLengths.get(LengthProperty.FLD_FIRSTNAME_MINLENGTH),
            fieldLengths.get(LengthProperty.FLD_FIRSTNAME_LENGTH)));
    form.add(fldFirstname);

    // last name
    RequiredTextField fldLastname =
        new RequiredTextField("lastName", new PropertyModel<String>(r, "lastName"));
    fldLastname.add(
        new StringValidator.LengthBetweenValidator(
            fieldLengths.get(LengthProperty.FLD_LASTNAME_MINLENGTH),
            fieldLengths.get(LengthProperty.FLD_LASTNAME_LENGTH)));
    form.add(fldLastname);

    // mobile number
    final TextField mobile =
        new RequiredTextField("mobileNum", new PropertyModel<PhoneNumber>(this, "phoneNumber")) {

          private static final long serialVersionUID = 1L;

          @Override
          public <C> IConverter<C> getConverter(Class<C> type) {
            return new PhoneNumberConverter();
          }
        };
    mobile.add(
        new AjaxFormComponentUpdatingBehavior("onBlur") {

          private static final long serialVersionUID = 1L;

          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            target.add(mobile);
          }
        });
    mobile.setMarkupId("mobileNum");
    form.add(mobile);

    form.add(
        new TextField("contacttime", new PropertyModel<String>(r, "bestTimeToContact"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_CONTACTTIME_LENGTH))));

    TextField tradeInValue =
        new TextField("tradeInValue", new PropertyModel<String>(r, "tradeInValue")) {

          private static final long serialVersionUID = 1L;

          @Override
          public <C> IConverter<C> getConverter(Class<C> type) {
            return new MoneyConverter();
          }
        };

    tradeInValue.add(new MinimumValidator<BigDecimal>(new BigDecimal(0)));
    form.add(tradeInValue);

    form.add(new CheckBox("upgradetext", new PropertyModel<Boolean>(r, "upgradeReminderText")));
    form.add(new CheckBox("upgradecall", new PropertyModel<Boolean>(r, "upgradeReminderCall")));

    // upgrade date
    DateTextField udate =
        new DateTextField(
            "upgradedate", new PropertyModel<Date>(r, "upgradeEligibilityDate"), "EEEE MM/dd/yy");
    DatePicker dp = new DatePicker();
    udate.add(dp);
    form.add(udate);

    // customer - plan features device. On left side of form, not to be
    // confused with recommended plan/features/device.
    form.add(
        new TextArea("planFeaturesDevice", new PropertyModel<String>(r, "subscriptionInfo"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_PLANFEATURESDEVICE_LENGTH))));
    form.add(
        new TextArea("internetuse", new PropertyModel<String>(r, "netUseInfo"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_INTERNETUSE_LENGTH))));

    form.add(
        new TextArea("rec_connectivity", new PropertyModel<String>(r, "recommendedSubscription"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_REC_CONNECTIVITY_LENGTH))));
    form.add(
        new TextArea("rec_phonedevice", new PropertyModel<String>(r, "recommendedDevice"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_REC_PHONEDEVICE_LENGTH))));
    form.add(
        new TextField("e_bluetooth", new PropertyModel<String>(e, "handsfree"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_memory", new PropertyModel<String>(e, "memory"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_accessories", new PropertyModel<String>(e, "accessories"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_shields", new PropertyModel<String>(e, "shields"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_chargers", new PropertyModel<String>(e, "chargers"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_gsbtp", new PropertyModel<String>(e, "gsbtp"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_buyback", new PropertyModel<String>(e, "buyback"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));
    form.add(
        new TextField("e_financing", new PropertyModel<String>(e, "financing"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_ESSENTIAL_LENGTH))));

    form.add(
        new TextArea("notes", new PropertyModel<String>(r, "notes"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_NOTES_LENGTH))));
    form.add(
        new TextArea("contactinfo", new PropertyModel<String>(r, "specialistContactInfo"))
            .add(
                new StringValidator.MaximumLengthValidator(
                    fieldLengths.get(LengthProperty.FLD_CONTACTINFO_LENGTH))));

    form.add(
        new CheckBox(
            "md_internet",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.INTERNET.name())));
    form.add(
        new CheckBox(
            "md_email",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.EMAIL.name())));
    form.add(
        new CheckBox(
            "md_music",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.MUSIC.name())));
    form.add(
        new CheckBox(
            "md_video",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.VIDEO.name())));
    form.add(
        new CheckBox(
            "md_photo",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.PHOTO.name())));
    form.add(
        new CheckBox(
            "md_tv",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.TV.name())));
    form.add(
        new CheckBox(
            "md_games",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.GAMING.name())));
    form.add(
        new CheckBox(
            "md_texting",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.TEXTING.name())));
    form.add(
        new CheckBox(
            "md_unlocked",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.UNLOCKED.name())));
    form.add(
        new CheckBox(
            "md_nav",
            new CheckboxModel(
                r, "deviceCapabilities", Recommendation.DeviceCapabilities.NAVIGATION.name())));

    form.add(
        new CheckBox(
            "wow_data",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.DATATRANSFER.name())));
    form.add(
        new CheckBox(
            "wow_email",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.PERSONALEMAIL.name())));
    form.add(
        new CheckBox(
            "wow_bluetooth",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.BLUETOOTHPAIRING.name())));
    form.add(
        new CheckBox(
            "wow_apps",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.APPLICATIONS.name())));
    form.add(
        new CheckBox(
            "wow_sw",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.SOFTWARE.name())));
    form.add(
        new CheckBox(
            "wow_social",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.SOCIALNETWORKING.name())));
    form.add(
        new CheckBox(
            "wow_power",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.POWERMANAGEMENT.name())));
    form.add(
        new CheckBox(
            "wow_voicemail",
            new CheckboxModel(
                r, "wowRequirements", Recommendation.WowRequirements.VOICEMAIL.name())));
    form.add(
        new CheckBox(
            "wow_other",
            new CheckboxModel(r, "wowRequirements", Recommendation.WowRequirements.OTHER.name())));

    HiddenField formChanged =
        new HiddenField<Boolean>("formChanged", new PropertyModel<Boolean>(this, "formChanged"));
    closeForm.add(formChanged);

    add(form);
    form.add(closeForm);

    SessionTimeoutPanel sessionTimeoutPanel = new SessionTimeoutPanel("sessionTimeoutPanel");
    add(sessionTimeoutPanel);
    sessionTimeoutPanel.setOutputMarkupPlaceholderTag(true);
  }
Ejemplo n.º 24
0
  private void init() {
    setDefaultModel(new PropertyModel(this, "product"));

    // Feedback
    final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupId(true);
    feedbackPanel.setFilter(new ContainerFeedbackMessageFilter(this));
    add(feedbackPanel);

    // Form
    this.form =
        new StatelessForm("form") {
          @Override
          protected void onSubmit() {
            product = productDao.update(product);
          }
        };
    this.form.setVersioned(false);
    add(this.form);

    // Boxes
    if (this.product != null) {
      add(new ReleasesBox("releasesBox", this.product, 100));
      this.form.add(new ReleaseTraitsPanel("templates", this.product));
    } else {
      add(new NoItemsFoundBox("releasesBox", "No product specified."));
      this.form.add(new WebMarkupContainer("templates"));
    }

    // Save as .properties - TODO
    this.form.add(
        new PropertiesDownloadLink(
            "downloadProps", product.getTraits(), product.getName() + "-traits.properties"));

    // Upload & apply .properties
    this.add(
        new PropertiesUploadForm("uploadForm") {
          FileUploadField upload;

          @Override
          protected void onSubmit() {
            Properties props;
            try {
              props = processPropertiesFromUploadedFile();
            } catch (IOException ex) {
              feedbackPanel.error("Could not process properties: " + ex.toString());
              return;
            }

            ReleaseTraits traits = ((Product) getPage().getDefaultModelObject()).getTraits();
            PropertiesUtils.applyToObjectFlat(traits, props);
            productDao.update(product);
          }
        });

    // Danger Zone
    WebMarkupContainer dangerZone = new WebMarkupContainer("dangerZone");
    this.add(dangerZone);

    // Danger Zone Form
    dangerZone.add(
        new StatelessForm("form") {
          {
            // Really button
            final AjaxButton really = new AjaxButton("deleteReally") {};
            really.setVisible(false).setRenderBodyOnly(false);
            really.setOutputMarkupPlaceholderTag(true);
            add(really);

            // Delete button
            add(
                new AjaxLink("delete") {
                  @Override
                  public void onClick(AjaxRequestTarget target) {
                    target.add(really);
                    really.setVisible(true);
                    // really.add(AttributeModifier.replace("style", "")); // Removes
                    // style="visibility: hidden".
                    // super.onSubmit( target, form );
                  }
                });
          }

          @Override
          protected void onSubmit() {
            productDao.deleteIncludingReleases((Product) product);
            setResponsePage(HomePage.class);
          }
        });
  } // init()
Ejemplo n.º 25
0
  private void initComponents() {

    this.form =
        new Form<ModulTransfer>(
            "createModulForm", new CompoundPropertyModel<ModulTransfer>(new ModulTransfer()));

    this.form.add(new TextField<String>("name"));
    this.form.add(new TextField<Integer>("creditPoints"));

    if (this.mod != null) {
      this.form.setModelObject(this.mod);
    }

    final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupId(true);

    add(feedbackPanel);

    this.form.add(
        new AjaxSubmitLink("submitModulForm", this.form) {

          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            final ModulTransfer newModul = (ModulTransfer) form.getModelObject();

            if (mod == null) {
              if (restMod.createModul(par.getId().toString(), newModul)) {

                if (modPage != null) {
                  modPage.refreshModul();
                  target.add(modPage.getPanel());

                  modPage.getModal().close(target);
                } else {
                  parPage.getModal().close(target);
                }
              } else {
                /** Fehler anzeigen */
                error("Es ist ein Fehler beim Erstellen der Fakultät aufgetreten!");
              }
            } else {
              if (restMod.updateModul(newModul)) {
                if (modPage != null) {
                  modPage.refreshModul();
                  target.add(modPage.getPanel());

                  modPage.getModal().close(target);
                } else {
                  parPage.getModal().close(target);
                }
              } else {
                /** Fehler anzeigen */
                error("Es ist ein Fehler beim Aktualisieren der Fakultät aufgetreten!");
              }
            }
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
          }
        });

    add(new Label("msgCreateModul", "Modul für " + this.par.getName() + " erstellen"));
    add(this.form);
  }
  public PatternTimePickerPage() {
    Form<Void> form = new Form<Void>("form");
    this.add(form);

    // FeedbackPanel //
    final FeedbackPanel feedbackPanel = new JQueryFeedbackPanel("feedback");
    form.add(feedbackPanel.setOutputMarkupId(true));

    // TimePicker //
    Calendar calendar = Calendar.getInstance();
    calendar.set(0, 0, 0, 14, 0); // 2:00 PM

    final TimePicker timepicker =
        new TimePicker("timepicker", new Model<Date>(calendar.getTime()), "HH:mm") {

          private static final long serialVersionUID = 1L;

          /**
           * This is different way to specify the kendo-ui format pattern. Look at the "DatePicker:
           * using pattern" sample to the other way.
           */
          @Override
          protected void onConfigure(JQueryBehavior behavior) {
            super.onConfigure(behavior);

            // this pattern is compatible with both java & kendo-ui, so we can use #getTextFormat()
            // to retrieve the pattern
            behavior.setOption("format", Options.asString(this.getTextFormat()));
          }
        };

    form.add(timepicker);

    // Buttons //
    form.add(
        new Button("submit") {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            this.info(timepicker.getModelObjectAsString());
          }
        });

    form.add(
        new AjaxButton("button") {

          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            this.info(timepicker.getModelObjectAsString());
            target.add(feedbackPanel);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
          }
        });
  }
Ejemplo n.º 27
0
  public AddGradeItemPanel(String id, final ModalWindow window) {
    super(id);

    Assignment assignment = new Assignment();

    // Default released to true
    assignment.setReleased(true);
    // If no categories, then default counted to true
    Gradebook gradebook = businessService.getGradebook();
    assignment.setCounted(
        GradebookService.CATEGORY_TYPE_NO_CATEGORY == gradebook.getCategory_type());

    Model<Assignment> model = new Model<Assignment>(assignment);

    Form form = new Form("addGradeItemForm", model);

    AjaxButton submit =
        new AjaxButton("submit") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form form) {
            Assignment assignment = (Assignment) form.getModelObject();

            Long assignmentId = null;

            boolean success = true;
            try {
              assignmentId = businessService.addAssignment(assignment);
            } catch (AssignmentHasIllegalPointsException e) {
              error(new ResourceModel("error.addgradeitem.points").getObject());
              success = false;
            } catch (ConflictingAssignmentNameException e) {
              error(new ResourceModel("error.addgradeitem.title").getObject());
              success = false;
            } catch (ConflictingExternalIdException e) {
              error(new ResourceModel("error.addgradeitem.exception").getObject());
              success = false;
            } catch (Exception e) {
              error(new ResourceModel("error.addgradeitem.exception").getObject());
              success = false;
            }
            if (success) {
              getSession()
                  .info(
                      MessageFormat.format(
                          getString("notification.addgradeitem.success"), assignment.getName()));
              setResponsePage(
                  getPage().getPageClass(),
                  new PageParameters()
                      .add(GradebookPage.CREATED_ASSIGNMENT_ID_PARAM, assignmentId));
            } else {
              target.addChildren(form, FeedbackPanel.class);
            }
          }
        };
    form.add(submit);

    form.add(new AddGradeItemPanelContent("subComponents", model));

    FeedbackPanel feedback =
        new FeedbackPanel("addGradeFeedback") {
          private static final long serialVersionUID = 1L;

          @Override
          protected Component newMessageDisplayComponent(
              final String id, final FeedbackMessage message) {
            final Component newMessageDisplayComponent =
                super.newMessageDisplayComponent(id, message);

            if (message.getLevel() == FeedbackMessage.ERROR
                || message.getLevel() == FeedbackMessage.DEBUG
                || message.getLevel() == FeedbackMessage.FATAL
                || message.getLevel() == FeedbackMessage.WARNING) {
              add(AttributeModifier.replace("class", "messageError"));
              add(AttributeModifier.append("class", "feedback"));
            } else if (message.getLevel() == FeedbackMessage.INFO) {
              add(AttributeModifier.replace("class", "messageSuccess"));
              add(AttributeModifier.append("class", "feedback"));
            }

            return newMessageDisplayComponent;
          }
        };
    feedback.setOutputMarkupId(true);
    form.add(feedback);

    AjaxButton cancel =
        new AjaxButton("cancel") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            window.close(target);
          }
        };
    form.add(cancel);
    add(form);
  }
Ejemplo n.º 28
0
  public SaveCancelFormPanel(String id, boolean ajax) {
    super(id);

    form = new Form("form");
    form.add(new SetFocusBehavior(form));
    feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupId(true);
    titleLabel = new Label("title", getTitleModel());

    if (ajax) {
      submitButton =
          new AjaxButton("submitButton") {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form form) {
              onSave(target);
              if (!Session.get()
                  .getFeedbackMessages()
                  .hasMessage(new ErrorLevelFeedbackMessageFilter(FeedbackMessage.ERROR))) {
                defaultReturnAction(target);
              }
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form form) {
              target.addComponent(feedbackPanel);
            }
          };
      cancelButton =
          new AjaxButton("cancelButton") {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form form) {
              onCancel(target);
              defaultReturnAction(target);
            }
          };
    } else {
      submitButton =
          new Button("submitButton") {
            @Override
            public void onSubmit() {
              onSave(null);
              if (!Session.get()
                  .getFeedbackMessages()
                  .hasMessage(new ErrorLevelFeedbackMessageFilter(FeedbackMessage.ERROR))) {
                defaultReturnAction();
              }
            }
          };
      cancelButton =
          new Button("cancelButton") {
            @Override
            public void onSubmit() {
              onCancel(null);
              defaultReturnAction();
            }
          };
    }
    cancelButton.setDefaultFormProcessing(false);

    add(form);
    form.add(feedbackPanel);
    form.add(titleLabel);
    form.add(submitButton);
    form.add(cancelButton);
  }
Ejemplo n.º 29
0
  public PasswordPage() {

    Usuario usuario =
        this.daoService.getUsuario(SecurityUtils.getSubject().getPrincipal().toString());

    final Form<Usuario> form =
        new Form<Usuario>("form", new CompoundPropertyModel<Usuario>(usuario));
    this.add(form);

    final FeedbackPanel feedBackPanel = new FeedbackPanel("feedBackPanel");
    feedBackPanel.setOutputMarkupId(true);
    form.add(feedBackPanel);

    Label nombreUsuario = new Label("nombreUsuario", usuario.getNombre());
    form.add(nombreUsuario);

    final PasswordTextField passActual =
        new PasswordTextField("contraseniaActual", new Model<String>(new String()));
    passActual.setLabel(Model.of("Password actual"));
    passActual.add(new StringValidator(0, 30));
    passActual.setRequired(true);
    passActual.add(
        new IValidator<String>() {

          @Override
          public void validate(IValidatable<String> validatable) {

            Boolean correcto =
                daoService.validarPassword(form.getModelObject(), validatable.getValue());

            if (!correcto) {
              error(validatable, "La password ingresada en 'Password actual' no es correcta.");
            }
          }

          private void error(IValidatable<String> validatable, String errorKey) {
            ValidationError error = new ValidationError();
            error.addKey(getClass().getSimpleName() + "." + errorKey);
            error.setMessage(errorKey);
            validatable.error(error);
          }
        });

    form.add(passActual);

    final PasswordTextField password = new PasswordTextField("password");
    password.setLabel(Model.of("Nueva Password"));
    password.add(new StringValidator(0, 30));
    password.setRequired(true);
    form.add(password);

    final PasswordTextField passConfirmacion =
        new PasswordTextField("contraseniaConfirmacion", new Model<String>(new String()));
    passConfirmacion.setLabel(Model.of("Confirmaci\363n"));
    passConfirmacion.setRequired(true);
    passConfirmacion.add(new StringValidator(0, 30));
    passConfirmacion.add(
        new IValidator<String>() {

          @Override
          public void validate(IValidatable<String> validatable) {

            if (!validatable.getValue().equals(password.getValue())) {
              error(
                  validatable,
                  "Las passwords ingresadas en 'Nueva Password' y 'Confimaci\363n' deben ser iguales.");
            }
          }

          private void error(IValidatable<String> validatable, String errorKey) {
            ValidationError error = new ValidationError();
            error.addKey(getClass().getSimpleName() + "." + errorKey);
            error.setMessage(errorKey);
            validatable.error(error);
          }
        });

    form.add(passConfirmacion);

    final SelectModalWindow selectModalWindow =
        new SelectModalWindow("modalWindow") {

          public void onCancel(AjaxRequestTarget target) {
            close(target);
          }
        };

    form.add(selectModalWindow);

    AjaxButton submit =
        new AjaxButton("submit", form) {

          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            Usuario usuario = (Usuario) form.getModelObject();

            String nuevaPassword = usuario.getPassword();

            Boolean estaHabilitado =
                PasswordPage.this.daoService.getPermisoCambiarPassword(usuario.getNombreLogin());

            if (estaHabilitado) {
              PasswordPage.this.daoService.setPassword(usuario.getNombreLogin(), nuevaPassword);
              selectModalWindow.show(target);

            } else {
              this.error("No tiene permiso para cambiar su password");
            }

            target.add(feedBackPanel);
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedBackPanel);
          }
        };

    form.add(submit);
  }
Ejemplo n.º 30
0
  public PatientsLoginPage() {
    // Patients log in form
    CompoundPropertyModel<PatientUser> model =
        new CompoundPropertyModel<PatientUser>(new PatientUser());
    final Model<String> passwordModel = new Model<String>();

    // components to update on ajax
    final List<Component> componentsToUpdateList = new ArrayList<Component>();

    Form<PatientUser> form =
        new Form<PatientUser>("form", model) {
          @Override
          protected void onSubmit() {
            RadarSecuredSession session = RadarSecuredSession.get();
            PatientUser user = getModelObject();
            boolean loginFailed = false;
            PatientUser patientUser =
                userManager.getPatientUserWithUsername(user.getUsername(), user.getDateOfBirth());

            if (patientUser != null) {
              if (session.signIn(user.getUsername(), passwordModel.getObject())) {
                session.setUser(patientUser);
                // If we haven't been diverted here from a page request (i.e. we clicked login),
                // redirect to logged in page
                setResponsePage(
                    SrnsPatientPageReadOnly.class,
                    SrnsPatientPageReadOnly.getParameters(patientUser.getRadarNumber()));

              } else {
                loginFailed = true;
              }
            } else {
              loginFailed = true;
            }

            if (loginFailed) {
              // Show that the login failed if we couldn't authenticate
              error(LOGIN_FAILED_MESSAGE);
            }
          }
        };
    add(form);

    // Add components to form
    form.add(new RadarRequiredTextField("username", form, componentsToUpdateList));
    RadarRequiredPasswordTextField password =
        new RadarRequiredPasswordTextField("password", form, componentsToUpdateList);
    form.add(password);
    password.setModel(passwordModel);

    // Date of birth with picker
    DateTextField dateOfBirth =
        new RadarRequiredDateTextField("dateOfBirth", form, componentsToUpdateList);
    form.add(dateOfBirth);

    // Construct feedback panel
    final FeedbackPanel feedbackPanel =
        new FeedbackPanel(
            "feedback",
            new IFeedbackMessageFilter() {
              public boolean accept(FeedbackMessage feedbackMessage) {
                String message = feedbackMessage.getMessage().toString();
                return message.contains(LOGIN_FAILED_MESSAGE);
              }
            });
    form.add(feedbackPanel);
    componentsToUpdateList.add(feedbackPanel);
    feedbackPanel.setOutputMarkupPlaceholderTag(true);

    form.add(
        new IndicatingAjaxButton("submit") {
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(
                componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
          }

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
          }
        });

    // Add links for forgotten password and register
    add(
        new BookmarkablePageLink<PatientForgottenPasswordPage>(
            "forgottenPasswordLink", PatientForgottenPasswordPage.class));
  }