Example usage for org.apache.wicket.ajax.markup.html AjaxLink add

List of usage examples for org.apache.wicket.ajax.markup.html AjaxLink add

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.markup.html AjaxLink add.

Prototype

public MarkupContainer add(final Component... children) 

Source Link

Document

Adds the child component(s) to this container.

Usage

From source file:org.hippoecm.frontend.plugins.cms.admin.plugins.ChangePasswordShortcutPlugin.java

License:Apache License

public ChangePasswordShortcutPlugin(final IPluginContext context, final IPluginConfig config) {
    super(context, config);

    notificationPeriod = (long) getPluginConfig().getDouble("passwordexpirationnotificationdays", 3)
            * ONE_DAY_MS;/*from  ww w. ja va  2  s  . c o m*/

    final UserSession session = UserSession.get();
    // password max age is defined on the /hippo:configuration/hippo:security node
    try {
        Node securityNode = session.getRootNode().getNode(SECURITY_PATH);
        if (securityNode.hasProperty(HippoNodeType.HIPPO_PASSWORDMAXAGEDAYS)) {
            passwordMaxAge = (long) (securityNode.getProperty(HippoNodeType.HIPPO_PASSWORDMAXAGEDAYS)
                    .getDouble() * ONE_DAY_MS);
        }
    } catch (RepositoryException e) {
        log.error("Failed to determine configured password maximum age", e);
    }

    username = session.getJcrSession().getUserID();
    user = new User(username);

    AjaxLink link = new AjaxLink("link") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            IDialogService dialogService = getDialogService();
            if (user != null && canChangePassword()) {
                currentPassword = newPassword = checkPassword = "";
                dialogService.show(new ChangePasswordDialog());
            } else {
                dialogService.show(new CannotChangePasswordDialog());
            }
        }
    };
    add(link);

    final IModel<String> labelModel = new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            if (user.isPasswordExpired()) {
                return translate("password-is-expired");
            } else if (isPasswordAboutToExpire(user)) {
                final long expirationTime = user.getPasswordExpirationTime();
                final Duration expirationDuration = Duration
                        .valueOf(expirationTime - System.currentTimeMillis());
                String expiration = expirationDuration.toString(getLocale());

                final Matcher matcher = EXPIRATION_PATTERN.matcher(expiration);
                if (matcher.matches()) {
                    final String expirationMatch = matcher.group(1);
                    expiration = expiration.replace(expirationMatch, translate(expirationMatch));
                }

                final StringResourceModel model = new StringResourceModel("password-about-to-expire",
                        ChangePasswordShortcutPlugin.this, null, null, expiration);
                return model.getObject();
            }
            return StringUtils.EMPTY;
        }
    };
    label = new Label("label", labelModel) {
        @Override
        public boolean isVisible() {
            return StringUtils.isNotEmpty(labelModel.getObject());
        }
    };
    label.setOutputMarkupId(true);
    add(label);

    final HippoIcon icon = HippoIcon.fromSprite("change-password-icon", Icon.PENCIL_SQUARE);
    link.add(icon);
}

From source file:org.hippoecm.frontend.plugins.cms.admin.widgets.AjaxLinkLabel.java

License:Apache License

public AjaxLinkLabel(final String id, final IModel<String> model) {
    super(id, model);

    final AjaxLink link = new AjaxLink("link") {
        @Override//from   ww w. ja  v a  2 s. c  o  m
        public void onClick(final AjaxRequestTarget target) {
            AjaxLinkLabel.this.onClick(target);
        }
    };
    link.add(new Label("label", model));
    add(link);
}

From source file:org.hippoecm.frontend.plugins.cms.browse.section.SearchingSectionPlugin.java

License:Apache License

public SearchingSectionPlugin(IPluginContext context, IPluginConfig config) {
    super(context, config);

    rootPath = config.getString("model.folder.root", "/");
    rootModel = new JcrNodeModel(rootPath);
    scopeModel = new JcrNodeModel(rootPath);

    collection = new DocumentCollection();

    folderService = new FolderModelService(config, rootModel);
    collection.setFolder(folderService.getModel());

    collection.addListener(this::redrawSearch);

    final Form form = new Form("form") {

        @Override//from w  ww  .  j a va 2s  . c  o  m
        protected void onBeforeRender() {
            redrawSearch = false;
            super.onBeforeRender();
        }

        @Override
        protected void onSubmit() {
        }
    };
    form.setOutputMarkupId(true);

    TextField<String> tx = new SubmittingTextField("searchBox", PropertyModel.of(this, "query"));
    tx.setLabel(Model.of(getString("placeholder")));
    form.add(tx);

    final AjaxSubmitLink browseLink = new AjaxSubmitLink("toggle") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (hasSearchResult()) {
                collection.setSearchResult(NO_RESULTS);
                query = "";
            } else {
                updateSearch(true);
            }
        }
    };
    browseLink.add(createSearchIcon("search-icon", collection));
    form.add(browseLink);

    WebMarkupContainer scopeContainer = new WebMarkupContainer("scope-container") {
        @Override
        public boolean isVisible() {
            return hasSearchResult() && !rootModel.equals(scopeModel);
        }
    };

    final AjaxLink scopeLink = new AjaxLink("scope") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            folderService.setModel(scopeModel);
        }

        @Override
        public boolean isEnabled() {
            return hasSearchResult() && !rootModel.equals(scopeModel)
                    && !scopeModel.equals(folderService.getModel());
        }

    };
    scopeContainer.add(CssClass.append(new SearchScopeModel(scopeLink)));
    scopeLink.add(new Label("scope-label", new LoadableDetachableModel<String>() {
        @Override
        protected String load() {
            return new NodeNameModel(scopeModel).getObject();
        }

    }).setRenderBodyOnly(true));
    scopeContainer.add(scopeLink);
    form.add(scopeContainer);

    WebMarkupContainer allContainer = new WebMarkupContainer("all-container") {
        @Override
        public boolean isVisible() {
            return hasSearchResult();
        }
    };
    final AjaxLink allLink = new AjaxLink("all") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            IModel<Node> backup = folderService.getModel();
            folderService.setModel(rootModel);
            scopeModel = backup;
        }

        @Override
        public boolean isEnabled() {
            return hasSearchResult() && !rootModel.equals(folderService.getModel());
        }
    };
    allContainer.add(CssClass.append(new SearchScopeModel(allLink)));
    allContainer.add(allLink);
    form.add(allContainer);

    sectionTop = new WebMarkupContainer("section-top");
    sectionTop.setOutputMarkupId(true);
    sectionTop.add(CssClass.append(new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            return hasSearchResult() ? "search-result" : "";
        }
    }));
    sectionTop.add(form);
    add(sectionTop);
}

From source file:org.hippoecm.frontend.plugins.cms.dashboard.BrowseLink.java

License:Apache License

public BrowseLink(final IPluginContext context, final IPluginConfig config, final String id,
        final BrowseLinkTarget browseLinkTarget, final IModel<String> labelModel) {
    super(id);/*from   ww  w . ja  v  a2s . c  o  m*/

    AjaxLink<Void> link = new AjaxLink<Void>("link") {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(AjaxRequestTarget target) {
            final JcrNodeModel nodeModel = browseLinkTarget.getBrowseModel();
            final String browserId = config.getString("browser.id");
            final IBrowseService browseService = context.getService(browserId, IBrowseService.class);
            if (browseService != null) {
                browseService.browse(nodeModel);
            } else {
                log.warn("no browse service found with id '{}', cannot browse to '{}'", browserId,
                        JcrUtils.getNodePathQuietly(nodeModel.getNode()));
            }
        }

        @Override
        public boolean isEnabled() {
            return browseLinkTarget.getBrowseModel() != null;
        }
    };
    add(link);

    Label linkLabel = new Label("label", labelModel);
    linkLabel.setEscapeModelStrings(false);
    link.add(linkLabel);

    link.add(TitleAttribute.set(new PropertyModel<>(browseLinkTarget, "displayPath")));
}

From source file:org.hippoecm.frontend.plugins.cms.dashboard.todo.TodoLink.java

License:Apache License

public TodoLink(final IPluginContext context, final IPluginConfig config, final String id,
        final BrowseLinkTarget browseLinkTarget, final IModel<String> userLabelModel,
        final IModel<String> operationLabelModel, final IModel<Calendar> creationDateModel) {
    super(id);/*from ww  w.  ja va2 s.  c o  m*/

    AjaxLink<Void> link = new AjaxLink<Void>("link") {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(AjaxRequestTarget target) {
            final JcrNodeModel nodeModel = browseLinkTarget.getBrowseModel();
            final String browserId = config.getString("browser.id");
            final IBrowseService browseService = context.getService(browserId, IBrowseService.class);
            if (browseService != null) {
                browseService.browse(nodeModel);
            } else {
                log.warn("no browse service found with id '{}', cannot browse to '{}'", browserId,
                        JcrUtils.getNodePathQuietly(nodeModel.getNode()));
            }
        }

        @Override
        public boolean isEnabled() {
            return browseLinkTarget.getBrowseModel() != null;
        }
    };
    add(link);
    link.add(TitleAttribute.set(new PropertyModel<>(browseLinkTarget, "displayPath")));

    Label userLabel = new Label("username", userLabelModel);
    link.add(userLabel);

    Label operationLabel = new Label("operation", operationLabelModel);
    operationLabel.setEscapeModelStrings(false);
    link.add(operationLabel);

    // Set the creation date or an empty string when no creation date is available
    final String creationDate = creationDateModel != null && creationDateModel.getObject() != null
            ? dateFormatShort.format(creationDateModel.getObject().getTime())
            : StringUtils.EMPTY;
    link.add(new Label("creationDate", new Model<>(creationDate)));

    Label documentLabel = new Label("document", "\"" + browseLinkTarget.getName() + "\"");
    link.add(documentLabel);
}

From source file:org.hippoecm.frontend.plugins.cms.logout.LogoutLink.java

License:Apache License

public LogoutLink(final String id, final ILogoutService logoutService) {
    super(id);//w  w  w .j  a  va 2 s .c  o m

    final AjaxLink link = new AjaxLink("logout-link") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            logoutService.logout();
        }
    };
    add(link);

    link.add(HippoIcon.fromSprite("logoutIcon", Icon.ARROW_RIGHT_SQUARE, IconSize.S));
}

From source file:org.hippoecm.frontend.plugins.console.editor.PropertiesEditor.java

License:Apache License

@Override
protected void populateItem(Item item) {
    JcrPropertyModel model = (JcrPropertyModel) item.getModel();

    try {/*from   ww w . ja v  a2  s . c om*/
        final AjaxLink deleteLink = deleteLink("delete", model);
        item.add(deleteLink);
        deleteLink.setVisible(!model.getProperty().getDefinition().isProtected());

        JcrName propName = new JcrName(model.getProperty().getName());
        item.add(new Label("namespace", namespacePrefix));
        item.add(new Label("name", propName.getName()));

        item.add(new Label("type", PropertyType.nameFromValue(model.getProperty().getType())));

        WebMarkupContainer valuesContainer = new WebMarkupContainer("values-container");
        valuesContainer.setOutputMarkupId(true);
        item.add(valuesContainer);

        PropertyValueEditor editor = createPropertyValueEditor("values", model);
        valuesContainer.add(editor);

        final AjaxLink addLink = addLink("add", model, valuesContainer, editor);
        addLink.add(TitleAttribute.set(getString("property.value.add")));
        item.add(addLink);

        PropertyDefinition definition = model.getProperty().getDefinition();
        addLink.setVisible(definition.isMultiple() && !definition.isProtected());
    } catch (RepositoryException e) {
        log.error(e.getMessage());
    }
}

From source file:org.hippoecm.frontend.plugins.console.editor.PropertiesEditor.java

License:Apache License

private AjaxLink deleteLink(String id, final JcrPropertyModel model) throws RepositoryException {
    AjaxLink deleteLink = new AjaxLink<Property>(id, model) {
        private static final long serialVersionUID = 1L;

        @Override/* w  ww  .j av a  2  s . c om*/
        protected void onComponentTag(final ComponentTag tag) {
            super.onComponentTag(tag);
            tag.put("class", "property-remove");
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            try {
                Property prop = model.getProperty();
                prop.remove();
            } catch (RepositoryException e) {
                log.error(e.getMessage());
            }

            NodeEditor editor = findParent(NodeEditor.class);
            target.add(editor);
        }
    };

    deleteLink.add(TitleAttribute.set(getString("property.remove")));

    return deleteLink;
}

From source file:org.hippoecm.frontend.plugins.console.editor.PropertyValueEditor.java

License:Apache License

@Override
protected void populateItem(Item item) {
    try {/*  w w  w  . j  ava 2 s.  co  m*/
        final JcrPropertyValueModel valueModel = (JcrPropertyValueModel) item.getModel();
        Component valueEditor = createValueEditor(valueModel);

        item.add(valueEditor);

        final AjaxLink removeLink = new AjaxLink("remove") {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                try {
                    Property prop = propertyModel.getProperty();
                    Value[] values = prop.getValues();
                    values = (Value[]) ArrayUtils.remove(values, valueModel.getIndex());
                    prop.getParent().setProperty(prop.getName(), values, prop.getType());
                } catch (RepositoryException e) {
                    log.error(e.getMessage());
                }

                NodeEditor editor = findParent(NodeEditor.class);
                if (editor != null) {
                    target.add(editor);
                }
            }
        };

        removeLink.add(TitleAttribute.set(getString("property.value.remove")));

        PropertyDefinition definition = propertyModel.getProperty().getDefinition();
        removeLink.setVisible(definition.isMultiple() && !definition.isProtected());

        item.add(removeLink);

        if (focusOnLastItem && item.getIndex() == getItemCount() - 1) {
            focusOnLastItem = false;

            AjaxRequestTarget ajax = RequestCycle.get().find(AjaxRequestTarget.class);
            if (ajax != null && valueEditor instanceof AjaxUpdatingWidget) {
                ajax.focusComponent(((AjaxUpdatingWidget) valueEditor).getFocusComponent());
            }
        }
    } catch (RepositoryException e) {
        log.error(e.getMessage());
        item.add(new Label("value", e.getClass().getName() + ":" + e.getMessage()));
        item.add(new Label("remove", ""));
    }
}

From source file:org.hippoecm.frontend.plugins.console.menu.property.PropertyDialog.java

License:Apache License

public PropertyDialog(IModelReference<Node> modelReference) {
    this.modelReference = modelReference;
    final IModel<Node> model = modelReference.getModel();

    getParent().add(CssClass.append("property-dialog"));

    // list defined properties for automatic completion
    choiceModel = new LoadableDetachableModel<Map<String, List<PropertyDefinition>>>() {

        protected Map<String, List<PropertyDefinition>> load() {
            Map<String, List<PropertyDefinition>> choices = new HashMap<>();
            Node node = model.getObject();
            try {
                NodeType pnt = node.getPrimaryNodeType();
                for (PropertyDefinition pd : pnt.getPropertyDefinitions()) {
                    List<PropertyDefinition> list = choices.get(pd.getName());
                    if (list == null) {
                        list = new ArrayList<>(5);
                    }//w w w.  j  ava2s  .c  o  m
                    list.add(pd);
                    choices.put(pd.getName(), list);
                }
                for (NodeType nt : node.getMixinNodeTypes()) {
                    for (PropertyDefinition pd : nt.getPropertyDefinitions()) {
                        List<PropertyDefinition> list = choices.get(pd.getName());
                        if (list == null) {
                            list = new ArrayList<>(5);
                        }
                        list.add(pd);
                        choices.put(pd.getName(), list);
                    }
                }
                // remove already set properties from suggestions:
                final Set<String> properties = new HashSet<>(choices.keySet());
                for (String property : properties) {
                    if (!isResidual(property) && node.hasProperty(property)) {
                        choices.remove(property);
                    }
                }
            } catch (RepositoryException e) {
                log.warn("Unable to populate autocomplete list for property names", e);
            }
            return choices;
        }
    };

    // checkbox for property ismultiple
    final CheckBox checkBox = new CheckBox("isMultiple", new Model<Boolean>() {

        @Override
        public void setObject(Boolean multiple) {
            PropertyDialog.this.isMultiple = multiple;
        }

        @Override
        public Boolean getObject() {
            if (PropertyDialog.this.name != null) {
                List<PropertyDefinition> propdefs = choiceModel.getObject().get(PropertyDialog.this.name);
                if (propdefs != null) {
                    for (PropertyDefinition pd : propdefs) {
                        if (PropertyType.nameFromValue(pd.getRequiredType()).equals(type)) {
                            // somehow need to set isMultiple here, otherwise it doesn't get picked up...
                            PropertyDialog.this.isMultiple = pd.isMultiple();
                            return pd.isMultiple();
                        }
                    }
                }
            }
            return PropertyDialog.this.isMultiple;
        }
    });
    checkBox.setOutputMarkupId(true);
    add(checkBox);

    // dropdown for property type
    final DropDownChoice<String> ddChoice = new DropDownChoice<String>("types") {
        @Override
        public List<? extends String> getChoices() {
            if (PropertyDialog.this.name != null) {
                List<PropertyDefinition> propdefs = choiceModel.getObject().get(PropertyDialog.this.name);
                if (propdefs != null) {
                    List<String> result = new ArrayList<>(propdefs.size());
                    for (PropertyDefinition pd : propdefs) {
                        result.add(PropertyType.nameFromValue(pd.getRequiredType()));
                    }
                    return result;
                }
            }
            return ALL_TYPES;

        }
    };
    ddChoice.setModel(new Model<String>() {
        @Override
        public void setObject(String object) {
            type = object;
        }

        @Override
        public String getObject() {
            List<? extends String> choices = ddChoice.getChoices();
            if (choices.size() == 1) {
                type = choices.iterator().next();
            }
            return type;
        }
    });

    ddChoice.setRequired(true);
    ddChoice.setOutputMarkupId(true);
    ddChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
        }
    });
    add(ddChoice);

    values = new LinkedList<>();
    values.add("");

    final WebMarkupContainer valuesContainer = new WebMarkupContainer("valuesContainer");
    valuesContainer.setOutputMarkupId(true);
    add(valuesContainer);

    valuesContainer.add(new ListView<String>("values", values) {

        @Override
        protected void populateItem(final ListItem<String> item) {
            final TextField textField = new TextField<>("val", item.getModel());
            textField.add(new OnChangeAjaxBehavior() {

                @Override
                protected void onUpdate(final AjaxRequestTarget target) {
                }

            });
            item.add(textField);

            if (focusOnLatestValue && item.getIndex() == (values.size() - 1)) {
                AjaxRequestTarget ajax = RequestCycle.get().find(AjaxRequestTarget.class);
                if (ajax != null) {
                    ajax.focusComponent(textField);
                }
                focusOnLatestValue = false;
            }

            final AjaxLink deleteLink = new AjaxLink("removeLink") {
                @Override
                public void onClick(final AjaxRequestTarget target) {
                    values.remove(item.getIndex());
                    target.add(valuesContainer);
                }

                @Override
                public boolean isVisible() {
                    return super.isVisible() && item.getIndex() > 0;
                }
            };

            deleteLink.add(TitleAttribute.set(getString("property.value.remove")));
            deleteLink.add(new InputBehavior(new KeyType[] { KeyType.Enter }, EventType.click) {
                @Override
                protected String getTarget() {
                    return "'" + deleteLink.getMarkupId() + "'";
                }
            });
            item.add(deleteLink);
        }
    });

    final AjaxLink addLink = new AjaxLink("addLink") {
        @Override
        public void onClick(final AjaxRequestTarget target) {
            values.add("");
            target.add(valuesContainer);
            focusOnLatestValue = true;
        }

        @Override
        public boolean isVisible() {
            return isMultiple;
        }
    };
    addLink.add(TitleAttribute.set(getString("property.value.add")));
    addLink.add(new InputBehavior(new KeyType[] { KeyType.Enter }, EventType.click) {
        @Override
        protected String getTarget() {
            return "'" + addLink.getMarkupId() + "'";
        }
    });
    valuesContainer.add(addLink);

    checkBox.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(valuesContainer);
            if (!isMultiple && values.size() > 1) {
                String first = values.get(0);
                values.clear();
                values.add(first);
            }
        }
    });

    // text field for property name
    AutoCompleteSettings settings = new AutoCompleteSettings();
    settings.setAdjustInputWidth(false);
    settings.setUseSmartPositioning(true);
    settings.setShowCompleteListOnFocusGain(true);
    settings.setShowListOnEmptyInput(true);
    // Setting a max height will trigger a correct recalculation of the height when the list of items is filtered
    settings.setMaxHeightInPx(400);

    final TextField<String> nameField = new AutoCompleteTextFieldWidget<String>("name",
            PropertyModel.of(this, "name"), settings) {

        @Override
        protected Iterator<String> getChoices(String input) {
            List<String> result = new ArrayList<>();
            for (String propName : choiceModel.getObject().keySet()) {
                if (propName.contains(input)) {
                    result.add(propName);
                }
            }
            return result.iterator();
        }

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            super.onUpdate(target);

            target.add(ddChoice);
            target.add(checkBox);
            target.add(valuesContainer);
            focusOnLatestValue = true;
        }
    };

    nameField.setRequired(true);
    add(nameField);
    setFocus(nameField);
}