All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.devbench.uibuilder.components.multivalue.UIBuilderMultiValueBindingContext Maven / Gradle / Ivy

There is a newer version: 3.0.4
Show newest version
/*
 *
 * Copyright © 2018 Webvalto Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.devbench.uibuilder.components.multivalue;

import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
import io.devbench.uibuilder.api.utils.PropertyPath;
import io.devbench.uibuilder.core.utils.JsonSerializer;
import io.devbench.uibuilder.core.utils.reflection.ClassMetadata;
import io.devbench.uibuilder.core.utils.reflection.PropertyMetadata;
import io.devbench.uibuilder.data.common.datasource.BaseDataSourceBindingContext;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class UIBuilderMultiValueBindingContext extends BaseDataSourceBindingContext {

    @Getter
    private final String templateBeanName;
    private final List>> backendComponentValueSuppliers;
    private final List>> backendComponentValueConsumers;

    public UIBuilderMultiValueBindingContext(String templateBeanName) {
        this.templateBeanName = templateBeanName;
        this.backendComponentValueSuppliers = new ArrayList<>();
        this.backendComponentValueConsumers = new ArrayList<>();
    }

    private void setJsonValueByPath(PropertyPath propertyPath, JsonObject rootObject, JsonValue value) {
        if (propertyPath.isEmpty()) {
            throw new IllegalStateException("Property path cannot be empty");
        }

        if (propertyPath.isSingleLevel()) {
            rootObject.put(propertyPath.toString(), value);
        } else {
            JsonObject object = rootObject;
            for (int level = 0; level < propertyPath.levelSize() - 1; level++) {
                String levelName = propertyPath.level(level).toString();
                if (!object.hasKey(levelName)) {
                    object.put(levelName, Json.createObject());
                }
                object = object.getObject(levelName);
            }
            object.put(propertyPath.getLeaf().toString(), value);
        }
    }

    public  JsonObject createJsonItem(int index, T item) {
        return createJsonItem(index, item, null);
    }

    public  JsonObject createJsonItem(int index, T item, String valueItemPath) {
        JsonObject itemObject = Json.createObject();

        if (item != null && StringUtils.isNotBlank(valueItemPath)) {
            Optional jsonValue = JsonSerializer.tryToConvertToSimpleType(item);
            if (jsonValue.isPresent()) {
                setJsonValueByPath(new PropertyPath(templateBeanName + "." + valueItemPath), itemObject, jsonValue.get());
                return itemObject;
            }
        }

        ClassMetadata metadata = ClassMetadata.ofValue(item);
        getBindings()
            .stream()
            .map(PropertyPath::new)
            .filter(propertyPath -> propertyPath.levelSize() > 1)
            .filter(propertyPath -> propertyPath.getFirstLevel().contentEquals(templateBeanName))
            .forEach(propertyPath -> {
                Optional> foundBackendValueSupplier = findBackendValueSupplier(index, propertyPath.toString());

                Object propertyValue;

                if (foundBackendValueSupplier.isPresent()) {
                    findBackendValueInitializer(index, propertyPath.toString())
                        .ifPresent(consumer -> consumer.accept(item));
                    propertyValue = foundBackendValueSupplier.get().get();
                } else {
                    Optional> foundProperty = metadata.property(propertyPath.subPath(1).toString());
                    if (foundProperty.isPresent()) {
                        PropertyMetadata property = foundProperty.get();
                        propertyValue = property.getValue();
                    } else {
                        throw new IllegalStateException("Cannot find property \"" + propertyPath + "\" in bean");
                    }
                }

                JsonValue jsonValue = JsonSerializer.toJson(propertyValue);
                setJsonValueByPath(propertyPath, itemObject, jsonValue);
            });

        return itemObject;
    }

    private Optional> findBackendValueSupplier(int index, String propertyPath) {
        if (backendComponentValueSuppliers.size() > index) {
            Map> propertyPathValueSupplierMap = backendComponentValueSuppliers.get(index);
            if (propertyPathValueSupplierMap != null) {
                Supplier backendValueSupplier = propertyPathValueSupplierMap.get(propertyPath);
                return Optional.ofNullable(backendValueSupplier);
            }
        }
        return Optional.empty();
    }

    private  Optional> findBackendValueInitializer(int index, String propertyPath) {
        if (backendComponentValueConsumers.size() > index) {
            Map> propertyPathInitializerMap = backendComponentValueConsumers.get(index);
            if (propertyPathInitializerMap != null) {
                @SuppressWarnings("unchecked")
                Consumer backendValueInitializer = (Consumer) propertyPathInitializerMap.get(propertyPath);
                return Optional.ofNullable(backendValueInitializer);
            }
        }
        return Optional.empty();
    }

    private void ensureBackendComponentValueSuppliersAndConsumersSize(int size) {
        while (backendComponentValueSuppliers.size() < size) {
            backendComponentValueSuppliers.add(new HashMap<>());
            backendComponentValueConsumers.add(new HashMap<>());
        }
    }

    void registerBackendComponentValueSupplier(int index, String propertyPath, Supplier valueSupplier, Consumer valueInitializer) {
        ensureBackendComponentValueSuppliersAndConsumersSize(index + 1);
        Map> propertyPathSupplier = backendComponentValueSuppliers.get(index);
        Map> propertyPathConsumer = backendComponentValueConsumers.get(index);
        propertyPathSupplier.put(propertyPath, valueSupplier);
        propertyPathConsumer.put(propertyPath, valueInitializer);
    }

    void removeBackendComponentValueSuppliersAndConsumers(int index) {
        if (backendComponentValueSuppliers.size() > index) {
            backendComponentValueSuppliers.remove(index);
            backendComponentValueConsumers.remove(index);
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy