Esempio n. 1
0
  @Override
  public void buildItems(Fragment fragment, final Preference preference) {
    fragment.add(new TextField<String>("name", new PropertyModel<String>(preference, "name")));

    RefreshingView<String> view =
        new RefreshingView<String>("values") {
          private static final long serialVersionUID = 1L;

          @Override
          protected Iterator<IModel<String>> getItemModels() {
            List<IModel<String>> preferenceValueModels = new LinkedList<IModel<String>>();
            int preferenceCount = preference.getValues().size();

            for (int i = 0; i < preferenceCount; i++) {
              preferenceValueModels.add(new PropertyModel<String>(preference, "values." + i));
            }

            return preferenceValueModels.iterator();
          }

          @Override
          protected void populateItem(Item<String> item) {
            item.add(new TextField<String>("value", item.getModel()));
          }
        };

    fragment.add(view);
  }
Esempio n. 2
0
  @SuppressWarnings("serial")
  private Fragment getDepartmentListHolder(List<UserDepartment> departments) {
    Fragment fragment = new Fragment("itemListHolder", "itemListHolder", DepartmentAdminPage.this);

    deptListView =
        new EntrySelectorListView<UserDepartment>("itemList", departments) {
          @Override
          protected void onPopulate(
              ListItem<UserDepartment> item, IModel<UserDepartment> itemModel) {
            UserDepartment dept = item.getModelObject();

            item.add(new Label("name", dept.getName()));
            item.add(new Label("code", dept.getCode()));
            item.add(new Label("users", dept.getUsers() == null ? 0 : dept.getUsers().size()));
          }

          @Override
          protected void onClick(ListItem<UserDepartment> item, AjaxRequestTarget target)
              throws ObjectNotFoundException {
            final Integer deptId = item.getModelObject().getDepartmentId();

            getTabbedPanel()
                .setEditBackingBean(
                    new DepartmentAdminBackingBean(userService.getUserDepartment(deptId)));
            getTabbedPanel().switchTabOnAjaxTarget(target, AddEditTabbedPanel.TABPOS_EDIT);
          }
        };

    fragment.add(deptListView);

    return fragment;
  }
  private Fragment getLocationFragment(final TopologyNode node, final PageReference pageRef) {
    final Fragment fragment = new Fragment("actions", "locationActions", this);

    final AjaxLink<String> create =
        new IndicatingAjaxLink<String>("create") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            final ConnInstanceTO modelObject = new ConnInstanceTO();
            modelObject.setLocation(node.getKey().toString());

            final IModel<ConnInstanceTO> model = new CompoundPropertyModel<>(modelObject);
            resourceModal.setFormModel(model);

            target.add(resourceModal.setContent(new ConnectorModal(resourceModal, pageRef, model)));

            resourceModal.header(
                new Model<>(MessageFormat.format(getString("connector.new"), node.getKey())));

            MetaDataRoleAuthorizationStrategy.authorize(
                resourceModal.addSumbitButton(), ENABLE, StandardEntitlement.CONNECTOR_CREATE);

            resourceModal.show(true);
          }
        };
    fragment.add(create);

    MetaDataRoleAuthorizationStrategy.authorize(
        create, ENABLE, StandardEntitlement.CONNECTOR_CREATE);

    return fragment;
  }
  public ModalDialogWithStylePanel(final String id) {
    super(id);
    final ModalWindow modal = new ModalWindow("modal");
    modal.setCssClassName("w_vegas");
    modal.setTitle("Trivial Modal");

    final AjaxLink<Void> modalLink =
        new AjaxLink<Void>("modalLink") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(final AjaxRequestTarget target) {

            target.appendJavaScript(
                "var originalStyle = $('.wicket-modal').attr('style');"
                    + "$('.wicket-modal').attr('style', originalStyle + 'opacity: 0.5;');");
          }
        };
    final Fragment modalFragment = new Fragment(modal.getContentId(), "modalContent", this);
    modalFragment.add(modalLink);
    modal.setContent(modalFragment);

    add(modal);
    add(
        new AjaxLink<Void>("openModal") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            modal.show(target);
          }
        });
  }
Esempio n. 5
0
  private void addOrReplaceTabContentPanel() {
    Fragment fragment;

    switch (tabContentType.get(tabNumberModel.getObject())) {
      case LIST:
        // Create list representing the
        fragment = new Fragment("tabContentPanel", "events", this);

        eventsList =
            new AbstractListEventPanel<Event>("eventsPanel") {
              @Override
              protected SortableDataProvider<Event, String> getDataProvider() {
                return new SortableEventProvider(sessionFactory, filterModel);
              }
            };
        eventsList.setOutputMarkupId(true);

        fragment.add(eventsList);
        break;
      default:
        throw new IllegalStateException("Invalid tab content type");
    }

    tabContent.addOrReplace(fragment);
  }
  @Override
  protected WebMarkupContainer newContent(String markupId) {
    Fragment fragment = new Fragment(markupId, "tooltip-fragment", markupProvider);
    fragment.add(new Label("content", Model.of(this.content)));

    return fragment;
  }
  @SuppressWarnings("serial")
  private Component createParameterList(final String id, final Collection<Parameter<?>> params) {
    List<ParameterInfo> inputs = new ArrayList<ParameterInfo>();

    for (Parameter<?> input : params) {
      inputs.add(
          new ParameterInfo(
              input.getName().toString(),
              input.getDescription().toString(),
              input.getType().getSimpleName(),
              input.getMinOccurs(),
              input.getMaxOccurs()));
    }

    Fragment table = new Fragment(id, "paramlist", OpenGeoProcessListPage.this);
    ListView<ParameterInfo> rows =
        new ListView<ParameterInfo>("param", inputs) {
          @Override
          protected void populateItem(ListItem<ParameterInfo> item) {
            item.add(
                new Label("title", new PropertyModel<String>(item.getModel(), "title")),
                new Label("name", new PropertyModel<String>(item.getModel(), "name")),
                new Label("type", new PropertyModel<String>(item.getModel(), "type")),
                new Label("minOccurs", new PropertyModel<Integer>(item.getModel(), "minOccurs")),
                new Label("maxOccurs", new PropertyModel<String>(item.getModel(), "maxOccurs"))
                    .setEscapeModelStrings(false));
          }
        };

    table.add(rows);
    return table;
  }
Esempio n. 8
0
  private void addSshKeys(final UserModel user) {
    Fragment keysTab = new Fragment("sshKeysTab", "sshKeysTabFragment", this);
    keysTab.add(new SshKeysPanel("sshKeysPanel", user));

    // add the SSH keys tab
    add(new Fragment("sshKeysLink", "sshKeysLinkFragment", this).setRenderBodyOnly(true));
    add(keysTab.setRenderBodyOnly(true));
  }
Esempio n. 9
0
  protected Component headerPanel() {
    Fragment header = new Fragment(HEADER_PANEL, "header", this);

    // the add button
    header.add(
        new BookmarkablePageLink<NewDataAccessRulePage>("addNew", NewDataAccessRulePage.class));

    // the removal button
    header.add(removal = new SelectionDataRuleRemovalLink("removeSelected", rules, dialog));
    removal.setOutputMarkupId(true);
    removal.setEnabled(false);

    return header;
  }
Esempio n. 10
0
  protected void createDepartmentInput(Form<T> form) {
    Fragment f = new Fragment("dept", "department", this);

    DropDownChoice<UserDepartment> userDepartment =
        new DropDownChoice<UserDepartment>(
            "user.userDepartment",
            getUserDepartments(),
            new ChoiceRenderer<UserDepartment>("name"));
    userDepartment.setRequired(true);
    userDepartment.setLabel(new ResourceModel("admin.user.department"));
    userDepartment.add(new ValidatingFormComponentAjaxBehavior());
    f.add(userDepartment);
    f.add(new AjaxFormComponentFeedbackIndicator("departmentValidationError", userDepartment));
    form.add(f);
  }
Esempio n. 11
0
  protected Component headerPanel() {
    Fragment header = new Fragment(HEADER_PANEL, "header", this);

    // the add button
    header.add(new BookmarkablePageLink<WorkspaceNewPage>("addNew", WorkspaceNewPage.class));

    // the removal button
    header.add(removal = new SelectionRemovalLink("removeSelected", table, dialog));
    removal.setOutputMarkupId(true);
    removal.setEnabled(false);

    // check for full admin, we don't allow workspace admins to add new workspaces
    header.setEnabled(isAuthenticatedAsAdmin());
    return header;
  }
Esempio n. 12
0
  // Factory //
  @Override
  protected Fragment newInputFragment(String id) {
    Fragment fragment;

    // no input TextField has been supplied in ctor //
    if (this.input == null) {
      this.input = new HiddenField<Integer>("input", this.getModel(), Integer.class);

      fragment = new Fragment(id, "input-fragment", this);
      fragment.add(this.input.setOutputMarkupPlaceholderTag(true));
    } else {
      fragment = super.newInputFragment(id); // return empty fragment
    }

    return fragment;
  }
  @Test
  public void fragment1() {
    MarkupContainer a = new A(), b = new B(), r = new R(), s = new S();

    TestPage page = new TestPage();
    page.setPageMarkup(
        "<a wicket:id='a'></a><f wicket:id='fragment'></f><b wicket:id='b'></b>"
            + "<wicket:fragment wicket:id='f'><r wicket:id='r'></r><s wicket:id='s'></s></wicket:fragment>");

    Fragment fragment = new Fragment("fragment", "f", page);

    fragment.queue(r, s);
    page.queue(a, b, fragment);

    assertThat(page, hasPath(new Path(a)));
    assertThat(page, hasPath(new Path(b)));
    assertThat(page, hasPath(new Path(fragment, r)));
    assertThat(page, hasPath(new Path(fragment, s)));
  }
  private Fragment getSyncopeFragment(final PageReference pageRef) {
    final Fragment fragment = new Fragment("actions", "syncopeActions", this);

    final AjaxLink<String> tasks =
        new IndicatingAjaxLink<String>("tasks") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            target.add(taskModal.setContent(new SchedTasks(pageRef)));
            taskModal.header(new ResourceModel("task.generic.list", "Scheduled tasks"));
            taskModal.show(true);
          }
        };
    fragment.add(tasks);

    MetaDataRoleAuthorizationStrategy.authorize(tasks, ENABLE, StandardEntitlement.TASK_LIST);

    return fragment;
  }
Esempio n. 15
0
  private Fragment getUserListHolder(List<User> users) {
    Fragment fragment = new Fragment("itemListHolder", "itemListHolder", UserAdmin.this);

    userListView =
        new ListView<User>("itemList", users) {
          private static final long serialVersionUID = 5334338761736798802L;

          @Override
          protected void populateItem(ListItem<User> item) {
            final User user = item.getModelObject();
            final Integer userId = user.getUserId();

            AjaxLink<Void> link =
                new AjaxLink<Void>("itemLink") {
                  private static final long serialVersionUID = -3898942767521616039L;

                  @Override
                  public void onClick(AjaxRequestTarget target) {
                    try {
                      getTabbedPanel()
                          .setEditBackingBean(
                              new UserBackingBean(
                                  userService.getUserAndCheckDeletability(userId),
                                  AdminAction.EDIT));
                      getTabbedPanel().switchTabOnAjaxTarget(target, 1);
                    } catch (ObjectNotFoundException e) {
                      LOGGER.error("User not found for id: " + userId);
                    }
                  }
                };

            item.add(link);
            link.add(new Label("linkLabel", user.getFullName() + (user.isActive() ? "" : "*")));
          }
        };

    fragment.add(userListView);

    return fragment;
  }
Esempio n. 16
0
  // Factories //
  @Override
  protected Fragment newInputFragment(String id) {
    Fragment fragment = null;

    // lower & upper TextFields have not been specified in ctor //
    if (this.lower == null || this.upper == null) {
      this.lower =
          new HiddenField<Integer>(
              "lower", new PropertyModel<Integer>(this.getModelObject(), "lower"), Integer.class);
      this.upper =
          new HiddenField<Integer>(
              "upper", new PropertyModel<Integer>(this.getModelObject(), "upper"), Integer.class);

      fragment = new Fragment(id, "range-fragment", this);
      fragment.add(this.lower.setOutputMarkupPlaceholderTag(true));
      fragment.add(this.upper.setOutputMarkupPlaceholderTag(true));
    } else {
      fragment = super.newInputFragment(id); // return empty fragment
    }

    return fragment;
  }
    @Override
    protected void onInitialize() {
      ContentViewOrEditPanel contentViewOrEditPanel =
          new ContentViewOrEditPanel("contentViewOrEditPanel", (IModel<Product>) getDefaultModel());
      SubCategoryViewOrEditPanel subCategoryViewOrEditPanel =
          new SubCategoryViewOrEditPanel(
              "subCategoryViewOrEditPanel", (IModel<Product>) getDefaultModel());
      Form<Product> productEditForm = new Form<Product>("productEditForm");
      productEditForm.setModel(
          new CompoundPropertyModel<Product>((IModel<Product>) getDefaultModel()));

      productEditForm.add(new TextField<String>("number"));
      productEditForm.add(new TextField<String>("name"));
      productEditForm.add(new TextArea<String>("description"));
      productEditForm.add(
          new UrlTextField(ITEM_URL, new PropertyModel<String>(getDefaultModelObject(), ITEM_URL)));
      productEditForm.add(new NumberTextField<Integer>("amount"));
      productEditForm.add(new NumberTextField<Integer>("discount"));
      productEditForm.add(new NumberTextField<Integer>("shippingCost"));
      productEditForm.add(new NumberTextField<Integer>("tax"));
      productEditForm.add(new NumberTextField<Integer>("itemHeight"));
      productEditForm.add(new TextField<String>("itemHeightUnit"));
      productEditForm.add(new NumberTextField<Integer>("itemLength"));
      productEditForm.add(new TextField<String>("itemLengthUnit"));
      productEditForm.add(new NumberTextField<Integer>("itemWeight"));
      productEditForm.add(new TextField<String>("itemWeightUnit"));
      productEditForm.add(new NumberTextField<Integer>("itemWidth"));
      productEditForm.add(new TextField<String>("itemWidthUnit"));
      productEditForm.add(new BootstrapCheckbox("bestsellers"));
      productEditForm.add(new BootstrapCheckbox("latestCollection"));
      productEditForm.add(new NumberTextField<Integer>("rating"));
      productEditForm.add(new BootstrapCheckbox("recommended"));
      productEditForm.add(new NumberTextField<Integer>("stock.maxQuantity"));
      productEditForm.add(new NumberTextField<Integer>("stock.minQuantity"));
      productEditForm.add(new NumberTextField<Integer>("stock.quantity"));

      add(productEditForm.setOutputMarkupId(true));
      add(
          contentViewOrEditPanel
              .add(contentViewOrEditPanel.new ContentEditFragement())
              .setOutputMarkupId(true));
      add(
          subCategoryViewOrEditPanel
              .add(subCategoryViewOrEditPanel.new SubCategoryEditFragement())
              .setOutputMarkupId(true));
      add(new NotificationPanel("feedback").hideAfter(Duration.seconds(5)).setOutputMarkupId(true));
      add(new CancelAjaxLink().setOutputMarkupId(true));
      add(new SaveAjaxButton(productEditForm).setOutputMarkupId(true));
      super.onInitialize();
    }
    @Override
    protected void onInitialize() {
      ContentViewOrEditPanel contentViewOrEditPanel =
          new ContentViewOrEditPanel("contentViewOrEditPanel", (IModel<Product>) getDefaultModel());
      SubCategoryViewOrEditPanel subCategoryViewOrEditPanel =
          new SubCategoryViewOrEditPanel(
              "subCategoryViewOrEditPanel", (IModel<Product>) getDefaultModel());
      Form<Product> productViewForm = new Form<Product>("productViewForm");
      productViewForm.setModel(
          new CompoundPropertyModel<Product>((IModel<Product>) getDefaultModel()));

      productViewForm.add(new Label("number"));
      productViewForm.add(new Label("name"));
      productViewForm.add(new Label("description"));
      productViewForm.add(new Label(ITEM_URL));
      productViewForm.add(new Label("amount"));
      productViewForm.add(new Label("discount"));
      productViewForm.add(new Label("shippingCost"));
      productViewForm.add(new Label("tax"));
      productViewForm.add(new Label("itemHeight"));
      productViewForm.add(new Label("itemHeightUnit"));
      productViewForm.add(new Label("itemLength"));
      productViewForm.add(new Label("itemLengthUnit"));
      productViewForm.add(new Label("itemWeight"));
      productViewForm.add(new Label("itemWeightUnit"));
      productViewForm.add(new Label("itemWidth"));
      productViewForm.add(new Label("itemWidthUnit"));
      productViewForm.add(new Label("bestsellers"));
      productViewForm.add(new Label("latestCollection"));
      productViewForm.add(new Label("rating"));
      productViewForm.add(new Label("recommended"));
      productViewForm.add(new Label("stock.maxQuantity"));
      productViewForm.add(new Label("stock.minQuantity"));
      productViewForm.add(new Label("stock.quantity"));

      add(new EditAjaxLink().setOutputMarkupId(true));
      add(productViewForm.setOutputMarkupId(true));
      add(
          contentViewOrEditPanel
              .add(contentViewOrEditPanel.new ContentViewFragement())
              .setOutputMarkupId(true));
      add(
          subCategoryViewOrEditPanel
              .add(subCategoryViewOrEditPanel.new SubCategoryViewFragement())
              .setOutputMarkupId(true));
      super.onInitialize();
    }
Esempio n. 19
0
  public ComparePage(PageParameters params) {
    super(params);
    Repository r = getRepository();
    RepositoryModel repository = getRepositoryModel();

    if (StringUtils.isEmpty(objectId)) {
      // seleciton form
      add(new Label("comparison").setVisible(false));
    } else {
      // active comparison
      Fragment comparison = new Fragment("comparison", "comparisonFragment", this);
      add(comparison);

      RevCommit fromCommit;
      RevCommit toCommit;

      String[] parts = objectId.split("\\.\\.");
      if (parts[0].startsWith("refs/") && parts[1].startsWith("refs/")) {
        // set the ref models
        fromRefId.setObject(parts[0]);
        toRefId.setObject(parts[1]);

        fromCommit = getCommit(r, fromRefId.getObject());
        toCommit = getCommit(r, toRefId.getObject());
      } else {
        // set the id models
        fromCommitId.setObject(parts[0]);
        toCommitId.setObject(parts[1]);

        fromCommit = getCommit(r, fromCommitId.getObject());
        toCommit = getCommit(r, toCommitId.getObject());
      }

      // prepare submodules
      getSubmodules(toCommit);

      final String startId = fromCommit.getId().getName();
      final String endId = toCommit.getId().getName();

      // commit ids
      fromCommitId.setObject(startId);
      toCommitId.setObject(endId);

      final DiffOutput diff = DiffUtils.getDiff(r, fromCommit, toCommit, DiffOutputType.HTML);

      // add compare diffstat
      int insertions = 0;
      int deletions = 0;
      for (PathChangeModel pcm : diff.stat.paths) {
        insertions += pcm.insertions;
        deletions += pcm.deletions;
      }
      comparison.add(new DiffStatPanel("diffStat", insertions, deletions));

      // compare page links
      //			comparison.add(new BookmarkablePageLink<Void>("patchLink", PatchPage.class,
      //					WicketUtils.newRangeParameter(repositoryName, fromCommitId.toString(),
      // toCommitId.getObject())));

      // display list of commits
      comparison.add(
          new LogPanel(
              "commitList", repositoryName, objectId, r, 0, 0, repository.showRemoteBranches));

      // changed paths list
      comparison.add(new CommitLegendPanel("commitLegend", diff.stat.paths));
      ListDataProvider<PathChangeModel> pathsDp =
          new ListDataProvider<PathChangeModel>(diff.stat.paths);
      DataView<PathChangeModel> pathsView =
          new DataView<PathChangeModel>("changedPath", pathsDp) {
            private static final long serialVersionUID = 1L;
            int counter;

            @Override
            public void populateItem(final Item<PathChangeModel> item) {
              final PathChangeModel entry = item.getModelObject();
              Label changeType = new Label("changeType", "");
              WicketUtils.setChangeTypeCssClass(changeType, entry.changeType);
              setChangeTypeTooltip(changeType, entry.changeType);
              item.add(changeType);
              item.add(new DiffStatPanel("diffStat", entry.insertions, entry.deletions, true));

              boolean hasSubmodule = false;
              String submodulePath = null;
              if (entry.isTree()) {
                // tree
                item.add(
                    new LinkPanel(
                        "pathName",
                        null,
                        entry.path,
                        TreePage.class,
                        WicketUtils.newPathParameter(repositoryName, endId, entry.path)));
              } else if (entry.isSubmodule()) {
                // submodule
                String submoduleId = entry.objectId;
                SubmoduleModel submodule = getSubmodule(entry.path);
                submodulePath = submodule.gitblitPath;
                hasSubmodule = submodule.hasSubmodule;

                // add relative link
                item.add(
                    new LinkPanel(
                        "pathName",
                        "list",
                        entry.path + " @ " + getShortObjectId(submoduleId),
                        "#" + entry.path));
              } else {
                // add relative link
                item.add(new LinkPanel("pathName", "list", entry.path, "#" + entry.path));
              }

              // quick links
              if (entry.isSubmodule()) {
                // submodule
                item.add(new ExternalLink("patch", "").setEnabled(false));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "view",
                            CommitPage.class,
                            WicketUtils.newObjectParameter(submodulePath, entry.objectId))
                        .setEnabled(hasSubmodule));
                item.add(new ExternalLink("blame", "").setEnabled(false));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "history",
                            HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
              } else {
                // tree or blob
                item.add(
                    new BookmarkablePageLink<Void>(
                            "patch",
                            PatchPage.class,
                            WicketUtils.newBlobDiffParameter(
                                repositoryName, startId, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "view",
                            BlobPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "raw",
                            RawPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "blame",
                            BlamePage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(
                            !entry.changeType.equals(ChangeType.ADD)
                                && !entry.changeType.equals(ChangeType.DELETE)));
                item.add(
                    new BookmarkablePageLink<Void>(
                            "history",
                            HistoryPage.class,
                            WicketUtils.newPathParameter(repositoryName, endId, entry.path))
                        .setEnabled(!entry.changeType.equals(ChangeType.ADD)));
              }
              WicketUtils.setAlternatingBackground(item, counter);
              counter++;
            }
          };
      comparison.add(pathsView);
      comparison.add(new Label("diffText", diff.content).setEscapeModelStrings(false));
    }

    //
    // ref selection form
    //
    SessionlessForm<Void> refsForm =
        new SessionlessForm<Void>("compareRefsForm", getClass(), getPageParameters()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String from = ComparePage.this.fromRefId.getObject();
            String to = ComparePage.this.toRefId.getObject();

            PageParameters params = WicketUtils.newRangeParameter(repositoryName, from, to);
            String relativeUrl = urlFor(ComparePage.class, params).toString();
            String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
            getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl));
          }
        };

    List<String> refs = new ArrayList<String>();
    for (RefModel ref : JGitUtils.getLocalBranches(r, true, -1)) {
      refs.add(ref.getName());
    }
    if (repository.showRemoteBranches) {
      for (RefModel ref : JGitUtils.getRemoteBranches(r, true, -1)) {
        refs.add(ref.getName());
      }
    }
    for (RefModel ref : JGitUtils.getTags(r, true, -1)) {
      refs.add(ref.getName());
    }
    refsForm.add(
        new DropDownChoice<String>("fromRef", fromRefId, refs).setEnabled(refs.size() > 0));
    refsForm.add(new DropDownChoice<String>("toRef", toRefId, refs).setEnabled(refs.size() > 0));
    add(refsForm);

    //
    // manual ids form
    //
    SessionlessForm<Void> idsForm =
        new SessionlessForm<Void>("compareIdsForm", getClass(), getPageParameters()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String from = ComparePage.this.fromCommitId.getObject();
            String to = ComparePage.this.toCommitId.getObject();

            PageParameters params = WicketUtils.newRangeParameter(repositoryName, from, to);
            String relativeUrl = urlFor(ComparePage.class, params).toString();
            String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
            getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl));
          }
        };

    TextField<String> fromIdField = new TextField<String>("fromId", fromCommitId);
    WicketUtils.setInputPlaceholder(fromIdField, getString("gb.from") + "...");
    idsForm.add(fromIdField);

    TextField<String> toIdField = new TextField<String>("toId", toCommitId);
    WicketUtils.setInputPlaceholder(toIdField, getString("gb.to") + "...");
    idsForm.add(toIdField);
    add(idsForm);

    r.close();
  }
  private Fragment getConnectorFragment(final TopologyNode node, final PageReference pageRef) {
    final Fragment fragment = new Fragment("actions", "connectorActions", this);

    final AjaxLink<String> delete =
        new IndicatingAjaxLink<String>("delete") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            try {
              connectorRestClient.delete(Long.class.cast(node.getKey()));
              target.appendJavaScript(String.format("jsPlumb.remove('%s');", node.getKey()));
              info(getString(Constants.OPERATION_SUCCEEDED));
            } catch (SyncopeClientException e) {
              error(getString(Constants.ERROR) + ": " + e.getMessage());
              LOG.error("While deleting resource {}", node.getKey(), e);
            }
            ((BasePage) getPage()).getNotificationPanel().refresh(target);
          }
        };

    fragment.add(delete);
    delete.add(new ConfirmationModalBehavior());

    MetaDataRoleAuthorizationStrategy.authorize(
        delete, ENABLE, StandardEntitlement.CONNECTOR_DELETE);

    final AjaxLink<String> create =
        new IndicatingAjaxLink<String>("create") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            final ResourceTO modelObject = new ResourceTO();
            modelObject.setConnector(Long.class.cast(node.getKey()));
            modelObject.setConnectorDisplayName(node.getDisplayName());

            final IModel<ResourceTO> model = new CompoundPropertyModel<>(modelObject);
            resourceModal.setFormModel(model);

            target.add(
                resourceModal.setContent(new ResourceModal<>(resourceModal, pageRef, model, true)));

            resourceModal.header(
                new Model<>(MessageFormat.format(getString("resource.new"), node.getKey())));

            MetaDataRoleAuthorizationStrategy.authorize(
                resourceModal.addSumbitButton(), ENABLE, StandardEntitlement.RESOURCE_CREATE);

            resourceModal.show(true);
          }
        };
    fragment.add(create);

    MetaDataRoleAuthorizationStrategy.authorize(
        create, ENABLE, StandardEntitlement.RESOURCE_CREATE);

    final AjaxLink<String> edit =
        new IndicatingAjaxLink<String>("edit") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            final ConnInstanceTO modelObject =
                connectorRestClient.read(Long.class.cast(node.getKey()));

            final IModel<ConnInstanceTO> model = new CompoundPropertyModel<>(modelObject);
            resourceModal.setFormModel(model);

            target.add(resourceModal.setContent(new ConnectorModal(resourceModal, pageRef, model)));

            resourceModal.header(
                new Model<>(MessageFormat.format(getString("connector.edit"), node.getKey())));

            MetaDataRoleAuthorizationStrategy.authorize(
                resourceModal.addSumbitButton(), ENABLE, StandardEntitlement.CONNECTOR_UPDATE);

            resourceModal.show(true);
          }
        };
    fragment.add(edit);

    MetaDataRoleAuthorizationStrategy.authorize(edit, ENABLE, StandardEntitlement.CONNECTOR_UPDATE);

    return fragment;
  }
Esempio n. 21
0
 private Fragment createLinkFragment(String value) {
   Fragment fragment = new Fragment("info", "linkFragment", DownloadPage.this);
   fragment.add(createManufacturerLink(value));
   return fragment;
 }
Esempio n. 22
0
  public UsersPanel(String wicketId, final boolean showAdmin) {
    super(wicketId);

    Fragment adminLinks = new Fragment("adminPanel", "adminLinks", this);
    adminLinks.add(new BookmarkablePageLink<Void>("newUser", EditUserPage.class));
    add(adminLinks.setVisible(showAdmin));

    final List<UserModel> users = app().users().getAllUsers();
    DataView<UserModel> usersView =
        new DataView<UserModel>("userRow", new ListDataProvider<UserModel>(users)) {
          private static final long serialVersionUID = 1L;
          private int counter;

          @Override
          protected void onBeforeRender() {
            super.onBeforeRender();
            counter = 0;
          }

          @Override
          public void populateItem(final Item<UserModel> item) {
            final UserModel entry = item.getModelObject();
            LinkPanel editLink =
                new LinkPanel(
                    "username",
                    "list",
                    entry.username,
                    EditUserPage.class,
                    WicketUtils.newUsernameParameter(entry.username));
            WicketUtils.setHtmlTooltip(
                editLink, getString("gb.edit") + " " + entry.getDisplayName());
            item.add(editLink);

            if (StringUtils.isEmpty(entry.displayName)) {
              item.add(new Label("displayName").setVisible(false));
            } else {
              editLink =
                  new LinkPanel(
                      "displayName",
                      "list",
                      entry.getDisplayName(),
                      EditUserPage.class,
                      WicketUtils.newUsernameParameter(entry.username));
              WicketUtils.setHtmlTooltip(
                  editLink, getString("gb.edit") + " " + entry.getDisplayName());
              item.add(editLink);
            }

            if (StringUtils.isEmpty(entry.emailAddress)) {
              item.add(new Label("emailAddress").setVisible(false));
            } else {
              editLink =
                  new LinkPanel(
                      "emailAddress",
                      "list",
                      entry.emailAddress,
                      EditUserPage.class,
                      WicketUtils.newUsernameParameter(entry.username));
              WicketUtils.setHtmlTooltip(
                  editLink, getString("gb.edit") + " " + entry.getDisplayName());
              item.add(editLink);
            }

            item.add(
                new Label(
                    "accountType", entry.accountType.name() + (entry.canAdmin() ? ", admin" : "")));
            item.add(new Label("teams", entry.teams.size() > 0 ? ("" + entry.teams.size()) : ""));
            item.add(
                new Label(
                    "repositories",
                    entry.permissions.size() > 0 ? ("" + entry.permissions.size()) : ""));
            Fragment userLinks = new Fragment("userLinks", "userAdminLinks", this);
            userLinks.add(
                new BookmarkablePageLink<Void>(
                    "editUser",
                    EditUserPage.class,
                    WicketUtils.newUsernameParameter(entry.username)));
            Link<Void> deleteLink =
                new Link<Void>("deleteUser") {

                  private static final long serialVersionUID = 1L;

                  @Override
                  public void onClick() {
                    if (app().users().deleteUser(entry.username)) {
                      users.remove(entry);
                      info(MessageFormat.format(getString("gb.userDeleted"), entry.username));
                    } else {
                      error(MessageFormat.format(getString("gb.deleteUserFailed"), entry.username));
                    }
                  }
                };
            deleteLink.add(
                new JavascriptEventConfirmation(
                    "onclick", MessageFormat.format(getString("gb.deleteUser"), entry.username)));
            userLinks.add(deleteLink);
            item.add(userLinks);

            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
          }
        };
    add(usersView.setVisible(showAdmin));
  }
  private Fragment getResurceFragment(final TopologyNode node, final PageReference pageRef) {
    final Fragment fragment = new Fragment("actions", "resourceActions", this);

    final AjaxLink<String> delete =
        new IndicatingAjaxLink<String>("delete") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            try {
              resourceRestClient.delete(node.getKey().toString());
              target.appendJavaScript(String.format("jsPlumb.remove('%s');", node.getKey()));
              info(getString(Constants.OPERATION_SUCCEEDED));
            } catch (SyncopeClientException e) {
              error(getString(Constants.ERROR) + ": " + e.getMessage());
              LOG.error("While deleting resource {}", node.getKey(), e);
            }
            ((BasePage) getPage()).getNotificationPanel().refresh(target);
          }
        };
    fragment.add(delete);

    delete.add(new ConfirmationModalBehavior());

    MetaDataRoleAuthorizationStrategy.authorize(
        delete, ENABLE, StandardEntitlement.RESOURCE_DELETE);

    final AjaxLink<String> edit =
        new IndicatingAjaxLink<String>("edit") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            final ResourceTO modelObject = resourceRestClient.read(node.getKey().toString());

            final IModel<ResourceTO> model = new CompoundPropertyModel<>(modelObject);
            resourceModal.setFormModel(model);

            target.add(
                resourceModal.setContent(
                    new ResourceModal<>(resourceModal, pageRef, model, false)));

            resourceModal.header(
                new Model<>(MessageFormat.format(getString("resource.edit"), node.getKey())));

            MetaDataRoleAuthorizationStrategy.authorize(
                resourceModal.addSumbitButton(), ENABLE, StandardEntitlement.RESOURCE_UPDATE);

            resourceModal.show(true);
          }
        };
    fragment.add(edit);
    MetaDataRoleAuthorizationStrategy.authorize(edit, ENABLE, StandardEntitlement.RESOURCE_UPDATE);

    final AjaxLink<String> propagation =
        new IndicatingAjaxLink<String>("propagation") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          @SuppressWarnings("unchecked")
          public void onClick(final AjaxRequestTarget target) {
            target.add(
                taskModal.setContent(new PropagationTasks(pageRef, node.getKey().toString())));
            taskModal.header(new ResourceModel("task.propagation.list", "Propagation tasks"));
            taskModal.show(true);
          }
        };
    fragment.add(propagation);
    MetaDataRoleAuthorizationStrategy.authorize(propagation, ENABLE, StandardEntitlement.TASK_LIST);

    final AjaxLink<String> synchronization =
        new IndicatingAjaxLink<String>("synchronization") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            target.add(taskModal.setContent(new SyncTasks(pageRef, node.getKey().toString())));
            taskModal.header(
                new ResourceModel("task.synchronization.list", "Synchronization tasks"));
            taskModal.show(true);
          }
        };
    fragment.add(synchronization);
    MetaDataRoleAuthorizationStrategy.authorize(
        synchronization, ENABLE, StandardEntitlement.TASK_LIST);

    final AjaxLink<String> push =
        new IndicatingAjaxLink<String>("push") {

          private static final long serialVersionUID = 3776750333491622263L;

          @Override
          public void onClick(final AjaxRequestTarget target) {
            target.add(taskModal.setContent(new PushTasks(pageRef, node.getKey().toString())));
            taskModal.header(new ResourceModel("task.push.list", "Push tasks"));
            taskModal.show(true);
          }
        };
    fragment.add(push);
    MetaDataRoleAuthorizationStrategy.authorize(push, ENABLE, StandardEntitlement.TASK_LIST);

    return fragment;
  }
Esempio n. 24
0
  private void addPreferences(UserModel user) {
    // add preferences
    Form<Void> prefs = new Form<Void>("prefsForm");

    List<Language> languages =
        Arrays.asList(
            new Language("Deutsch", "de"),
            new Language("English", "en"),
            new Language("Español", "es"),
            new Language("Français", "fr"),
            new Language("Italiano", "it"),
            new Language("日本語", "ja"),
            new Language("한국말", "ko"),
            new Language("Nederlands", "nl"),
            new Language("Norsk", "no"),
            new Language("Język Polski", "pl"),
            new Language("Português", "pt_BR"),
            new Language("簡體中文", "zh_CN"),
            new Language("正體中文", "zh_TW"));

    Locale locale = user.getPreferences().getLocale();
    if (locale == null) {
      // user has not specified language preference
      // try server default preference
      String lc = app().settings().getString(Keys.web.forceDefaultLocale, null);
      if (StringUtils.isEmpty(lc)) {
        // server default language is not configured
        // try browser preference
        Locale sessionLocale = GitBlitWebSession.get().getLocale();
        if (sessionLocale != null) {
          locale = sessionLocale;
        }
      } else {

      }
    }

    Language preferredLanguage = null;
    if (locale != null) {
      String localeCode = locale.getLanguage();
      if (!StringUtils.isEmpty(locale.getCountry())) {
        localeCode += "_" + locale.getCountry();
      }

      for (Language language : languages) {
        if (language.code.equals(localeCode)) {
          // language_COUNTRY match
          preferredLanguage = language;
        } else if (preferredLanguage != null && language.code.startsWith(locale.getLanguage())) {
          // language match
          preferredLanguage = language;
        }
      }
    }

    final IModel<String> displayName = Model.of(user.getDisplayName());
    final IModel<String> emailAddress =
        Model.of(user.emailAddress == null ? "" : user.emailAddress);
    final IModel<Language> language = Model.of(preferredLanguage);
    final IModel<Boolean> emailMeOnMyTicketChanges =
        Model.of(user.getPreferences().isEmailMeOnMyTicketChanges());
    final IModel<Transport> transport = Model.of(user.getPreferences().getTransport());

    prefs.add(
        new TextOption(
                "displayName",
                getString("gb.displayName"),
                getString("gb.displayNameDescription"),
                displayName)
            .setVisible(app().authentication().supportsDisplayNameChanges(user)));

    prefs.add(
        new TextOption(
                "emailAddress",
                getString("gb.emailAddress"),
                getString("gb.emailAddressDescription"),
                emailAddress)
            .setVisible(app().authentication().supportsEmailAddressChanges(user)));

    prefs.add(
        new ChoiceOption<Language>(
            "language",
            getString("gb.languagePreference"),
            getString("gb.languagePreferenceDescription"),
            language,
            languages));

    prefs.add(
        new BooleanOption(
                "emailMeOnMyTicketChanges",
                getString("gb.emailMeOnMyTicketChanges"),
                getString("gb.emailMeOnMyTicketChangesDescription"),
                emailMeOnMyTicketChanges)
            .setVisible(app().notifier().isSendingMail()));

    List<Transport> availableTransports = new ArrayList<>();
    if (app().services().isServingSSH()) {
      availableTransports.add(Transport.SSH);
    }
    if (app().services().isServingHTTP()) {
      availableTransports.add(Transport.HTTP);
    }
    if (app().services().isServingHTTPS()) {
      availableTransports.add(Transport.HTTPS);
    }
    if (app().services().isServingGIT()) {
      availableTransports.add(Transport.GIT);
    }

    prefs.add(
        new ChoiceOption<Transport>(
            "transport",
            getString("gb.transportPreference"),
            getString("gb.transportPreferenceDescription"),
            transport,
            availableTransports));

    prefs.add(
        new AjaxButton("save") {

          private static final long serialVersionUID = 1L;

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

            UserModel user = GitBlitWebSession.get().getUser();

            user.displayName = displayName.getObject();
            user.emailAddress = emailAddress.getObject();

            Language lang = language.getObject();
            if (lang != null) {
              user.getPreferences().setLocale(lang.code);
            }

            user.getPreferences().setEmailMeOnMyTicketChanges(emailMeOnMyTicketChanges.getObject());
            user.getPreferences().setTransport(transport.getObject());

            try {
              app().gitblit().reviseUser(user.username, user);

              setRedirect(true);
              setResponsePage(UserPage.class, WicketUtils.newUsernameParameter(user.username));
            } catch (GitBlitException e) {
              // logger.error("Failed to update user " + user.username, e);
              // error(getString("gb.failedToUpdateUser"), false);
            }
          }
        });

    // add the preferences tab
    add(new Fragment("preferencesLink", "preferencesLinkFragment", this).setRenderBodyOnly(true));
    Fragment fragment = new Fragment("preferencesTab", "preferencesTabFragment", this);
    fragment.add(prefs);
    add(fragment.setRenderBodyOnly(true));
  }
Esempio n. 25
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);
  }
Esempio n. 26
0
  public SummaryPage(PageParameters params) {
    super(params);

    int numberCommits = GitBlit.getInteger(Keys.web.summaryCommitCount, 20);
    if (numberCommits <= 0) {
      numberCommits = 20;
    }
    int numberRefs = GitBlit.getInteger(Keys.web.summaryRefsCount, 5);

    Repository r = getRepository();
    RepositoryModel model = getRepositoryModel();

    List<Metric> metrics = null;
    Metric metricsTotal = null;
    if (!model.skipSummaryMetrics && GitBlit.getBoolean(Keys.web.generateActivityGraph, true)) {
      metrics = GitBlit.self().getRepositoryDefaultMetrics(model, r);
      metricsTotal = metrics.remove(0);
    }

    addSyndicationDiscoveryLink();

    // repository description
    add(new Label("repositoryDescription", getRepositoryModel().description));
    add(new Label("repositoryOwner", getRepositoryModel().owner));

    add(
        WicketUtils.createTimestampLabel(
            "repositoryLastChange", JGitUtils.getLastChange(r), getTimeZone()));
    if (metricsTotal == null) {
      add(new Label("branchStats", ""));
    } else {
      add(
          new Label(
              "branchStats",
              MessageFormat.format(
                  "{0} commits and {1} tags in {2}",
                  metricsTotal.count,
                  metricsTotal.tag,
                  TimeUtils.duration(metricsTotal.duration))));
    }
    add(
        new BookmarkablePageLink<Void>(
            "metrics", MetricsPage.class, WicketUtils.newRepositoryParameter(repositoryName)));

    List<String> repositoryUrls = new ArrayList<String>();

    if (GitBlit.getBoolean(Keys.git.enableGitServlet, true)) {
      AccessRestrictionType accessRestriction = getRepositoryModel().accessRestriction;
      switch (accessRestriction) {
        case NONE:
          add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
          break;
        case PUSH:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "lock_go_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        case CLONE:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "lock_pull_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        case VIEW:
          add(
              WicketUtils.newImage(
                  "accessRestrictionIcon",
                  "shield_16x16.png",
                  getAccessRestrictions().get(accessRestriction)));
          break;
        default:
          add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
      }
      // add the Gitblit repository url
      repositoryUrls.add(getRepositoryUrl(getRepositoryModel()));
    } else {
      add(WicketUtils.newClearPixel("accessRestrictionIcon").setVisible(false));
    }
    repositoryUrls.addAll(GitBlit.self().getOtherCloneUrls(repositoryName));

    String primaryUrl = ArrayUtils.isEmpty(repositoryUrls) ? "" : repositoryUrls.remove(0);
    add(new RepositoryUrlPanel("repositoryCloneUrl", primaryUrl));

    add(
        new Label("otherUrls", StringUtils.flattenStrings(repositoryUrls, "<br/>"))
            .setEscapeModelStrings(false));

    add(
        new LogPanel(
            "commitsPanel", repositoryName, getRepositoryModel().HEAD, r, numberCommits, 0));
    add(new TagsPanel("tagsPanel", repositoryName, r, numberRefs).hideIfEmpty());
    add(new BranchesPanel("branchesPanel", getRepositoryModel(), r, numberRefs).hideIfEmpty());

    if (getRepositoryModel().showReadme) {
      String htmlText = null;
      String readme = null;
      try {
        RevCommit head = JGitUtils.getCommit(r, null);
        List<String> markdownExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
        List<PathModel> paths = JGitUtils.getFilesInPath(r, null, head);
        for (PathModel path : paths) {
          if (!path.isTree()) {
            String name = path.name.toLowerCase();

            if (name.startsWith("readme")) {
              if (name.indexOf('.') > -1) {
                String ext = name.substring(name.lastIndexOf('.') + 1);
                if (markdownExtensions.contains(ext)) {
                  readme = path.name;
                  break;
                }
              }
            }
          }
        }
        if (!StringUtils.isEmpty(readme)) {
          String markdownText = JGitUtils.getStringContent(r, head.getTree(), readme);
          htmlText = MarkdownUtils.transformMarkdown(markdownText);
        }
      } catch (ParseException p) {
        error(p.getMessage());
      }
      Fragment fragment = new Fragment("readme", "markdownPanel");
      fragment.add(new Label("readmeFile", readme));
      // Add the html to the page
      Component content = new Label("readmeContent", htmlText).setEscapeModelStrings(false);
      fragment.add(content.setVisible(!StringUtils.isEmpty(htmlText)));
      add(fragment);
    } else {
      add(new Label("readme").setVisible(false));
    }

    // Display an activity line graph
    insertActivityGraph(metrics);
  }
Esempio n. 27
0
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
      String message = readMarkdown(messageSource, "login.mkd");
      Component repositoriesMessage = new Label("repositoriesMessage", message);
      add(repositoriesMessage.setEscapeModelStrings(false));
      add(new Label("activity").setVisible(false));
      add(new Label("repositoryTabs").setVisible(false));
      return;
    }

    // Load the markdown welcome message
    String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
    String message = readMarkdown(messageSource, "welcome.mkd");
    Component repositoriesMessage =
        new Label("repositoriesMessage", message)
            .setEscapeModelStrings(false)
            .setVisible(message.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }

    // parameters
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -1 * daysBack);
    Date minimumDate = c.getTime();

    // build repo lists
    List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
    List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
    List<RepositoryModel> active = new ArrayList<RepositoryModel>();

    for (RepositoryModel model : getRepositoryModels()) {
      if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
        owned.add(model);
      }

      if (user.getPreferences().isStarredRepository(model.name)) {
        starred.add(model);
      }

      if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
        active.add(model);
      }
    }

    Comparator<RepositoryModel> lastUpdateSort =
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            return o2.lastChange.compareTo(o1.lastChange);
          }
        };

    Collections.sort(owned, lastUpdateSort);
    Collections.sort(starred, lastUpdateSort);
    Collections.sort(active, lastUpdateSort);

    String activityTitle;
    Set<RepositoryModel> feed = new HashSet<RepositoryModel>();
    feed.addAll(starred);
    feed.addAll(owned);
    if (feed.isEmpty()) {
      // no starred or owned, go with recent activity
      activityTitle = getString("gb.recentActivity");
      feed.addAll(active);
    } else if (starred.isEmpty()) {
      // no starred, owned repos feed
      activityTitle = getString("gb.owned");
    } else if (owned.isEmpty()) {
      // no owned, starred repos feed
      activityTitle = getString("gb.starred");
    } else {
      // starred and owned repositories
      activityTitle = getString("gb.starredAndOwned");
    }

    addActivity(user, feed, activityTitle, daysBack);

    Fragment repositoryTabs;
    if (UserModel.ANONYMOUS.equals(user)) {
      repositoryTabs = new Fragment("repositoryTabs", "anonymousTabsFragment", this);
    } else {
      repositoryTabs = new Fragment("repositoryTabs", "authenticatedTabsFragment", this);
    }

    add(repositoryTabs);

    // projects list
    List<ProjectModel> projects = GitBlit.self().getProjectModels(getRepositoryModels(), false);
    repositoryTabs.add(new FilterableProjectList("projects", projects));

    // active repository list
    if (active.isEmpty()) {
      repositoryTabs.add(new Label("active").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("active", active);
      repoList.setTitle(getString("gb.activeRepositories"), "icon-time");
      repositoryTabs.add(repoList);
    }

    // starred repository list
    if (ArrayUtils.isEmpty(starred)) {
      repositoryTabs.add(new Label("starred").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("starred", starred);
      repoList.setTitle(getString("gb.starredRepositories"), "icon-star");
      repositoryTabs.add(repoList);
    }

    // owned repository list
    if (ArrayUtils.isEmpty(owned)) {
      repositoryTabs.add(new Label("owned").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("owned", owned);
      repoList.setTitle(getString("gb.myRepositories"), "icon-user");
      repoList.setAllowCreate(user.canCreate() || user.canAdmin());
      repositoryTabs.add(repoList);
    }
  }
Esempio n. 28
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public GeoServerHomePage() {
    GeoServer gs = getGeoServer();
    ContactInfo contact = gs.getGlobal().getSettings().getContact();

    // add some contact info
    add(
        new ExternalLink("contactURL", contact.getOnlineResource())
            .add(new Label("contactName", contact.getContactOrganization())));
    {
      String version = String.valueOf(new ResourceModel("version").getObject());
      String contactEmail = contact.getContactEmail();
      HashMap<String, String> params = new HashMap<String, String>();
      params.put("version", version);
      params.put("contactEmail", (contactEmail == null ? "*****@*****.**" : contactEmail));
      Label label =
          new Label(
              "footerMessage",
              new StringResourceModel("GeoServerHomePage.footer", this, new Model(params)));
      label.setEscapeModelStrings(false);
      add(label);
    }

    Authentication auth = getSession().getAuthentication();
    if (isAdmin(auth)) {
      Stopwatch sw = Stopwatch.createStarted();
      Fragment f = new Fragment("catalogLinks", "catalogLinksFragment", this);
      Catalog catalog = getCatalog();

      NumberFormat numberFormat = NumberFormat.getIntegerInstance(getLocale());
      numberFormat.setGroupingUsed(true);

      final Filter allLayers = acceptAll();
      final Filter allStores = acceptAll();
      final Filter allWorkspaces = acceptAll();

      final int layerCount = catalog.count(LayerInfo.class, allLayers);
      final int storesCount = catalog.count(StoreInfo.class, allStores);
      final int wsCount = catalog.count(WorkspaceInfo.class, allWorkspaces);

      f.add(
          new BookmarkablePageLink("layersLink", LayerPage.class)
              .add(new Label("nlayers", numberFormat.format(layerCount))));
      f.add(new BookmarkablePageLink("addLayerLink", NewLayerPage.class));

      f.add(
          new BookmarkablePageLink("storesLink", StorePage.class)
              .add(new Label("nstores", numberFormat.format(storesCount))));
      f.add(new BookmarkablePageLink("addStoreLink", NewDataPage.class));

      f.add(
          new BookmarkablePageLink("workspacesLink", WorkspacePage.class)
              .add(new Label("nworkspaces", numberFormat.format(wsCount))));
      f.add(new BookmarkablePageLink("addWorkspaceLink", WorkspaceNewPage.class));
      add(f);

      sw.stop();
    } else {
      Label placeHolder = new Label("catalogLinks");
      placeHolder.setVisible(false);
      add(placeHolder);
    }

    final IModel<List<GeoServerHomePageContentProvider>> contentProviders;
    contentProviders = getContentProviders(GeoServerHomePageContentProvider.class);
    ListView<GeoServerHomePageContentProvider> contentView =
        new ListView<GeoServerHomePageContentProvider>("contributedContent", contentProviders) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void populateItem(ListItem<GeoServerHomePageContentProvider> item) {
            GeoServerHomePageContentProvider provider = item.getModelObject();
            Component extraContent = provider.getPageBodyComponent("contentList");
            if (null == extraContent) {
              Label placeHolder = new Label("contentList");
              placeHolder.setVisible(false);
              extraContent = placeHolder;
            }
            item.add(extraContent);
          }
        };
    add(contentView);

    final IModel<List<CapabilitiesHomePageLinkProvider>> capsProviders;
    capsProviders = getContentProviders(CapabilitiesHomePageLinkProvider.class);

    ListView<CapabilitiesHomePageLinkProvider> capsView =
        new ListView<CapabilitiesHomePageLinkProvider>("providedCaps", capsProviders) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void populateItem(ListItem<CapabilitiesHomePageLinkProvider> item) {
            CapabilitiesHomePageLinkProvider provider = item.getModelObject();
            Component capsList = provider.getCapabilitiesComponent("capsList");
            item.add(capsList);
          }
        };
    add(capsView);
  }
Esempio n. 29
0
 @Override
 public void buildNew(Fragment fragment) {
   fragment.add(new TextField<String>("newName", new PropertyModel<String>(this, "newName")));
   fragment.add(new TextField<String>("newValue", new PropertyModel<String>(this, "newValue")));
 }
Esempio n. 30
0
  /**
   * Construct a new YUIDateField.
   *
   * @param id the Wicket id for the editor.
   * @param model the model.
   * @param metaData the meta data for the property.
   * @param viewOnly true if the component should be view-only.
   */
  public YUIDateField(String id, IModel<Date> model, ElementMetaData metaData, boolean viewOnly) {
    super(id, model, metaData, viewOnly);

    type = metaData.getPropertyType();
    boolean displayTz = false;
    Component metaDataComponent = metaData.getBeanMetaData().getComponent();
    Localizer localizer = metaDataComponent.getLocalizer();
    if (Time.class.isAssignableFrom(type)
        || java.sql.Date.class.isAssignableFrom(type)
        || Date.class.isAssignableFrom(type)
        || Timestamp.class.isAssignableFrom(type)) {
      fmt =
          localizer.getString(
              DATE_TIME_FIELD_PREFIX + "date" + FORMAT_SUFFIX, metaDataComponent, DATE_FMT_STR);
    } else if (Calendar.class.isAssignableFrom(type)) {
      fmt =
          viewOnly
              ? localizer.getString(
                  DATE_TIME_FIELD_PREFIX + "datetz" + FORMAT_SUFFIX,
                  metaDataComponent,
                  DATE_ZONE_FMT_STR)
              : localizer.getString(
                  DATE_TIME_FIELD_PREFIX + "date" + FORMAT_SUFFIX, metaDataComponent, DATE_FMT_STR);
      displayTz = true;
    } else {
      throw new RuntimeException("YUIDateField does not handle " + type);
    }

    String customFmt = getFormat();
    if (customFmt != null) {
      fmt = customFmt;
    }

    Fragment fragment;
    if (viewOnly) {
      fragment = new Fragment("frag", "viewer");
      fragment.add(DateLabel.withConverter("date", model, new InternalDateConverter()));
    } else {
      fragment = new Fragment("frag", "editor");

      FormComponent dateField =
          DateTextField.withConverter("dateTextField", model, new InternalDateConverter());
      setFieldParameters(dateField);
      fragment.add(dateField);

      dateField.add(
          new DatePicker() {
            private static final long serialVersionUID = 1L;

            @Override
            protected boolean enableMonthYearSelection() {
              return false;
            }

            @Override
            protected CharSequence getIconUrl() {
              return RequestCycle.get()
                  .urlFor(new ResourceReference(YUIDateField.class, "calendar.gif"));
            }
          });

      if (displayTz) {
        DateLabel tzLabel = DateLabel.withConverter("timezone", model, new TimeZoneConverter());
        fragment.add(tzLabel);
      } else {
        fragment.add(new Label("timezone", "").setVisible(false));
      }
    }

    add(fragment);
  }