Example usage for org.apache.wicket.markup.html.list ListView setOutputMarkupId

List of usage examples for org.apache.wicket.markup.html.list ListView setOutputMarkupId

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.list ListView setOutputMarkupId.

Prototype

public final Component setOutputMarkupId(final boolean output) 

Source Link

Document

Sets whether or not component will output id attribute into the markup.

Usage

From source file:hsa.awp.admingui.edit.event.tabs.TabRule.java

License:Open Source License

/**
 * Constructor./*from   w w  w.  j a  va 2 s  . co  m*/
 *
 * @param id    wicket-id.
 * @param event event to edit.
 */
public TabRule(String id, final Event event) {

    super(id);

    if (event == null) {
        throw new IllegalArgumentException("no event given");
    }
    this.event = event;

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

    add(new Link<RulePanel>("event.rule.ruleLink") {
        /**
         * Generated serialization id.
         */
        private static final long serialVersionUID = -4330022747603538362L;

        @Override
        public void onClick() {

            setResponsePage(new OnePanelPage(new RulePanel(OnePanelPage.getPanelIdOne())));
        }
    });

    final WebMarkupContainer viewContainer = new WebMarkupContainer("event.rule.viewContainer");
    add(viewContainer);
    viewContainer.setOutputMarkupId(true);

    final LoadableDetachedModel<List<MappingCampaignRule>> appliedRuleSets = new LoadableDetachedModel<List<MappingCampaignRule>>() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -2124579745330512796L;

        @Override
        protected List<MappingCampaignRule> load() {

            return getCampaignRuleSetMappingUsingRegistrationRuleSet();
        }
    };

    ListView<MappingCampaignRule> campaigns = new ListView<MappingCampaignRule>(
            "event.rule.viewContainer.campaigns", appliedRuleSets) {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -8838977200090913199L;

        @Override
        protected void populateItem(ListItem<MappingCampaignRule> item) {

            Campaign campaign = item.getModelObject().campaign;
            item.add(new Label("event.rule.viewContainer.campaigns.campaignName", campaign.getName()));

            item.add(new ListView<Rule>("event.rule.viewContainer.campaigns.rules",
                    item.getModelObject().rules) {
                /**
                 * unique serialization id.
                 */
                private static final long serialVersionUID = 3744568568875419040L;

                @Override
                protected void populateItem(ListItem<Rule> item) {

                    item.add(new Label("event.rule.viewContainer.campaigns.rules.rulename",
                            item.getModelObject().getName()));
                }
            });
        }
    };
    campaigns.setOutputMarkupId(true);
    viewContainer.add(campaigns);

    Form<Object> form = new Form<Object>("event.rule.selectForm");
    add(form);

    LoadableDetachedModel<List<Rule>> ruleChoiceModel = new LoadableDetachedModel<List<Rule>>() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = 8248346584785484372L;

        @Override
        protected List<Rule> load() {

            return getAllAvailableCampaignRules();
        }
    };

    campaignDropDownChoice = new DropDownChoice<Campaign>("event.rule.campaignSelect", new Model<Campaign>(),
            getAllCampaigns(), new ChoiceRenderer<Campaign>("name"));
    form.add(campaignDropDownChoice);
    campaignDropDownChoice.add(new OnChangeAjaxBehavior() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = 3121098439171790920L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {

            target.addComponent(ruleDropDownChoice);
        }
    });
    campaignDropDownChoice.setRequired(true);

    ruleDropDownChoice = new DropDownChoice<Rule>("event.rule.ruleSelect", new Model<Rule>(), ruleChoiceModel,
            new ChoiceRenderer<Rule>("name"));
    form.add(ruleDropDownChoice);
    ruleDropDownChoice.setRequired(true);
    ruleDropDownChoice.setOutputMarkupId(true);

    form.add(new AjaxButton("event.rule.submit") {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = 3023000043184393346L;

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

            target.addComponent(viewContainer);
            target.addComponent(feedbackPanel);
            controller.addRule(campaignDropDownChoice.getModelObject(), event,
                    ruleDropDownChoice.getModelObject(), getSession());
            info("Regel wurde zugeordnet.");
        }
    });
}

From source file:hsa.awp.admingui.usermanagement.RoleTab.java

License:Open Source License

public RoleTab(String wicketId, final Role role, boolean changeable, final Mandator mandator) {

    super(wicketId);

    if (role == null) {
        throw new IllegalArgumentException("no role given");
    }/*from w ww  . ja  va2 s .c  o m*/

    WebMarkupContainer addUserContainer = new WebMarkupContainer("addUser");
    add(addUserContainer);

    addUserContainer.add(new UserSelectPanel("userSelectPanel") {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -2199695801515215562L;

        @Override
        protected boolean onSendSubmit(SingleUser singleUser) {

            if (hasUserRoleForMandator(singleUser, role, mandator)) {
                getFeedbackPanel().error("User " + singleUser.getName() + " is already in role " + role.name());
                return false;
            }

            RoleMapping roleMapping = RoleMapping.getInstance(role, mandator, singleUser);

            getController().addRoleMappingToSingleUser(singleUser, roleMapping);

            return true;
        }

        @Override
        protected boolean vetoFindSubmit(SingleUser user) {

            if (hasUserRoleForMandator(user, role, mandator)) {
                getFeedbackPanel().error("User " + user.getName() + " is already in role " + role.name());
                return true;
            }
            return false;
        }
    });

    listUserContainer = new WebMarkupContainer("userListContainer");
    listUserContainer.setOutputMarkupId(true);
    add(listUserContainer);

    final ILoadableDetachedModel<List<SingleUser>> usersModel = new LoadableDetachedModel<List<SingleUser>>() {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = -2548188711048825707L;

        @Override
        protected List<SingleUser> load() {

            List<SingleUser> singleUsers = getController().findSingleUsersByRole(role);

            Set<SingleUser> filtered = new HashSet<SingleUser>();

            for (SingleUser singleUser : singleUsers) {
                if (hasUserRoleForMandator(singleUser, role, mandator)) {
                    filtered.add(singleUser);
                }
            }

            return new ArrayList<SingleUser>(filtered);
        }
    };

    ListView<SingleUser> list = new ListView<SingleUser>("userList", usersModel) {
        /**
         * unique serialization id.
         */
        private static final long serialVersionUID = 4307951155564631399L;

        @Override
        protected void populateItem(final ListItem<SingleUser> item) {

            item.add(new Label("username", item.getModelObject().getUsername()));
            item.add(new Label("name", item.getModelObject().getName()));

            item.add(new AjaxFallbackLink<RoleTab>("delete") {
                /**
                 * unique serialization id.
                 */
                private static final long serialVersionUID = 2004009811773410560L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    usersModel.getObject();

                    SingleUser singleUser = item.getModelObject();
                    getController().removeRoleMappingForMandator(singleUser,
                            singleUser.roleMappingForRole(role), mandator);

                    target.addComponent(listUserContainer);
                    usersModel.detach();
                }
            });
        }
    };
    list.setOutputMarkupId(true);
    listUserContainer.add(list);

    feedbackPanel = new FeedbackPanel("feedbackPanel");
    feedbackPanel.setFilter(new ContainerFeedbackMessageFilter(listUserContainer));
    add(feedbackPanel);

    if (!changeable) {
        addUserContainer.setVisible(false);
    }
}

From source file:io.ucoin.ucoinj.web.pages.admin.JobManagerPage.java

License:Open Source License

public JobManagerPage(PageParameters pageParameters) {
    super(pageParameters);

    // Create models (list of progressionModel)
    LoadableDetachableModel<List<JobVO>> jobListModel = new LoadableDetachableModel<List<JobVO>>() {
        private static final long serialVersionUID = 1L;

        @Override/*from   ww w.j ava  2 s  .  c o m*/
        protected List<JobVO> load() {
            return ServiceLocator.instance().getExecutorService().getAllJobs();
        }
    };

    add(new Label("jobCount", new PropertyModel<Integer>(jobListModel, "size")));

    // List of import jobs
    ListView<JobVO> jobListView = new ListView<JobVO>("jobList", jobListModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<JobVO> item) {
            // User infos
            item.add(new Label("issuer", new PropertyModel<Integer>(item.getModel(), "issuer")));

            // Progress bar
            String jobId = item.getModelObject().getId();
            ProgressionPanel progressionPanel = new ProgressionPanel("progress",
                    new WicketProgressionModel(jobId)) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onComplete(AjaxRequestTarget target) {
                    stop(target);
                }
            };
            progressionPanel.setOutputMarkupId(true);
            progressionPanel.setOutputMarkupPlaceholderTag(true);
            item.add(progressionPanel);
        }
    };
    jobListView.setOutputMarkupId(true);
    add(jobListView);

    add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)));
}

From source file:ontopoly.components.FieldsEditor.java

License:Apache License

private ListView<FieldDefinitionModel> createListView(final List<FieldDefinitionModel> fieldDefinitionModels) {
    ListView<FieldDefinitionModel> listView = new ListView<FieldDefinitionModel>("addFields",
            fieldDefinitionModels) {//from  ww  w .  j  a  v a 2  s .com
        public void populateItem(final ListItem<FieldDefinitionModel> item) {

            FieldDefinitionModel fieldDefinitionModel = item.getModelObject();
            //item.setRenderBodyOnly(true);

            Component component = new FieldsEditorAddPanel("field", topicTypeModel, fieldDefinitionModel) {
                @Override
                protected void onAddField(TopicTypeModel topicTypeModel,
                        FieldDefinitionModel fieldDefinitionModel, AjaxRequestTarget target) {
                    // add field to topic type
                    topicTypeModel.getTopicType().addField(fieldDefinitionModel.getFieldDefinition());

                    // remove field definition from available list
                    fieldDefinitionModels.remove(fieldDefinitionModel);
                    @SuppressWarnings("rawtypes")
                    ListView pListView = (ListView) item.getParent();
                    pListView.removeAll();
                    onUpdate(target);
                }
            };
            //component.setRenderBodyOnly(true);
            item.add(component);
        }
    };
    listView.setOutputMarkupId(true);
    listView.setReuseItems(true);
    return listView;
}

From source file:org.apache.syncope.client.console.pages.BasePage.java

License:Apache License

public BasePage(final PageParameters parameters) {
    super(parameters);

    // Native WebSocket
    add(new WebSocketBehavior() {

        private static final long serialVersionUID = 3109256773218160485L;

        @Override/*from  w  w w.j av  a 2  s. c  o  m*/
        protected void onConnect(final ConnectedMessage message) {
            super.onConnect(message);

            SyncopeConsoleSession.get().scheduleAtFixedRate(new ApprovalsWidget.ApprovalInfoUpdater(message), 0,
                    30, TimeUnit.SECONDS);

            if (BasePage.this instanceof Dashboard) {
                SyncopeConsoleSession.get().scheduleAtFixedRate(new JobWidget.JobInfoUpdater(message), 0, 10,
                        TimeUnit.SECONDS);
                SyncopeConsoleSession.get().scheduleAtFixedRate(
                        new ReconciliationWidget.ReconciliationJobInfoUpdater(message), 0, 10,
                        TimeUnit.SECONDS);
            }
        }

    });

    body = new WebMarkupContainer("body");
    Serializable leftMenuCollapse = SyncopeConsoleSession.get()
            .getAttribute(SyncopeConsoleSession.MENU_COLLAPSE);
    if ((leftMenuCollapse instanceof Boolean) && ((Boolean) leftMenuCollapse)) {
        body.add(new AttributeAppender("class", " sidebar-collapse"));
    }
    add(body);

    notificationPanel = new NotificationPanel(Constants.FEEDBACK);
    body.addOrReplace(notificationPanel.setOutputMarkupId(true));

    // header, footer
    body.add(new Label("version", SyncopeConsoleApplication.get().getVersion()));
    body.add(new Label("username", SyncopeConsoleSession.get().getSelfTO().getUsername()));

    body.add(new ApprovalsWidget("approvalsWidget", getPageReference()).setRenderBodyOnly(true));

    // right sidebar
    SystemInfo systemInfo = SyncopeConsoleSession.get().getSystemInfo();
    body.add(new Label("hostname", systemInfo.getHostname()));
    body.add(new Label("processors", systemInfo.getAvailableProcessors()));
    body.add(new Label("os", systemInfo.getOs()));
    body.add(new Label("jvm", systemInfo.getJvm()));

    Link<Void> dbExportLink = new Link<Void>("dbExportLink") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick() {
            try {
                HttpResourceStream stream = new HttpResourceStream(new ConfigurationRestClient().dbExport());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(
                        stream.getFilename() == null ? SyncopeConsoleSession.get().getDomain() + "Content.xml"
                                : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                SyncopeConsoleSession.get().error(getString(Constants.ERROR) + ": " + e.getMessage());
            }
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(dbExportLink, WebPage.ENABLE,
            StandardEntitlement.CONFIGURATION_EXPORT);
    body.add(dbExportLink);

    // menu
    WebMarkupContainer liContainer = new WebMarkupContainer(getLIContainerId("dashboard"));
    body.add(liContainer);
    liContainer.add(BookmarkablePageLinkBuilder.build("dashboard", Dashboard.class));

    liContainer = new WebMarkupContainer(getLIContainerId("realms"));
    body.add(liContainer);
    BookmarkablePageLink<? extends BasePage> link = BookmarkablePageLinkBuilder.build("realms", Realms.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.REALM_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("topology"));
    body.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("topology", Topology.class);
    StringBuilder bld = new StringBuilder();
    bld.append(StandardEntitlement.CONNECTOR_LIST).append(",").append(StandardEntitlement.RESOURCE_LIST)
            .append(",");
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, bld.toString());
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("reports"));
    body.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("reports", Reports.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.REPORT_LIST);
    liContainer.add(link);

    WebMarkupContainer confLIContainer = new WebMarkupContainer(getLIContainerId("configuration"));
    body.add(confLIContainer);
    WebMarkupContainer confULContainer = new WebMarkupContainer(getULContainerId("configuration"));
    confLIContainer.add(confULContainer);

    liContainer = new WebMarkupContainer(getLIContainerId("workflow"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("workflow", Workflow.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.WORKFLOW_DEF_READ);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("audit"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("audit", Audit.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.AUDIT_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("logs"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("logs", Logs.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.LOG_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("securityquestions"));
    confULContainer.add(liContainer);
    bld = new StringBuilder();
    bld.append(StandardEntitlement.SECURITY_QUESTION_CREATE).append(",")
            .append(StandardEntitlement.SECURITY_QUESTION_DELETE).append(",")
            .append(StandardEntitlement.SECURITY_QUESTION_UPDATE);
    link = BookmarkablePageLinkBuilder.build("securityquestions", SecurityQuestions.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, bld.toString());
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("types"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("types", Types.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.SCHEMA_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("roles"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("roles", Roles.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.ROLE_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("policies"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("policies", Policies.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.POLICY_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("notifications"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("notifications", Notifications.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.NOTIFICATION_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("parameters"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("parameters", Parameters.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.CONFIGURATION_LIST);
    liContainer.add(link);

    body.add(new AjaxLink<Void>("collapse") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            SyncopeConsoleSession.get().setAttribute(SyncopeConsoleSession.MENU_COLLAPSE,
                    SyncopeConsoleSession.get().getAttribute(SyncopeConsoleSession.MENU_COLLAPSE) == null ? true
                            : !(Boolean) SyncopeConsoleSession.get()
                                    .getAttribute(SyncopeConsoleSession.MENU_COLLAPSE));
        }
    });
    body.add(new Label("domain", SyncopeConsoleSession.get().getDomain()));
    body.add(new BookmarkablePageLink<Page>("logout", Logout.class));

    // set 'active' menu item for everything but extensions
    // 1. check if current class is set to top-level menu
    Component containingLI = body.get(getLIContainerId(getClass().getSimpleName().toLowerCase()));
    // 2. if not, check if it is under 'Configuration'
    if (containingLI == null) {
        containingLI = confULContainer.get(getLIContainerId(getClass().getSimpleName().toLowerCase()));
    }
    // 3. when found, set CSS coordinates for menu
    if (containingLI != null) {
        containingLI.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "active");
            }
        });

        if (confULContainer.getId().equals(containingLI.getParent().getId())) {
            confULContainer.add(new Behavior() {

                private static final long serialVersionUID = 3109256773218160485L;

                @Override
                public void onComponentTag(final Component component, final ComponentTag tag) {
                    tag.put("class", "treeview-menu menu-open");
                    tag.put("style", "display: block;");
                }

            });

            confLIContainer.add(new Behavior() {

                private static final long serialVersionUID = 3109256773218160485L;

                @Override
                public void onComponentTag(final Component component, final ComponentTag tag) {
                    tag.put("class", "treeview active");
                }
            });
        }
    }

    // Extensions
    ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) SyncopeConsoleApplication
            .get().getServletContext().getAttribute(ConsoleInitializer.CLASSPATH_LOOKUP);
    List<Class<? extends BaseExtPage>> extPageClasses = classPathScanImplementationLookup.getExtPageClasses();

    WebMarkupContainer extensionsLI = new WebMarkupContainer(getLIContainerId("extensions"));
    extensionsLI.setOutputMarkupPlaceholderTag(true);
    extensionsLI.setVisible(!extPageClasses.isEmpty());
    body.add(extensionsLI);

    ListView<Class<? extends BaseExtPage>> extPages = new ListView<Class<? extends BaseExtPage>>("extPages",
            extPageClasses) {

        private static final long serialVersionUID = 4949588177564901031L;

        @Override
        protected void populateItem(final ListItem<Class<? extends BaseExtPage>> item) {
            WebMarkupContainer containingLI = new WebMarkupContainer("extPageLI");
            item.add(containingLI);
            if (item.getModelObject().equals(BasePage.this.getClass())) {
                containingLI.add(new Behavior() {

                    private static final long serialVersionUID = 1469628524240283489L;

                    @Override
                    public void onComponentTag(final Component component, final ComponentTag tag) {
                        tag.put("class", "active");
                    }
                });
            }

            ExtPage ann = item.getModelObject().getAnnotation(ExtPage.class);

            BookmarkablePageLink<Page> link = new BookmarkablePageLink<>("extPage", item.getModelObject());
            link.add(new Label("extPageLabel", ann.label()));
            MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, ann.listEntitlement());
            containingLI.add(link);

            Label extPageIcon = new Label("extPageIcon");
            extPageIcon.add(new AttributeModifier("class", "fa " + ann.icon()));
            link.add(extPageIcon);
        }
    };
    extPages.setOutputMarkupId(true);
    extensionsLI.add(extPages);

    if (getPage() instanceof BaseExtPage) {
        extPages.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "treeview-menu menu-open");
                tag.put("style", "display: block;");
            }

        });

        extensionsLI.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "treeview active");
            }
        });
    }
}

From source file:org.apache.syncope.client.console.pages.ConnectorModalPage.java

License:Apache License

public ConnectorModalPage(final PageReference pageRef, final ModalWindow window,
        final ConnInstanceTO connInstanceTO) {

    super();/* w  w  w . j av a 2 s.  co  m*/

    this.add(new Label("new",
            connInstanceTO.getKey() == 0 ? new ResourceModel("new") : new Model<>(StringUtils.EMPTY)));
    this.add(new Label("key", connInstanceTO.getKey() == 0 ? StringUtils.EMPTY : connInstanceTO.getKey()));

    // general data setup
    selectedCapabilities = new ArrayList<>(
            connInstanceTO.getKey() == 0 ? EnumSet.noneOf(ConnectorCapability.class)
                    : connInstanceTO.getCapabilities());

    mapConnBundleTOs = new HashMap<>();
    for (ConnBundleTO connBundleTO : restClient.getAllBundles()) {
        // by location
        if (!mapConnBundleTOs.containsKey(connBundleTO.getLocation())) {
            mapConnBundleTOs.put(connBundleTO.getLocation(), new HashMap<String, Map<String, ConnBundleTO>>());
        }
        final Map<String, Map<String, ConnBundleTO>> byLocation = mapConnBundleTOs
                .get(connBundleTO.getLocation());

        // by name
        if (!byLocation.containsKey(connBundleTO.getBundleName())) {
            byLocation.put(connBundleTO.getBundleName(), new HashMap<String, ConnBundleTO>());
        }
        final Map<String, ConnBundleTO> byName = byLocation.get(connBundleTO.getBundleName());

        // by version
        if (!byName.containsKey(connBundleTO.getVersion())) {
            byName.put(connBundleTO.getVersion(), connBundleTO);
        }
    }

    bundleTO = getSelectedBundleTO(connInstanceTO);
    properties = fillProperties(bundleTO, connInstanceTO);

    // form - first tab
    final Form<ConnInstanceTO> connectorForm = new Form<>(FORM);
    connectorForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorForm.setOutputMarkupId(true);
    add(connectorForm);

    propertiesContainer = new WebMarkupContainer("container");
    propertiesContainer.setOutputMarkupId(true);
    connectorForm.add(propertiesContainer);

    final Form<ConnInstanceTO> connectorPropForm = new Form<>("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorPropForm.setOutputMarkupId(true);
    propertiesContainer.add(connectorPropForm);

    final AjaxTextFieldPanel displayName = new AjaxTextFieldPanel("displayName", "display name",
            new PropertyModel<String>(connInstanceTO, "displayName"));
    displayName.setOutputMarkupId(true);
    displayName.addRequiredLabel();
    connectorForm.add(displayName);

    final AjaxDropDownChoicePanel<String> location = new AjaxDropDownChoicePanel<>("location", "location",
            new Model<>(bundleTO == null ? null : bundleTO.getLocation()));
    ((DropDownChoice<String>) location.getField()).setNullValid(true);
    location.setStyleSheet("long_dynamicsize");
    location.setChoices(new ArrayList<>(mapConnBundleTOs.keySet()));
    location.setRequired(true);
    location.addRequiredLabel();
    location.setOutputMarkupId(true);
    location.setEnabled(connInstanceTO.getKey() == 0);
    location.getField().setOutputMarkupId(true);
    connectorForm.add(location);

    final AjaxDropDownChoicePanel<String> connectorName = new AjaxDropDownChoicePanel<>("connectorName",
            "connectorName", new Model<>(bundleTO == null ? null : bundleTO.getBundleName()));
    ((DropDownChoice<String>) connectorName.getField()).setNullValid(true);
    connectorName.setStyleSheet("long_dynamicsize");
    connectorName.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation()).keySet()));
    connectorName.setRequired(true);
    connectorName.addRequiredLabel();
    connectorName.setEnabled(connInstanceTO.getLocation() != null);
    connectorName.setOutputMarkupId(true);
    connectorName.setEnabled(connInstanceTO.getKey() == 0);
    connectorName.getField().setOutputMarkupId(true);
    connectorForm.add(connectorName);

    final AjaxDropDownChoicePanel<String> version = new AjaxDropDownChoicePanel<>("version", "version",
            new Model<>(bundleTO == null ? null : bundleTO.getVersion()));
    version.setStyleSheet("long_dynamicsize");
    version.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation())
                    .get(connInstanceTO.getBundleName()).keySet()));
    version.setRequired(true);
    version.addRequiredLabel();
    version.setEnabled(connInstanceTO.getBundleName() != null);
    version.setOutputMarkupId(true);
    version.addRequiredLabel();
    version.getField().setOutputMarkupId(true);
    connectorForm.add(version);

    final SpinnerFieldPanel<Integer> connRequestTimeout = new SpinnerFieldPanel<>("connRequestTimeout",
            "connRequestTimeout", Integer.class,
            new PropertyModel<Integer>(connInstanceTO, "connRequestTimeout"), 0, null);
    connRequestTimeout.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(connRequestTimeout);

    if (connInstanceTO.getPoolConf() == null) {
        connInstanceTO.setPoolConf(new ConnPoolConfTO());
    }
    final SpinnerFieldPanel<Integer> poolMaxObjects = new SpinnerFieldPanel<>("poolMaxObjects",
            "poolMaxObjects", Integer.class,
            new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxObjects"), 0, null);
    poolMaxObjects.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxObjects);
    final SpinnerFieldPanel<Integer> poolMinIdle = new SpinnerFieldPanel<>("poolMinIdle", "poolMinIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "minIdle"), 0, null);
    poolMinIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMinIdle);
    final SpinnerFieldPanel<Integer> poolMaxIdle = new SpinnerFieldPanel<>("poolMaxIdle", "poolMaxIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxIdle"), 0, null);
    poolMaxIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxIdle);
    final SpinnerFieldPanel<Long> poolMaxWait = new SpinnerFieldPanel<>("poolMaxWait", "poolMaxWait",
            Long.class, new PropertyModel<Long>(connInstanceTO.getPoolConf(), "maxWait"), 0L, null);
    poolMaxWait.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMaxWait);
    final SpinnerFieldPanel<Long> poolMinEvictableIdleTime = new SpinnerFieldPanel<>("poolMinEvictableIdleTime",
            "poolMinEvictableIdleTime", Long.class,
            new PropertyModel<Long>(connInstanceTO.getPoolConf(), "minEvictableIdleTimeMillis"), 0L, null);
    poolMinEvictableIdleTime.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMinEvictableIdleTime);

    // form - first tab - onchange()
    location.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) location.getField()).setNullValid(false);
            connInstanceTO.setLocation(location.getModelObject());
            target.add(location);

            connectorName.setChoices(new ArrayList<>(mapConnBundleTOs.get(location.getModelObject()).keySet()));
            connectorName.setEnabled(true);
            connectorName.getField().setModelValue(null);
            target.add(connectorName);

            version.setChoices(new ArrayList<String>());
            version.getField().setModelValue(null);
            version.setEnabled(false);
            target.add(version);

            properties.clear();
            target.add(propertiesContainer);
        }
    });
    connectorName.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) connectorName.getField()).setNullValid(false);
            connInstanceTO.setBundleName(connectorName.getModelObject());
            target.add(connectorName);

            List<String> versions = new ArrayList<>(mapConnBundleTOs.get(location.getModelObject())
                    .get(connectorName.getModelObject()).keySet());
            version.setChoices(versions);
            version.setEnabled(true);
            if (versions.size() == 1) {
                selectVersion(target, connInstanceTO, version, versions.get(0));
                version.getField().setModelObject(versions.get(0));
            } else {
                version.getField().setModelValue(null);
                properties.clear();
                target.add(propertiesContainer);
            }
            target.add(version);
        }
    });
    version.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            selectVersion(target, connInstanceTO, version, version.getModelObject());
        }
    });

    // form - second tab (properties)
    final ListView<ConnConfProperty> connPropView = new ConnConfPropertyListView("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "properties"), true,
            connInstanceTO.getConfiguration());
    connPropView.setOutputMarkupId(true);
    connectorPropForm.add(connPropView);

    final AjaxButton check = new IndicatingAjaxButton("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            // ensure that connector bundle information is in sync
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.setConnectorName(bundleTO.getConnectorName());

            if (restClient.check(conn)) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            feedbackPanel.refresh(target);
        }
    };
    connectorPropForm.add(check);

    // form - third tab (capabilities)
    final IModel<List<ConnectorCapability>> capabilities = new LoadableDetachableModel<List<ConnectorCapability>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnectorCapability> load() {
            return Arrays.asList(ConnectorCapability.values());
        }
    };
    CheckBoxMultipleChoice<ConnectorCapability> capabilitiesPalette = new CheckBoxMultipleChoice<>(
            "capabilitiesPalette", new PropertyModel<List<ConnectorCapability>>(this, "selectedCapabilities"),
            capabilities);

    capabilitiesPalette.add(new AjaxFormChoiceComponentUpdatingBehavior() {

        private static final long serialVersionUID = -1107858522700306810L;

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

    connectorForm.add(capabilitiesPalette);

    // form - submit / cancel buttons
    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            conn.setConnectorName(bundleTO.getConnectorName());
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.getConfiguration().clear();
            conn.getConfiguration().addAll(connPropView.getModelObject());

            // Set the model object's capabilities to capabilitiesPalette's converted Set
            conn.getCapabilities().clear();
            conn.getCapabilities()
                    .addAll(selectedCapabilities.isEmpty() ? EnumSet.noneOf(ConnectorCapability.class)
                            : EnumSet.copyOf(selectedCapabilities));

            // Reset pool configuration if all fields are null
            if (conn.getPoolConf() != null && conn.getPoolConf().getMaxIdle() == null
                    && conn.getPoolConf().getMaxObjects() == null && conn.getPoolConf().getMaxWait() == null
                    && conn.getPoolConf().getMinEvictableIdleTimeMillis() == null
                    && conn.getPoolConf().getMinIdle() == null) {

                conn.setPoolConf(null);
            }

            try {
                if (connInstanceTO.getKey() == 0) {
                    restClient.create(conn);
                } else {
                    restClient.update(conn);
                }

                ((Resources) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                feedbackPanel.refresh(target);
                ((Resources) pageRef.getPage()).setModalResult(false);
                LOG.error("While creating or updating connector {}", conn, e);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };
    String roles = connInstanceTO.getKey() == 0 ? xmlRolesReader.getEntitlement("Connectors", "create")
            : xmlRolesReader.getEntitlement("Connectors", "update");
    MetaDataRoleAuthorizationStrategy.authorize(submit, ENABLE, roles);
    connectorForm.add(submit);

    final IndicatingAjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            window.close(target);
        }
    };
    cancel.setDefaultFormProcessing(false);
    connectorForm.add(cancel);
}

From source file:org.apache.syncope.client.console.pages.LogViewer.java

License:Apache License

public LogViewer() {
    final WebMarkupContainer viewer = new WebMarkupContainer("viewer");
    viewer.setOutputMarkupId(true);/*  w w  w .ja v a 2 s  .  c o  m*/
    add(viewer);

    final AjaxDropDownChoicePanel<String> appenders = new AjaxDropDownChoicePanel<>("appenders", "Appender",
            new Model<String>(), false);
    MetaDataRoleAuthorizationStrategy.authorize(appenders, ENABLE, StandardEntitlement.LOG_READ);
    appenders.setChoices(restClient.listMemoryAppenders());
    viewer.add(appenders);

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

    final Model<Long> lastTimeInMillis = Model.of(0L);
    final IModel<List<LogStatementTO>> statementViewModel = new ListModel<>(new ArrayList<LogStatementTO>());
    final ListView<LogStatementTO> statementView = new ListView<LogStatementTO>("statements",
            statementViewModel) {

        private static final long serialVersionUID = -9180479401817023838L;

        @Override
        protected void populateItem(final ListItem<LogStatementTO> item) {
            LogStatementPanel panel = new LogStatementPanel("statement", item.getModelObject());
            panel.setOutputMarkupId(true);
            item.add(panel);
        }
    };
    statementView.setOutputMarkupId(true);
    stContainer.add(statementView);
    stContainer.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(10)) {

        private static final long serialVersionUID = 7298597675929755960L;

        @Override
        protected void onPostProcessTarget(final AjaxRequestTarget target) {
            // save scroll position
            target.prependJavaScript(
                    String.format("window.scrollTop = $('#%s').scrollTop();", stContainer.getMarkupId()));

            List<LogStatementTO> recentLogStatements = appenders.getModelObject() == null
                    ? new ArrayList<LogStatementTO>()
                    : restClient.getLastLogStatements(appenders.getModelObject(), lastTimeInMillis.getObject());
            if (!recentLogStatements.isEmpty()) {
                lastTimeInMillis
                        .setObject(recentLogStatements.get(recentLogStatements.size() - 1).getTimeMillis());

                int currentSize = statementView.getModelObject().size();
                int recentSize = recentLogStatements.size();

                List<LogStatementTO> newModelObject = SetUniqueList.<LogStatementTO>setUniqueList(
                        new ArrayList<LogStatementTO>(MAX_STATEMENTS_PER_APPENDER));
                if (currentSize <= MAX_STATEMENTS_PER_APPENDER - recentSize) {
                    newModelObject.addAll(statementView.getModelObject());
                } else {
                    newModelObject.addAll(statementView.getModelObject()
                            .subList(currentSize - (MAX_STATEMENTS_PER_APPENDER - recentSize), currentSize));
                }
                newModelObject.addAll(recentLogStatements);

                statementViewModel.setObject(newModelObject);
                target.add(stContainer);

            }

            // restore scroll position - might not work perfectly if items were removed from the top
            target.appendJavaScript(
                    String.format("$('#%s').scrollTop(window.scrollTop);", stContainer.getMarkupId()));
        }
    });

    appenders.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            List<LogStatementTO> lastStatements = appenders.getModelObject() == null
                    ? new ArrayList<LogStatementTO>()
                    : restClient.getLastLogStatements(appenders.getModelObject(), 0);
            statementViewModel.setObject(lastStatements);
            target.add(stContainer);

            lastTimeInMillis.setObject(0L);
        }
    });
}

From source file:org.apache.syncope.client.console.panels.ConnectorModal.java

License:Apache License

public ConnectorModal(final ModalWindow window, final PageReference pageRef,
        final ConnInstanceTO connInstanceTO) {

    super(window, pageRef);

    this.add(new Label("new",
            connInstanceTO.getKey() == 0 ? new ResourceModel("new") : new Model<>(StringUtils.EMPTY)));
    this.add(new Label("key", connInstanceTO.getKey() == 0 ? StringUtils.EMPTY : connInstanceTO.getKey()));

    // general data setup
    selectedCapabilities = new ArrayList<>(
            connInstanceTO.getKey() == 0 ? EnumSet.noneOf(ConnectorCapability.class)
                    : connInstanceTO.getCapabilities());

    mapConnBundleTOs = new HashMap<>();
    for (ConnBundleTO connBundleTO : connectorRestClient.getAllBundles()) {
        // by location
        if (!mapConnBundleTOs.containsKey(connBundleTO.getLocation())) {
            mapConnBundleTOs.put(connBundleTO.getLocation(), new HashMap<String, Map<String, ConnBundleTO>>());
        }/*  w  w  w  .j  ava 2 s .  co  m*/
        final Map<String, Map<String, ConnBundleTO>> byLocation = mapConnBundleTOs
                .get(connBundleTO.getLocation());

        // by name
        if (!byLocation.containsKey(connBundleTO.getBundleName())) {
            byLocation.put(connBundleTO.getBundleName(), new HashMap<String, ConnBundleTO>());
        }
        final Map<String, ConnBundleTO> byName = byLocation.get(connBundleTO.getBundleName());

        // by version
        if (!byName.containsKey(connBundleTO.getVersion())) {
            byName.put(connBundleTO.getVersion(), connBundleTO);
        }
    }

    bundleTO = getSelectedBundleTO(connInstanceTO);
    properties = fillProperties(bundleTO, connInstanceTO);

    // form - first tab
    final Form<ConnInstanceTO> connectorForm = new Form<>(FORM);
    connectorForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorForm.setOutputMarkupId(true);
    add(connectorForm);

    propertiesContainer = new WebMarkupContainer("container");
    propertiesContainer.setOutputMarkupId(true);
    connectorForm.add(propertiesContainer);

    final Form<ConnInstanceTO> connectorPropForm = new Form<>("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorPropForm.setOutputMarkupId(true);
    propertiesContainer.add(connectorPropForm);

    final AjaxTextFieldPanel displayName = new AjaxTextFieldPanel("displayName", "display name",
            new PropertyModel<String>(connInstanceTO, "displayName"));
    displayName.setOutputMarkupId(true);
    displayName.addRequiredLabel();
    connectorForm.add(displayName);

    final AjaxDropDownChoicePanel<String> location = new AjaxDropDownChoicePanel<>("location", "location",
            new Model<>(bundleTO == null ? null : bundleTO.getLocation()));
    ((DropDownChoice<String>) location.getField()).setNullValid(true);
    location.setStyleSheet("long_dynamicsize");
    location.setChoices(new ArrayList<>(mapConnBundleTOs.keySet()));
    location.setRequired(true);
    location.addRequiredLabel();
    location.setOutputMarkupId(true);
    location.setEnabled(connInstanceTO.getKey() == 0);
    location.getField().setOutputMarkupId(true);
    connectorForm.add(location);

    final AjaxDropDownChoicePanel<String> connectorName = new AjaxDropDownChoicePanel<>("connectorName",
            "connectorName", new Model<>(bundleTO == null ? null : bundleTO.getBundleName()));
    ((DropDownChoice<String>) connectorName.getField()).setNullValid(true);
    connectorName.setStyleSheet("long_dynamicsize");
    connectorName.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation()).keySet()));
    connectorName.setRequired(true);
    connectorName.addRequiredLabel();
    connectorName.setEnabled(connInstanceTO.getLocation() != null);
    connectorName.setOutputMarkupId(true);
    connectorName.setEnabled(connInstanceTO.getKey() == 0);
    connectorName.getField().setOutputMarkupId(true);
    connectorForm.add(connectorName);

    final AjaxDropDownChoicePanel<String> version = new AjaxDropDownChoicePanel<>("version", "version",
            new Model<>(bundleTO == null ? null : bundleTO.getVersion()));
    version.setStyleSheet("long_dynamicsize");
    version.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation())
                    .get(connInstanceTO.getBundleName()).keySet()));
    version.setRequired(true);
    version.addRequiredLabel();
    version.setEnabled(connInstanceTO.getBundleName() != null);
    version.setOutputMarkupId(true);
    version.addRequiredLabel();
    version.getField().setOutputMarkupId(true);
    connectorForm.add(version);

    final SpinnerFieldPanel<Integer> connRequestTimeout = new SpinnerFieldPanel<>("connRequestTimeout",
            "connRequestTimeout", Integer.class,
            new PropertyModel<Integer>(connInstanceTO, "connRequestTimeout"), 0, null);
    connRequestTimeout.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(connRequestTimeout);

    if (connInstanceTO.getPoolConf() == null) {
        connInstanceTO.setPoolConf(new ConnPoolConfTO());
    }
    final SpinnerFieldPanel<Integer> poolMaxObjects = new SpinnerFieldPanel<>("poolMaxObjects",
            "poolMaxObjects", Integer.class,
            new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxObjects"), 0, null);
    poolMaxObjects.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxObjects);
    final SpinnerFieldPanel<Integer> poolMinIdle = new SpinnerFieldPanel<>("poolMinIdle", "poolMinIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "minIdle"), 0, null);
    poolMinIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMinIdle);
    final SpinnerFieldPanel<Integer> poolMaxIdle = new SpinnerFieldPanel<>("poolMaxIdle", "poolMaxIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxIdle"), 0, null);
    poolMaxIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxIdle);
    final SpinnerFieldPanel<Long> poolMaxWait = new SpinnerFieldPanel<>("poolMaxWait", "poolMaxWait",
            Long.class, new PropertyModel<Long>(connInstanceTO.getPoolConf(), "maxWait"), 0L, null);
    poolMaxWait.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMaxWait);
    final SpinnerFieldPanel<Long> poolMinEvictableIdleTime = new SpinnerFieldPanel<>("poolMinEvictableIdleTime",
            "poolMinEvictableIdleTime", Long.class,
            new PropertyModel<Long>(connInstanceTO.getPoolConf(), "minEvictableIdleTimeMillis"), 0L, null);
    poolMinEvictableIdleTime.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMinEvictableIdleTime);

    // form - first tab - onchange()
    location.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) location.getField()).setNullValid(false);
            connInstanceTO.setLocation(location.getModelObject());
            target.add(location);

            connectorName.setChoices(new ArrayList<>(mapConnBundleTOs.get(location.getModelObject()).keySet()));
            connectorName.setEnabled(true);
            connectorName.getField().setModelValue(null);
            target.add(connectorName);

            version.setChoices(new ArrayList<String>());
            version.getField().setModelValue(null);
            version.setEnabled(false);
            target.add(version);

            properties.clear();
            target.add(propertiesContainer);
        }
    });
    connectorName.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) connectorName.getField()).setNullValid(false);
            connInstanceTO.setBundleName(connectorName.getModelObject());
            target.add(connectorName);

            List<String> versions = new ArrayList<>(mapConnBundleTOs.get(location.getModelObject())
                    .get(connectorName.getModelObject()).keySet());
            version.setChoices(versions);
            version.setEnabled(true);
            if (versions.size() == 1) {
                selectVersion(target, connInstanceTO, version, versions.get(0));
                version.getField().setModelObject(versions.get(0));
            } else {
                version.getField().setModelValue(null);
                properties.clear();
                target.add(propertiesContainer);
            }
            target.add(version);
        }
    });
    version.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            selectVersion(target, connInstanceTO, version, version.getModelObject());
        }
    });

    // form - second tab (properties)
    final ListView<ConnConfProperty> connPropView = new ConnConfPropertyListView("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "properties"), true,
            connInstanceTO.getConfiguration());
    connPropView.setOutputMarkupId(true);
    connectorPropForm.add(connPropView);

    final AjaxButton check = new IndicatingAjaxButton("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            // ensure that connector bundle information is in sync
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.setConnectorName(bundleTO.getConnectorName());

            if (connectorRestClient.check(conn)) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            feedbackPanel.refresh(target);
        }
    };
    connectorPropForm.add(check);

    // form - third tab (capabilities)
    final IModel<List<ConnectorCapability>> capabilities = new LoadableDetachableModel<List<ConnectorCapability>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnectorCapability> load() {
            return Arrays.asList(ConnectorCapability.values());
        }
    };
    CheckBoxMultipleChoice<ConnectorCapability> capabilitiesPalette = new CheckBoxMultipleChoice<>(
            "capabilitiesPalette", new PropertyModel<List<ConnectorCapability>>(this, "selectedCapabilities"),
            capabilities);

    capabilitiesPalette.add(new AjaxFormChoiceComponentUpdatingBehavior() {

        private static final long serialVersionUID = -1107858522700306810L;

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

    connectorForm.add(capabilitiesPalette);

    // form - submit / cancel buttons
    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            conn.setConnectorName(bundleTO.getConnectorName());
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.getConfiguration().clear();
            conn.getConfiguration().addAll(connPropView.getModelObject());

            // Set the model object's capabilities to capabilitiesPalette's converted Set
            conn.getCapabilities().clear();
            conn.getCapabilities()
                    .addAll(selectedCapabilities.isEmpty() ? EnumSet.noneOf(ConnectorCapability.class)
                            : EnumSet.copyOf(selectedCapabilities));

            // Reset pool configuration if all fields are null
            if (conn.getPoolConf() != null && conn.getPoolConf().getMaxIdle() == null
                    && conn.getPoolConf().getMaxObjects() == null && conn.getPoolConf().getMaxWait() == null
                    && conn.getPoolConf().getMinEvictableIdleTimeMillis() == null
                    && conn.getPoolConf().getMinIdle() == null) {

                conn.setPoolConf(null);
            }

            try {
                if (connInstanceTO.getKey() == 0) {
                    connectorRestClient.create(conn);
                } else {
                    connectorRestClient.update(conn);
                }

                ((BasePage) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                feedbackPanel.refresh(target);
                ((BasePage) pageRef.getPage()).setModalResult(false);
                LOG.error("While creating or updating connector {}", conn, e);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };
    String entitlements = connInstanceTO.getKey() == 0 ? Entitlement.CONNECTOR_CREATE
            : Entitlement.CONNECTOR_UPDATE;

    MetaDataRoleAuthorizationStrategy.authorize(submit, ENABLE, entitlements);
    connectorForm.add(submit);

    final IndicatingAjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            window.close(target);
        }
    };
    cancel.setDefaultFormProcessing(false);
    connectorForm.add(cancel);
}

From source file:org.apache.syncope.client.console.panels.ResourceConnConfPanel.java

License:Apache License

public ResourceConnConfPanel(final String id, final ResourceTO resourceTO, final boolean createFlag) {
    super(id);//  www.  j  a va  2s  . c  o m
    setOutputMarkupId(true);

    this.createFlag = createFlag;
    this.resourceTO = resourceTO;

    connConfProperties = getConnConfProperties();

    connConfPropContainer = new WebMarkupContainer("connectorPropertiesContainer");
    connConfPropContainer.setOutputMarkupId(true);
    add(connConfPropContainer);

    /*
     * the list of overridable connector properties
     */
    final ListView<ConnConfProperty> connPropView = new ConnConfPropertyListView("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "connConfProperties"), false,
            resourceTO.getConnConfProperties());
    connPropView.setOutputMarkupId(true);
    connConfPropContainer.add(connPropView);

    check = new IndicatingAjaxButton("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -4199438518229098169L;

        @Override
        public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ResourceTO resourceTO = (ResourceTO) form.getModelObject();

            if (restClient.check(resourceTO)) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            ((BaseModalPage) getPage()).getFeedbackPanel().refresh(target);
        }
    };

    check.setEnabled(!connConfProperties.isEmpty());
    connConfPropContainer.add(check);
}

From source file:org.apache.syncope.client.console.topology.Topology.java

License:Apache License

public Topology() {
    modal = new BaseModal<>("resource-modal");
    body.add(modal.size(Modal.Size.Large));
    modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {

        private static final long serialVersionUID = 8804221891699487139L;

        @Override//from   w  w w  .j a  va2  s  . co  m
        public void onClose(final AjaxRequestTarget target) {
            modal.show(false);
        }
    });

    body.add(new TopologyWebSocketBehavior());

    togglePanel = new TopologyTogglePanel("toggle", getPageReference());
    body.add(togglePanel);

    // -----------------------------------------
    // Add Zoom panel
    // -----------------------------------------
    final ActionLinksPanel.Builder<Serializable> zoomActionPanel = ActionLinksPanel.builder();
    zoomActionPanel.setDisableIndicator(true);

    zoomActionPanel.add(new ActionLink<Serializable>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
            target.appendJavaScript("zoomIn($('#drawing')[0]);");
        }
    }, ActionLink.ActionType.ZOOM_IN, StandardEntitlement.RESOURCE_LIST).add(new ActionLink<Serializable>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
            target.appendJavaScript("zoomOut($('#drawing')[0]);");
        }
    }, ActionLink.ActionType.ZOOM_OUT, StandardEntitlement.RESOURCE_LIST);

    body.add(zoomActionPanel.build("zoom"));
    // -----------------------------------------

    // -----------------------------------------
    // Add Syncope (root topologynode)
    // -----------------------------------------
    final TopologyNode syncopeTopologyNode = new TopologyNode(ROOT_NAME, ROOT_NAME, TopologyNode.Kind.SYNCOPE);
    syncopeTopologyNode.setX(origX);
    syncopeTopologyNode.setY(origY);

    final URI uri = WebClient.client(BaseRestClient.getSyncopeService()).getBaseURI();
    syncopeTopologyNode.setHost(uri.getHost());
    syncopeTopologyNode.setPort(uri.getPort());

    body.add(topologyNodePanel("syncope", syncopeTopologyNode));

    final Map<Serializable, Map<Serializable, TopologyNode>> connections = new HashMap<>();
    final Map<Serializable, TopologyNode> syncopeConnections = new HashMap<>();
    connections.put(syncopeTopologyNode.getKey(), syncopeConnections);

    // required to retrieve parent positions
    final Map<String, TopologyNode> servers = new HashMap<>();
    final Map<String, TopologyNode> connectors = new HashMap<>();
    // -----------------------------------------

    // -----------------------------------------
    // Add Connector Servers
    // -----------------------------------------
    final ListView<URI> connectorServers = new ListView<URI>("connectorServers",
            csModel.getObject().getLeft()) {

        private static final long serialVersionUID = 6978621871488360380L;

        private final int size = csModel.getObject().getLeft().size() + 1;

        @Override
        protected void populateItem(final ListItem<URI> item) {
            int kx = size >= 4 ? 800 : (200 * size);

            int x = (int) Math.round(origX + kx * Math.cos(Math.PI + Math.PI * (item.getIndex() + 1) / size));
            int y = (int) Math.round(origY + 100 * Math.sin(Math.PI + Math.PI * (item.getIndex() + 1) / size));

            final URI location = item.getModelObject();
            final String url = location.toASCIIString();

            final TopologyNode topologynode = new TopologyNode(url, url, TopologyNode.Kind.CONNECTOR_SERVER);

            topologynode.setHost(location.getHost());
            topologynode.setPort(location.getPort());
            topologynode.setX(x);
            topologynode.setY(y);

            servers.put(String.class.cast(topologynode.getKey()), topologynode);

            item.add(topologyNodePanel("cs", topologynode));

            syncopeConnections.put(url, topologynode);
            connections.put(url, new HashMap<Serializable, TopologyNode>());
        }
    };

    connectorServers.setOutputMarkupId(true);
    body.add(connectorServers);
    // -----------------------------------------

    // -----------------------------------------
    // Add File Paths
    // -----------------------------------------
    final ListView<URI> filePaths = new ListView<URI>("filePaths", csModel.getObject().getRight()) {

        private static final long serialVersionUID = 6978621871488360380L;

        private final int size = csModel.getObject().getRight().size() + 1;

        @Override
        protected void populateItem(final ListItem<URI> item) {
            int kx = size >= 4 ? 800 : (200 * size);

            int x = (int) Math.round(origX + kx * Math.cos(Math.PI * (item.getIndex() + 1) / size));
            int y = (int) Math.round(origY + 100 * Math.sin(Math.PI * (item.getIndex() + 1) / size));

            final URI location = item.getModelObject();
            final String url = location.toASCIIString();

            final TopologyNode topologynode = new TopologyNode(url, url, TopologyNode.Kind.FS_PATH);

            topologynode.setHost(location.getHost());
            topologynode.setPort(location.getPort());
            topologynode.setX(x);
            topologynode.setY(y);

            servers.put(String.class.cast(topologynode.getKey()), topologynode);

            item.add(topologyNodePanel("fp", topologynode));

            syncopeConnections.put(url, topologynode);
            connections.put(url, new HashMap<Serializable, TopologyNode>());
        }
    };

    filePaths.setOutputMarkupId(true);
    body.add(filePaths);
    // -----------------------------------------

    // -----------------------------------------
    // Add Connector Intances
    // -----------------------------------------
    final List<List<ConnInstanceTO>> allConns = new ArrayList<>(connModel.getObject().values());

    final ListView<List<ConnInstanceTO>> conns = new ListView<List<ConnInstanceTO>>("conns", allConns) {

        private static final long serialVersionUID = 697862187148836036L;

        @Override
        protected void populateItem(final ListItem<List<ConnInstanceTO>> item) {

            final int size = item.getModelObject().size() + 1;

            final ListView<ConnInstanceTO> conns = new ListView<ConnInstanceTO>("conns",
                    item.getModelObject()) {

                private static final long serialVersionUID = 6978621871488360381L;

                @Override
                protected void populateItem(final ListItem<ConnInstanceTO> item) {
                    final ConnInstanceTO conn = item.getModelObject();

                    final TopologyNode topologynode = new TopologyNode(conn.getKey(), conn.getDisplayName(),
                            TopologyNode.Kind.CONNECTOR);

                    // Define the parent note
                    final TopologyNode parent = servers.get(conn.getLocation());

                    // Set the position
                    int kx = size >= 6 ? 800 : (130 * size);

                    final double hpos;
                    if (conn.getLocation().startsWith(CONNECTOR_SERVER_LOCATION_PREFIX)) {
                        hpos = Math.PI;
                    } else {
                        hpos = 0.0;
                    }

                    int x = (int) Math.round((parent == null ? origX : parent.getX())
                            + kx * Math.cos(hpos + Math.PI * (item.getIndex() + 1) / size));
                    int y = (int) Math.round((parent == null ? origY : parent.getY())
                            + 100 * Math.sin(hpos + Math.PI * (item.getIndex() + 1) / size));

                    topologynode.setConnectionDisplayName(conn.getBundleName());
                    topologynode.setX(x);
                    topologynode.setY(y);

                    connectors.put(String.class.cast(topologynode.getKey()), topologynode);
                    item.add(topologyNodePanel("conn", topologynode));

                    // Update connections
                    final Map<Serializable, TopologyNode> remoteConnections;

                    if (connections.containsKey(conn.getLocation())) {
                        remoteConnections = connections.get(conn.getLocation());
                    } else {
                        remoteConnections = new HashMap<>();
                        connections.put(conn.getLocation(), remoteConnections);
                    }
                    remoteConnections.put(conn.getKey(), topologynode);
                }
            };

            conns.setOutputMarkupId(true);
            item.add(conns);
        }
    };

    conns.setOutputMarkupId(true);
    body.add(conns);
    // -----------------------------------------

    // -----------------------------------------
    // Add Resources
    // -----------------------------------------
    final List<String> connToBeProcessed = new ArrayList<>();
    for (ResourceTO resourceTO : resModel.getObject()) {
        final TopologyNode topologynode = new TopologyNode(resourceTO.getKey(), resourceTO.getKey(),
                TopologyNode.Kind.RESOURCE);

        final Map<Serializable, TopologyNode> remoteConnections;

        if (connections.containsKey(resourceTO.getConnector())) {
            remoteConnections = connections.get(resourceTO.getConnector());
        } else {
            remoteConnections = new HashMap<>();
            connections.put(resourceTO.getConnector(), remoteConnections);
        }

        remoteConnections.put(topologynode.getKey(), topologynode);

        if (!connToBeProcessed.contains(resourceTO.getConnector())) {
            connToBeProcessed.add(resourceTO.getConnector());
        }
    }

    final ListView<String> resources = new ListView<String>("resources", connToBeProcessed) {

        private static final long serialVersionUID = 697862187148836038L;

        @Override
        protected void populateItem(final ListItem<String> item) {
            final String connectorKey = item.getModelObject();

            final ListView<TopologyNode> innerListView = new ListView<TopologyNode>("resources",
                    new ArrayList<>(connections.get(connectorKey).values())) {

                private static final long serialVersionUID = 1L;

                private final int size = getModelObject().size() + 1;

                @Override
                protected void populateItem(final ListItem<TopologyNode> item) {
                    final TopologyNode topologynode = item.getModelObject();
                    final TopologyNode parent = connectors.get(connectorKey);

                    // Set position
                    int kx = size >= 16 ? 800 : (48 * size);
                    int ky = size < 4 ? 100 : size < 6 ? 350 : 750;

                    final double hpos;
                    if (parent == null || parent.getY() < syncopeTopologyNode.getY()) {
                        hpos = Math.PI;
                    } else {
                        hpos = 0.0;
                    }

                    int x = (int) Math.round((parent == null ? origX : parent.getX())
                            + kx * Math.cos(hpos + Math.PI * (item.getIndex() + 1) / size));
                    int y = (int) Math.round((parent == null ? origY : parent.getY())
                            + ky * Math.sin(hpos + Math.PI * (item.getIndex() + 1) / size));

                    topologynode.setX(x);
                    topologynode.setY(y);

                    item.add(topologyNodePanel("res", topologynode));
                }
            };

            innerListView.setOutputMarkupId(true);
            item.add(innerListView);
        }
    };

    resources.setOutputMarkupId(true);
    body.add(resources);
    // -----------------------------------------

    // -----------------------------------------
    // Create connections
    // -----------------------------------------
    final WebMarkupContainer jsPlace = new WebMarkupContainerNoVeil("jsPlace");
    jsPlace.setOutputMarkupId(true);
    body.add(jsPlace);

    jsPlace.add(new Behavior() {

        private static final long serialVersionUID = 2661717818979056044L;

        @Override
        public void renderHead(final Component component, final IHeaderResponse response) {
            final StringBuilder jsPlumbConf = new StringBuilder();
            jsPlumbConf.append(String.format(Locale.US, "activate(%.2f);", 0.68f));

            for (String str : createConnections(connections)) {
                jsPlumbConf.append(str);
            }

            response.render(OnDomReadyHeaderItem.forScript(jsPlumbConf.toString()));
        }
    });

    jsPlace.add(new AbstractAjaxTimerBehavior(Duration.seconds(2)) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onTimer(final AjaxRequestTarget target) {
            target.appendJavaScript("checkConnection()");

            if (getUpdateInterval().seconds() < 5.0) {
                setUpdateInterval(Duration.seconds(5));
            } else if (getUpdateInterval().seconds() < 10.0) {
                setUpdateInterval(Duration.seconds(10));
            } else if (getUpdateInterval().seconds() < 15.0) {
                setUpdateInterval(Duration.seconds(15));
            } else if (getUpdateInterval().seconds() < 20.0) {
                setUpdateInterval(Duration.seconds(20));
            } else if (getUpdateInterval().seconds() < 30.0) {
                setUpdateInterval(Duration.seconds(30));
            } else if (getUpdateInterval().seconds() < 60.0) {
                setUpdateInterval(Duration.seconds(60));
            }
        }
    });
    // -----------------------------------------

    newlyCreatedContainer = new WebMarkupContainer("newlyCreatedContainer");
    newlyCreatedContainer.setOutputMarkupId(true);
    body.add(newlyCreatedContainer);

    newlyCreated = new ListView<TopologyNode>("newlyCreated", new ArrayList<TopologyNode>()) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<TopologyNode> item) {
            item.add(topologyNodePanel("el", item.getModelObject()));
        }
    };
    newlyCreated.setOutputMarkupId(true);
    newlyCreated.setReuseItems(true);

    newlyCreatedContainer.add(newlyCreated);
}