Search in sources :

Example 1 with SwitchItem

use of org.jboss.hal.ballroom.form.SwitchItem in project console by hal.

the class ResetServerDialog method reset.

void reset(String messagingServer) {
    LabelBuilder labelBuilder = new LabelBuilder();
    String l1 = labelBuilder.label(RESET_ALL_MESSAGE_COUNTERS);
    Property p1 = metadata.getDescription().findOperation(RESET_ALL_MESSAGE_COUNTERS);
    if (p1 != null && p1.getValue().hasDefined(DESCRIPTION)) {
        l1 = p1.getValue().get(DESCRIPTION).asString();
        l1 = Strings.sanitize(l1);
    }
    String l2 = labelBuilder.label(RESET_ALL_MESSAGE_COUNTER_HISTORIES);
    Property p2 = metadata.getDescription().findOperation(RESET_ALL_MESSAGE_COUNTER_HISTORIES);
    if (p2 != null && p2.getValue().hasDefined(DESCRIPTION)) {
        l2 = p2.getValue().get(DESCRIPTION).asString();
        l2 = Strings.sanitize(l2);
    }
    Form<ModelNode> form = new ModelNodeForm.Builder<>(Ids.RESET_MESSAGE_COUNTERS, Metadata.empty()).unboundFormItem(new SwitchItem(RESET_ALL_MESSAGE_COUNTERS, l1)).unboundFormItem(new SwitchItem(RESET_ALL_MESSAGE_COUNTER_HISTORIES, l2)).onSave((f, changedValues) -> column.resetServer(messagingServer, !f.getFormItem(RESET_ALL_MESSAGE_COUNTERS).isEmpty(), !f.getFormItem(RESET_ALL_MESSAGE_COUNTER_HISTORIES).isEmpty())).build();
    form.addFormValidation(new RequireAtLeastOneAttributeValidation<>(asList(RESET_ALL_MESSAGE_COUNTERS, RESET_ALL_MESSAGE_COUNTER_HISTORIES), resources));
    // Make the long labels more readable
    stream(form.element().querySelectorAll("." + halFormLabel + ", ." + halFormInput)).filter(htmlElements()).map(asHtmlElement()).forEach(element -> element.style.width = WidthUnionType.of("50%"));
    Dialog dialog = new Dialog.Builder(resources.constants().reset()).add(form.element()).primary(resources.constants().reset(), form::save).size(Size.MEDIUM).closeIcon(true).closeOnEsc(true).cancel().build();
    dialog.registerAttachable(form);
    form.edit(new ModelNode());
    dialog.show();
}
Also used : ModelNode(org.jboss.hal.dmr.ModelNode) Dialog(org.jboss.hal.ballroom.dialog.Dialog) RESET_ALL_MESSAGE_COUNTERS(org.jboss.hal.dmr.ModelDescriptionConstants.RESET_ALL_MESSAGE_COUNTERS) Size(org.jboss.hal.ballroom.dialog.Dialog.Size) Ids(org.jboss.hal.resources.Ids) Elements.stream(org.jboss.gwt.elemento.core.Elements.stream) Elements.asHtmlElement(org.jboss.gwt.elemento.core.Elements.asHtmlElement) CSS.halFormLabel(org.jboss.hal.resources.CSS.halFormLabel) ModelNodeForm(org.jboss.hal.core.mbui.form.ModelNodeForm) Elements.htmlElements(org.jboss.gwt.elemento.core.Elements.htmlElements) Property(org.jboss.hal.dmr.Property) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem) RESET_ALL_MESSAGE_COUNTER_HISTORIES(org.jboss.hal.dmr.ModelDescriptionConstants.RESET_ALL_MESSAGE_COUNTER_HISTORIES) Resources(org.jboss.hal.resources.Resources) DESCRIPTION(org.jboss.hal.dmr.ModelDescriptionConstants.DESCRIPTION) Arrays.asList(java.util.Arrays.asList) RequireAtLeastOneAttributeValidation(org.jboss.hal.core.mbui.form.RequireAtLeastOneAttributeValidation) Strings(org.jboss.hal.resources.Strings) WidthUnionType(elemental2.dom.CSSProperties.WidthUnionType) Metadata(org.jboss.hal.meta.Metadata) CSS.halFormInput(org.jboss.hal.resources.CSS.halFormInput) Form(org.jboss.hal.ballroom.form.Form) Dialog(org.jboss.hal.ballroom.dialog.Dialog) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) ModelNode(org.jboss.hal.dmr.ModelNode) Property(org.jboss.hal.dmr.Property) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem)

Example 2 with SwitchItem

use of org.jboss.hal.ballroom.form.SwitchItem in project console by hal.

the class RoleColumn method editScopedRole.

private void editScopedRole(Role role, String type, AddressTemplate template, AddressTemplate typeaheadTemplate, String formId, String scopeAttribute) {
    Metadata metadata = metadataRegistry.lookup(template);
    Form<ModelNode> form = new ModelNodeForm.Builder<>(formId, metadata).include(BASE_ROLE, scopeAttribute).customFormItem(BASE_ROLE, attributeDescription -> {
        SingleSelectBoxItem item = new SingleSelectBoxItem(BASE_ROLE, new LabelBuilder().label(BASE_ROLE), standardRoleNames, false);
        item.setRequired(true);
        return item;
    }).unboundFormItem(new SwitchItem(INCLUDE_ALL, new LabelBuilder().label(INCLUDE_ALL)), 2, resources.messages().includeAllHelpText()).build();
    form.getFormItem(scopeAttribute).setRequired(true);
    form.getFormItem(scopeAttribute).registerSuggestHandler(new ReadChildrenAutoComplete(dispatcher, statementContext, typeaheadTemplate));
    form.getFormItem(INCLUDE_ALL).setValue(role.isIncludeAll());
    form.attach();
    ModelNode modelNode = new ModelNode();
    modelNode.get(BASE_ROLE).set(role.getBaseRole().getName());
    role.getScope().forEach(scope -> modelNode.get(scopeAttribute).add(scope));
    new ModifyResourceDialog(resources.messages().modifyResourceTitle(type), form, (frm, changedValues) -> {
        boolean includeAll = frm.<Boolean>getFormItem(INCLUDE_ALL).getValue();
        boolean includeAllChanged = includeAll != role.isIncludeAll();
        List<Task<FlowContext>> tasks = new ArrayList<>();
        if (!changedValues.isEmpty()) {
            tasks.add(new ModifyScopedRole(dispatcher, role, changedValues, metadata));
        }
        if (includeAllChanged) {
            tasks.add(new ModifyIncludeAll(dispatcher, role, includeAll));
        }
        series(new FlowContext(progress.get()), tasks).subscribe(new SuccessfulOutcome<FlowContext>(eventBus, resources) {

            @Override
            public void onSuccess(FlowContext context) {
                MessageEvent.fire(eventBus, Message.success(resources.messages().modifyResourceSuccess(type, role.getName())));
                accessControl.reload(() -> {
                    refresh(role.getId());
                    eventBus.fireEvent(new RolesChangedEvent());
                });
            }
        });
    }).show(modelNode);
}
Also used : Provider(javax.inject.Provider) Environment(org.jboss.hal.config.Environment) StatementContext(org.jboss.hal.meta.StatementContext) AddScopedRole(org.jboss.hal.client.accesscontrol.AccessControlTasks.AddScopedRole) ItemDisplay(org.jboss.hal.core.finder.ItemDisplay) AddResourceDialog(org.jboss.hal.core.mbui.dialog.AddResourceDialog) HTMLElement(elemental2.dom.HTMLElement) Message(org.jboss.hal.spi.Message) SafeHtmlBuilder(com.google.gwt.safehtml.shared.SafeHtmlBuilder) Metadata(org.jboss.hal.meta.Metadata) CheckRoleMapping(org.jboss.hal.client.accesscontrol.AccessControlTasks.CheckRoleMapping) Settings(org.jboss.hal.config.Settings) SingleSelectBoxItem(org.jboss.hal.ballroom.form.SingleSelectBoxItem) ModifyResourceDialog(org.jboss.hal.core.mbui.dialog.ModifyResourceDialog) RemoveAssignments(org.jboss.hal.client.accesscontrol.AccessControlTasks.RemoveAssignments) List(java.util.List) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) MetadataRegistry(org.jboss.hal.meta.MetadataRegistry) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem) ModelDescriptionConstants(org.jboss.hal.dmr.ModelDescriptionConstants) Flow.series(org.jboss.hal.flow.Flow.series) Role(org.jboss.hal.config.Role) Finder(org.jboss.hal.core.finder.Finder) Footer(org.jboss.hal.spi.Footer) Elements.small(org.jboss.gwt.elemento.core.Elements.small) CSS.subtitle(org.jboss.hal.resources.CSS.subtitle) ModelNode(org.jboss.hal.dmr.ModelNode) RemoveScopedRole(org.jboss.hal.client.accesscontrol.AccessControlTasks.RemoveScopedRole) AsyncColumn(org.jboss.hal.spi.AsyncColumn) MessageEvent(org.jboss.hal.spi.MessageEvent) SuccessfulOutcome(org.jboss.hal.core.SuccessfulOutcome) ColumnAction(org.jboss.hal.core.finder.ColumnAction) ItemAction(org.jboss.hal.core.finder.ItemAction) FlowContext(org.jboss.hal.flow.FlowContext) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ModelNodeForm(org.jboss.hal.core.mbui.form.ModelNodeForm) AddRoleMapping(org.jboss.hal.client.accesscontrol.AccessControlTasks.AddRoleMapping) Task(org.jboss.hal.flow.Task) ModifyIncludeAll(org.jboss.hal.client.accesscontrol.AccessControlTasks.ModifyIncludeAll) Progress(org.jboss.hal.flow.Progress) AddressTemplate(org.jboss.hal.meta.AddressTemplate) RemoveRoleMapping(org.jboss.hal.client.accesscontrol.AccessControlTasks.RemoveRoleMapping) FinderColumn(org.jboss.hal.core.finder.FinderColumn) NameItem(org.jboss.hal.core.mbui.dialog.NameItem) Comparator.comparing(java.util.Comparator.comparing) ModifyScopedRole(org.jboss.hal.client.accesscontrol.AccessControlTasks.ModifyScopedRole) RolesChangedEvent(org.jboss.hal.config.RolesChangedEvent) AddressTemplates(org.jboss.hal.client.accesscontrol.AddressTemplates) ColumnActionFactory(org.jboss.hal.core.finder.ColumnActionFactory) Requires(org.jboss.hal.spi.Requires) CSS.itemText(org.jboss.hal.resources.CSS.itemText) Ids(org.jboss.hal.resources.Ids) EventBus(com.google.web.bindery.event.shared.EventBus) CSS.pfIcon(org.jboss.hal.resources.CSS.pfIcon) ReadChildrenAutoComplete(org.jboss.hal.ballroom.autocomplete.ReadChildrenAutoComplete) DialogFactory(org.jboss.hal.ballroom.dialog.DialogFactory) Dispatcher(org.jboss.hal.dmr.dispatch.Dispatcher) Collectors.toList(java.util.stream.Collectors.toList) Resources(org.jboss.hal.resources.Resources) RUN_AS(org.jboss.hal.config.Settings.Key.RUN_AS) Elements.span(org.jboss.gwt.elemento.core.Elements.span) Form(org.jboss.hal.ballroom.form.Form) SingleSelectBoxItem(org.jboss.hal.ballroom.form.SingleSelectBoxItem) SafeHtmlBuilder(com.google.gwt.safehtml.shared.SafeHtmlBuilder) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) Metadata(org.jboss.hal.meta.Metadata) ModifyScopedRole(org.jboss.hal.client.accesscontrol.AccessControlTasks.ModifyScopedRole) FlowContext(org.jboss.hal.flow.FlowContext) RolesChangedEvent(org.jboss.hal.config.RolesChangedEvent) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) List(java.util.List) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) ModifyIncludeAll(org.jboss.hal.client.accesscontrol.AccessControlTasks.ModifyIncludeAll) ModelNode(org.jboss.hal.dmr.ModelNode) SuccessfulOutcome(org.jboss.hal.core.SuccessfulOutcome) ReadChildrenAutoComplete(org.jboss.hal.ballroom.autocomplete.ReadChildrenAutoComplete) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem) ModifyResourceDialog(org.jboss.hal.core.mbui.dialog.ModifyResourceDialog)

Example 3 with SwitchItem

use of org.jboss.hal.ballroom.form.SwitchItem in project console by hal.

the class StandaloneServerPresenter method disableSslForManagementInterface.

@Override
@SuppressWarnings("DuplicatedCode")
public void disableSslForManagementInterface() {
    Constants constants = resources.constants();
    String serverName = environment.isStandalone() ? Names.STANDALONE_SERVER : Names.DOMAIN_CONTROLLER;
    String label = constants.reload() + " " + serverName;
    SwitchItem reload = new SwitchItem(RELOAD, label);
    reload.setExpressionAllowed(false);
    Form<ModelNode> form = new ModelNodeForm.Builder<>(Ids.build(RELOAD, FORM), Metadata.empty()).unboundFormItem(reload).build();
    form.attach();
    HTMLElement formElement = form.element();
    ModelNode model = new ModelNode();
    model.setEmptyObject();
    form.edit(model);
    ResourceAddress httpAddress = HTTP_INTERFACE_TEMPLATE.resolve(statementContext);
    DialogFactory.buildConfirmation(constants.disableSSL(), resources.messages().disableSSLManagementQuestion(serverName), formElement, Dialog.Size.MEDIUM, () -> {
        List<Task<FlowContext>> tasks = new ArrayList<>();
        // load the http-interface resource to get the port, there are differente attributes for
        // standalone and domain mode.
        Task<FlowContext> loadHttpInterface = flowContext -> {
            Operation readHttpInterface = new Operation.Builder(httpAddress, READ_RESOURCE_OPERATION).build();
            return dispatcher.execute(readHttpInterface).doOnSuccess(value -> {
                if (value.hasDefined(SOCKET_BINDING)) {
                    // standalone mode uses a socket-binding for port
                    // store the socket-binding name in the flow context and on a later call
                    // read the socket-binding-group=<s-b-g>/socket-binding=<http-binding> to
                    // retrieve the port number
                    flowContext.set(SOCKET_BINDING, value.get(SOCKET_BINDING).asString());
                }
            }).toCompletable();
        };
        tasks.add(loadHttpInterface);
        // if standalone mode, read the socket-binding-group=<s-b-g>/socket-binding=<http-binding>
        // to retrieve the port number
        Task<FlowContext> readHttpPortTask = flowContext -> {
            Operation op = new Operation.Builder(ResourceAddress.root(), READ_CHILDREN_NAMES_OPERATION).param(CHILD_TYPE, SOCKET_BINDING_GROUP).build();
            return dispatcher.execute(op).doOnSuccess(result -> {
                String sbg = result.asList().get(0).asString();
                String httpBinding = flowContext.get(SOCKET_BINDING);
                ResourceAddress address = SOCKET_BINDING_GROUP_TEMPLATE.resolve(statementContext, sbg, httpBinding);
                Operation readPort = new Operation.Builder(address, READ_ATTRIBUTE_OPERATION).param(NAME, PORT).param(RESOLVE_EXPRESSIONS, true).build();
                dispatcher.execute(readPort, portResult -> flowContext.set(PORT, portResult.asString()));
            }).toCompletable();
        };
        tasks.add(readHttpPortTask);
        // as part of the disable ssl task, undefine the secure-socket-binding
        // the attribute only exists in standalone mode
        Task<FlowContext> undefSslTask = flowContext -> {
            Operation op = new Operation.Builder(httpAddress, UNDEFINE_ATTRIBUTE_OPERATION).param(NAME, SECURE_SOCKET_BINDING).build();
            return dispatcher.execute(op).toCompletable();
        };
        tasks.add(undefSslTask);
        // as part of the disable ssl task, undefine the ssl-context
        Task<FlowContext> undefineSslContextTask = flowContext -> {
            Operation op = new Operation.Builder(httpAddress, UNDEFINE_ATTRIBUTE_OPERATION).param(NAME, SSL_CONTEXT).build();
            return dispatcher.execute(op).toCompletable();
        };
        tasks.add(undefineSslContextTask);
        series(new FlowContext(progress.get()), tasks).subscribe(new SuccessfulOutcome<FlowContext>(getEventBus(), resources) {

            @Override
            public void onSuccess(FlowContext flowContext) {
                if (reload.getValue() != null && reload.getValue()) {
                    String port = flowContext.get(PORT).toString();
                    // extracts the url search path, so the reload shows the same view the use is on
                    String urlSuffix = window.location.getHref();
                    urlSuffix = urlSuffix.substring(urlSuffix.indexOf("//") + 2);
                    urlSuffix = urlSuffix.substring(urlSuffix.indexOf("/"));
                    // the location to redirect the browser to the unsecure URL
                    // TODO Replace hardcoded scheme
                    String location = "http://" + window.location.getHostname() + ":" + port + urlSuffix;
                    reloadServer(null, location);
                } else {
                    reload();
                    MessageEvent.fire(getEventBus(), Message.success(resources.messages().disableSSLManagementSuccess()));
                }
            }

            @Override
            public void onError(FlowContext context, Throwable throwable) {
                MessageEvent.fire(getEventBus(), Message.error(resources.messages().disableSSLManagementError(throwable.getMessage())));
            }
        });
    }).show();
}
Also used : Dialog(org.jboss.hal.ballroom.dialog.Dialog) INCLUDE_RUNTIME(org.jboss.hal.dmr.ModelDescriptionConstants.INCLUDE_RUNTIME) LIST_REMOVE_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.LIST_REMOVE_OPERATION) Provider(javax.inject.Provider) Environment(org.jboss.hal.config.Environment) StatementContext(org.jboss.hal.meta.StatementContext) TopologyTasks.reloadBlocking(org.jboss.hal.core.runtime.TopologyTasks.reloadBlocking) ResourceAddress(org.jboss.hal.dmr.ResourceAddress) SOCKET_BINDING(org.jboss.hal.dmr.ModelDescriptionConstants.SOCKET_BINDING) VALUE(org.jboss.hal.dmr.ModelDescriptionConstants.VALUE) HTMLElement(elemental2.dom.HTMLElement) Map(java.util.Map) Message(org.jboss.hal.spi.Message) KEY_MANAGER(org.jboss.hal.dmr.ModelDescriptionConstants.KEY_MANAGER) NAME(org.jboss.hal.dmr.ModelDescriptionConstants.NAME) UNDEFINE_ATTRIBUTE_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION) READ_RESOURCE_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.READ_RESOURCE_OPERATION) SOCKET_BINDING_GROUP(org.jboss.hal.dmr.ModelDescriptionConstants.SOCKET_BINDING_GROUP) Server(org.jboss.hal.core.runtime.server.Server) LIST_ADD_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.LIST_ADD_OPERATION) HttpManagementInterfacePresenter(org.jboss.hal.client.runtime.managementinterface.HttpManagementInterfacePresenter) Metadata(org.jboss.hal.meta.Metadata) Names(org.jboss.hal.resources.Names) PORT(org.jboss.hal.dmr.ModelDescriptionConstants.PORT) SOCKET_BINDING_GROUP_TEMPLATE(org.jboss.hal.client.shared.sslwizard.AbstractConfiguration.SOCKET_BINDING_GROUP_TEMPLATE) CrudOperations(org.jboss.hal.core.CrudOperations) RESOLVE_EXPRESSIONS(org.jboss.hal.dmr.ModelDescriptionConstants.RESOLVE_EXPRESSIONS) NameToken(com.gwtplatform.mvp.client.annotations.NameToken) INDEX(org.jboss.hal.dmr.ModelDescriptionConstants.INDEX) FinderPath(org.jboss.hal.core.finder.FinderPath) SECURE_SOCKET_BINDING(org.jboss.hal.dmr.ModelDescriptionConstants.SECURE_SOCKET_BINDING) FORM(org.jboss.hal.resources.Ids.FORM) Collectors(java.util.stream.Collectors) List(java.util.List) OperationFactory(org.jboss.hal.core.OperationFactory) PATH(org.jboss.hal.dmr.ModelDescriptionConstants.PATH) RESULT(org.jboss.hal.dmr.ModelDescriptionConstants.RESULT) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem) Flow.series(org.jboss.hal.flow.Flow.series) Finder(org.jboss.hal.core.finder.Finder) Footer(org.jboss.hal.spi.Footer) SafeHtml(com.google.gwt.safehtml.shared.SafeHtml) SupportsExpertMode(org.jboss.hal.core.mvp.SupportsExpertMode) ModelNode(org.jboss.hal.dmr.ModelNode) ATTRIBUTES_ONLY(org.jboss.hal.dmr.ModelDescriptionConstants.ATTRIBUTES_ONLY) MessageEvent(org.jboss.hal.spi.MessageEvent) ProxyPlace(com.gwtplatform.mvp.client.proxy.ProxyPlace) SuccessfulOutcome(org.jboss.hal.core.SuccessfulOutcome) CHILD_TYPE(org.jboss.hal.dmr.ModelDescriptionConstants.CHILD_TYPE) KEY_STORE(org.jboss.hal.dmr.ModelDescriptionConstants.KEY_STORE) HashMap(java.util.HashMap) CONSTANT_HEADERS(org.jboss.hal.dmr.ModelDescriptionConstants.CONSTANT_HEADERS) FlowContext(org.jboss.hal.flow.FlowContext) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ModelNodeForm(org.jboss.hal.core.mbui.form.ModelNodeForm) Task(org.jboss.hal.flow.Task) RELOAD(org.jboss.hal.dmr.ModelDescriptionConstants.RELOAD) Progress(org.jboss.hal.flow.Progress) AddressTemplate(org.jboss.hal.meta.AddressTemplate) Constants(org.jboss.hal.resources.Constants) TRUST_MANAGER(org.jboss.hal.dmr.ModelDescriptionConstants.TRUST_MANAGER) Requires(org.jboss.hal.spi.Requires) CompositeResult(org.jboss.hal.dmr.CompositeResult) ProxyCodeSplit(com.gwtplatform.mvp.client.annotations.ProxyCodeSplit) EnableSSLWizard(org.jboss.hal.client.shared.sslwizard.EnableSSLWizard) SSL_CONTEXT(org.jboss.hal.dmr.ModelDescriptionConstants.SSL_CONTEXT) Operation(org.jboss.hal.dmr.Operation) Ids(org.jboss.hal.resources.Ids) FinderPathFactory(org.jboss.hal.core.finder.FinderPathFactory) EventBus(com.google.web.bindery.event.shared.EventBus) READ_ATTRIBUTE_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION) WRITE_ATTRIBUTE_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION) DialogFactory(org.jboss.hal.ballroom.dialog.DialogFactory) DomGlobal.window(elemental2.dom.DomGlobal.window) Composite(org.jboss.hal.dmr.Composite) Dispatcher(org.jboss.hal.dmr.dispatch.Dispatcher) HEADERS(org.jboss.hal.dmr.ModelDescriptionConstants.HEADERS) NameTokens(org.jboss.hal.meta.token.NameTokens) MbuiPresenter(org.jboss.hal.core.mbui.MbuiPresenter) Resources(org.jboss.hal.resources.Resources) MbuiView(org.jboss.hal.core.mbui.MbuiView) EnableSSLPresenter(org.jboss.hal.client.shared.sslwizard.EnableSSLPresenter) READ_CHILDREN_NAMES_OPERATION(org.jboss.hal.dmr.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION) SERVER_SSL_CONTEXT(org.jboss.hal.dmr.ModelDescriptionConstants.SERVER_SSL_CONTEXT) START_MODE(org.jboss.hal.dmr.ModelDescriptionConstants.START_MODE) Host(org.jboss.hal.core.runtime.host.Host) Form(org.jboss.hal.ballroom.form.Form) ConstantHeadersPresenter(org.jboss.hal.client.runtime.managementinterface.ConstantHeadersPresenter) Task(org.jboss.hal.flow.Task) HTMLElement(elemental2.dom.HTMLElement) ResourceAddress(org.jboss.hal.dmr.ResourceAddress) Constants(org.jboss.hal.resources.Constants) Operation(org.jboss.hal.dmr.Operation) FlowContext(org.jboss.hal.flow.FlowContext) List(java.util.List) ArrayList(java.util.ArrayList) ModelNode(org.jboss.hal.dmr.ModelNode) SuccessfulOutcome(org.jboss.hal.core.SuccessfulOutcome) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem)

Example 4 with SwitchItem

use of org.jboss.hal.ballroom.form.SwitchItem in project console by hal.

the class ExactlyOneAlternativeValidation method validate.

@Override
public ValidationResult validate(final Form<T> form) {
    LabelBuilder labelBuilder = new LabelBuilder();
    Set<String> emptyItems = requiredAlternatives.stream().filter(name -> {
        FormItem formItem = form.getFormItem(name);
        boolean empty = formItem != null && formItem.isEmpty();
        // there is a special case for SwitchItem of Boolean type, the SwitchItem.isEmpty() tests if the value is
        // null, but for this validation case we must ensure the value is set to false to allow the validation
        // to work
        boolean switchItemFalse = false;
        if (formItem != null && formItem.getClass().equals(SwitchItem.class)) {
            Object value = formItem.getValue();
            switchItemFalse = value != null && !Boolean.parseBoolean(value.toString());
        }
        return empty || switchItemFalse;
    }).collect(toSet());
    if (requiredAlternatives.size() == emptyItems.size()) {
        // show an error on each related form item
        requiredAlternatives.forEach(alternative -> {
            FormItem<Object> formItem = form.getFormItem(alternative);
            if (formItem.isEmpty()) {
                formItem.showError(messages.exactlyOneAlternativeError(labelBuilder.enumeration(requiredAlternatives, constants.or())));
            }
        });
        // return overall result
        return ValidationResult.invalid(messages.exactlyOneAlternativesError(labelBuilder.enumeration(requiredAlternatives, constants.or())));
    } else {
        return ValidationResult.OK;
    }
}
Also used : ModelNode(org.jboss.hal.dmr.ModelNode) Iterables(com.google.common.collect.Iterables) SortedSet(java.util.SortedSet) Messages(org.jboss.hal.resources.Messages) Set(java.util.Set) TreeSet(java.util.TreeSet) FormValidation(org.jboss.hal.ballroom.form.FormValidation) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder) FormItem(org.jboss.hal.ballroom.form.FormItem) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem) Constants(org.jboss.hal.resources.Constants) ValidationResult(org.jboss.hal.ballroom.form.ValidationResult) Collectors.toSet(java.util.stream.Collectors.toSet) Form(org.jboss.hal.ballroom.form.Form) FormItem(org.jboss.hal.ballroom.form.FormItem) LabelBuilder(org.jboss.hal.ballroom.LabelBuilder)

Example 5 with SwitchItem

use of org.jboss.hal.ballroom.form.SwitchItem in project console by hal.

the class DefaultFormItemProvider method createFrom.

@Override
public FormItem<?> createFrom(Property property) {
    FormItem<?> formItem = null;
    String name = property.getName();
    String label = labelBuilder.label(property);
    ModelNode attributeDescription = property.getValue();
    // don't use 'required' here!
    boolean required = attributeDescription.hasDefined(NILLABLE) && !attributeDescription.get(NILLABLE).asBoolean();
    boolean expressionAllowed = attributeDescription.hasDefined(EXPRESSIONS_ALLOWED) && attributeDescription.get(EXPRESSIONS_ALLOWED).asBoolean();
    boolean readOnly = attributeDescription.hasDefined(ACCESS_TYPE) && (READ_ONLY.equals(attributeDescription.get(ACCESS_TYPE).asString()) || METRIC.equals(attributeDescription.get(ACCESS_TYPE).asString()));
    String unit = attributeDescription.hasDefined(UNIT) ? attributeDescription.get(UNIT).asString() : null;
    Deprecation deprecation = attributeDescription.hasDefined(DEPRECATED) ? new Deprecation(attributeDescription.get(DEPRECATED)) : null;
    if (attributeDescription.hasDefined(TYPE)) {
        ModelType type = attributeDescription.get(TYPE).asType();
        ModelType valueType = (attributeDescription.has(VALUE_TYPE) && attributeDescription.get(VALUE_TYPE).getType() != ModelType.OBJECT) ? ModelType.valueOf(attributeDescription.get(VALUE_TYPE).asString()) : null;
        switch(type) {
            case BOOLEAN:
                {
                    SwitchItem switchItem = new SwitchItem(name, label);
                    if (attributeDescription.hasDefined(DEFAULT)) {
                        switchItem.assignDefaultValue(attributeDescription.get(DEFAULT).asBoolean());
                    }
                    formItem = switchItem;
                    break;
                }
            case BIG_INTEGER:
            case INT:
            case LONG:
                {
                    long min, max;
                    if (type == ModelType.INT) {
                        min = attributeDescription.get(MIN).asLong(Integer.MIN_VALUE);
                        max = attributeDescription.get(MAX).asLong(Integer.MAX_VALUE);
                    } else {
                        min = attributeDescription.get(MIN).asLong(MIN_SAFE_LONG);
                        max = attributeDescription.get(MAX).asLong(MAX_SAFE_LONG);
                    }
                    NumberItem numberItem = new NumberItem(name, label, unit, min, max);
                    if (attributeDescription.hasDefined(DEFAULT)) {
                        long defaultValue = attributeDescription.get(DEFAULT).asLong();
                        numberItem.assignDefaultValue(defaultValue);
                    }
                    formItem = numberItem;
                    break;
                }
            case DOUBLE:
                {
                    long min = attributeDescription.get(MIN).asLong(MIN_SAFE_LONG);
                    long max = attributeDescription.get(MAX).asLong(MAX_SAFE_LONG);
                    NumberDoubleItem numberItem = new NumberDoubleItem(name, label, unit, min, max);
                    if (attributeDescription.hasDefined(DEFAULT)) {
                        double defaultValue = attributeDescription.get(DEFAULT).asDouble();
                        numberItem.assignDefaultValue(defaultValue);
                    }
                    formItem = numberItem;
                    break;
                }
            case LIST:
                {
                    if (valueType != null && ModelType.STRING == valueType) {
                        List<String> allowedValues = stringValues(attributeDescription, ALLOWED);
                        if (!allowedValues.isEmpty()) {
                            MultiSelectBoxItem multiSelectBoxItem = new MultiSelectBoxItem(name, label, allowedValues);
                            if (attributeDescription.hasDefined(DEFAULT)) {
                                List<String> defaultValues = stringValues(attributeDescription, DEFAULT);
                                if (!defaultValues.isEmpty()) {
                                    multiSelectBoxItem.assignDefaultValue(defaultValues);
                                }
                            }
                            formItem = multiSelectBoxItem;
                        } else {
                            ListItem listItem = new ListItem(name, label);
                            if (attributeDescription.hasDefined(DEFAULT)) {
                                List<String> defaultValues = stringValues(attributeDescription, DEFAULT);
                                if (!defaultValues.isEmpty()) {
                                    listItem.assignDefaultValue(defaultValues);
                                }
                            }
                            formItem = listItem;
                            checkCapabilityReference(attributeDescription, formItem);
                        }
                    } else if (isSimpleTuple(attributeDescription)) {
                        // process OBJECT type attribute if all of its subattributes are simple types
                        formItem = new TuplesListItem(name, label, metadata.forComplexAttribute(property.getName()));
                    } else {
                        logger.warn("Unsupported model type {} for attribute {} in metadata {}. Unable to create a form item. Attribute will be skipped.", type.name(), property.getName(), metadata.getTemplate());
                        break;
                    }
                    break;
                }
            case OBJECT:
                {
                    if (valueType != null && ModelType.STRING == valueType) {
                        PropertiesItem propertiesItem = new PropertiesItem(name, label);
                        List<Property> properties = ModelNodeHelper.getOrDefault(attributeDescription, DEFAULT, () -> attributeDescription.get(DEFAULT).asPropertyList(), emptyList());
                        if (!properties.isEmpty()) {
                            Map<String, String> defaultValues = new HashMap<>();
                            for (Property p : properties) {
                                defaultValues.put(p.getName(), p.getValue().asString());
                            }
                            propertiesItem.assignDefaultValue(defaultValues);
                        }
                        formItem = propertiesItem;
                    }
                    break;
                }
            case STRING:
                {
                    List<String> allowedValues = stringValues(attributeDescription, ALLOWED);
                    if (allowedValues.isEmpty()) {
                        FormItem<String> textBoxItem = new TextBoxItem(name, label, null);
                        boolean sensitive = failSafeGet(attributeDescription, ACCESS_CONSTRAINTS + "/" + SENSITIVE).isDefined();
                        if (PASSWORD.equals(name) || sensitive) {
                            textBoxItem.mask();
                        }
                        if (attributeDescription.hasDefined(DEFAULT)) {
                            textBoxItem.assignDefaultValue(attributeDescription.get(DEFAULT).asString());
                        }
                        formItem = textBoxItem;
                        checkCapabilityReference(attributeDescription, formItem);
                    } else {
                        SingleSelectBoxItem singleSelectBoxItem = new SingleSelectBoxItem(name, label, allowedValues, !required);
                        if (attributeDescription.hasDefined(DEFAULT)) {
                            singleSelectBoxItem.assignDefaultValue(attributeDescription.get(DEFAULT).asString());
                        }
                        formItem = singleSelectBoxItem;
                    }
                    break;
                }
            // unsupported types
            case BIG_DECIMAL:
            case BYTES:
            case EXPRESSION:
            case PROPERTY:
            case TYPE:
            case UNDEFINED:
                logger.warn("Unsupported model type {} for attribute {} in metadata {}. Unable to create a form item. Attribute will be skipped.", type.name(), property.getName(), metadata.getTemplate());
                break;
            default:
                break;
        }
        if (formItem != null) {
            formItem.setRequired(required);
            formItem.setDeprecated(deprecation);
            if (formItem.supportsExpressions()) {
                formItem.setExpressionAllowed(expressionAllowed);
                formItem.addResolveExpressionHandler(event -> {
                    // resend as application event
                    Core.INSTANCE.eventBus().fireEvent(event);
                });
            }
            if (readOnly) {
                formItem.setEnabled(false);
                // if the attribute is read-only and required, the form validation prevents to save the form
                // remove the required constraint to allow the save operation.
                formItem.setRequired(false);
            }
        }
    }
    return formItem;
}
Also used : TuplesListItem(org.jboss.hal.core.ui.TuplesListItem) SingleSelectBoxItem(org.jboss.hal.ballroom.form.SingleSelectBoxItem) FormItem(org.jboss.hal.ballroom.form.FormItem) NumberItem(org.jboss.hal.ballroom.form.NumberItem) MultiSelectBoxItem(org.jboss.hal.ballroom.form.MultiSelectBoxItem) PropertiesItem(org.jboss.hal.ballroom.form.PropertiesItem) TextBoxItem(org.jboss.hal.ballroom.form.TextBoxItem) Deprecation(org.jboss.hal.dmr.Deprecation) ModelType(org.jboss.hal.dmr.ModelType) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) NumberDoubleItem(org.jboss.hal.ballroom.form.NumberDoubleItem) ListItem(org.jboss.hal.ballroom.form.ListItem) TuplesListItem(org.jboss.hal.core.ui.TuplesListItem) ModelNode(org.jboss.hal.dmr.ModelNode) HashMap(java.util.HashMap) Map(java.util.Map) Property(org.jboss.hal.dmr.Property) SwitchItem(org.jboss.hal.ballroom.form.SwitchItem)

Aggregations

SwitchItem (org.jboss.hal.ballroom.form.SwitchItem)7 ModelNode (org.jboss.hal.dmr.ModelNode)7 Form (org.jboss.hal.ballroom.form.Form)6 List (java.util.List)5 ModelNodeForm (org.jboss.hal.core.mbui.form.ModelNodeForm)5 Metadata (org.jboss.hal.meta.Metadata)5 Ids (org.jboss.hal.resources.Ids)5 Resources (org.jboss.hal.resources.Resources)5 EventBus (com.google.web.bindery.event.shared.EventBus)4 HTMLElement (elemental2.dom.HTMLElement)4 ArrayList (java.util.ArrayList)4 Inject (javax.inject.Inject)4 Provider (javax.inject.Provider)4 LabelBuilder (org.jboss.hal.ballroom.LabelBuilder)4 DialogFactory (org.jboss.hal.ballroom.dialog.DialogFactory)4 Environment (org.jboss.hal.config.Environment)4 SuccessfulOutcome (org.jboss.hal.core.SuccessfulOutcome)4 Finder (org.jboss.hal.core.finder.Finder)4 Dispatcher (org.jboss.hal.dmr.dispatch.Dispatcher)4 Flow.series (org.jboss.hal.flow.Flow.series)4