io.devbench.uibuilder.spring.page.BeanStore 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.server.VaadinSession;
import org.springframework.beans.factory.ObjectFactory;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
class BeanStore implements Serializable {
private final VaadinSession vaadinSession;
private final Map> destructionCallbacks;
private final Map beans;
BeanStore(VaadinSession vaadinSession) {
this.vaadinSession = vaadinSession;
this.beans = new ConcurrentHashMap<>();
this.destructionCallbacks = new HashMap<>();
}
public Object get(BEAN_ID beanId, ObjectFactory> objectFactory) {
return inLock(() -> {
beans.computeIfAbsent(beanId, id -> objectFactory.getObject());
return beans.get(beanId);
});
}
private T inLock(Supplier supplier) {
if (vaadinSession.hasLock()) {
return supplier.get();
} else {
try {
vaadinSession.lock();
return supplier.get();
} finally {
vaadinSession.unlock();
}
}
}
public void destroyBeans(Predicate predicate) {
inLock(() -> {
List toRemoveKeys = beans.keySet().stream().filter(predicate).collect(Collectors.toList());
toRemoveKeys.forEach(beanId -> {
destructionCallbacks.getOrDefault(beanId, Collections.emptyList()).forEach(Runnable::run);
destructionCallbacks.remove(beanId);
});
toRemoveKeys.forEach(beans::remove);
return null;
});
}
public void registerDestructionCallback(BEAN_ID beanIdForBean, Runnable callback) {
inLock(() -> {
destructionCallbacks.computeIfAbsent(beanIdForBean, id -> new ArrayList<>());
destructionCallbacks.get(beanIdForBean).add(callback);
return null;
});
}
}