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

io.devbench.uibuilder.spring.page.BeanStoreWrapper Maven / Gradle / Ivy

/*
 *
 * 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.spring.page;

import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.DetachEvent;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.VaadinSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

class BeanStoreWrapper implements ComponentEventListener {

    private final VaadinSession vaadinSession;
    private final Map, BeanStore>> beanStores;

    BeanStoreWrapper(VaadinSession vaadinSession) {
        this.vaadinSession = vaadinSession;
        this.beanStores = new HashMap<>();
    }

     BeanStore getBeanStore(UI ui, Class clazz) {
        beanStores.computeIfAbsent(ui, this::createNewMapForUI);
        beanStores.get(ui).computeIfAbsent(clazz, aClass -> createNewBeanStoreForClazz());

        @SuppressWarnings("unchecked")
        BeanStore beanStore = (BeanStore) beanStores.get(ui).get(clazz);
        return beanStore;
    }

    private BeanStore createNewBeanStoreForClazz() {
        return new BeanStore(vaadinSession);
    }

    private Map, BeanStore> createNewMapForUI(UI ui) {
        ui.addDetachListener(this);
        return new HashMap<>();
    }

    @Override
    public void onComponentEvent(DetachEvent event) {
        Optional.ofNullable(beanStores.get(event.getUI()))
            .ifPresent(beanStoresForClasses -> {
                beanStoresForClasses.values().forEach(beanStore -> {
                    beanStore.destroyBeans(bean -> true);
                });
                beanStoresForClasses.clear();
            });
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy