io.ultreia.java4all.bean.JavaBeanDefinitionStore Maven / Gradle / Ivy
Show all versions of java-bean Show documentation
package io.ultreia.java4all.bean;
/*-
* #%L
* Java Beans extends by Ultreia.io
* %%
* Copyright (C) 2018 Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
/**
* Store of {@link JavaBeanDefinition}.
*
* Use method {@link #getDefinition(Class)}, or {@link #getDefinition(JavaBean)} to get the registered java bean
* definition (or null if none found).
*
* Created by tchemit on 07/01/2018.
*
* @author Tony Chemit - [email protected]
*/
public final class JavaBeanDefinitionStore {
private static Map DEFINITIONS;
private JavaBeanDefinitionStore() {
}
/**
* @param type type of java bean
* @return the optional java bean definition registered
*/
public static Optional getDefinition(Class type) {
return Optional.ofNullable(definitions().get(Objects.requireNonNull(type)));
}
/**
* @param javaBean java bean
* @return the optional java bean definition registered
*/
public static Optional getDefinition(JavaBean javaBean) {
return Optional.ofNullable(definitions().get(Objects.requireNonNull(javaBean).getClass()));
}
static Map definitions() {
return DEFINITIONS == null ? DEFINITIONS = loadDefinitions() : DEFINITIONS;
}
@SuppressWarnings("unchecked")
static J definition(Class javaBeanDefinitionType) {
return (J) definitions().values().stream().filter(d -> javaBeanDefinitionType.equals(d.getClass())).findFirst().orElseThrow(IllegalStateException::new);
}
private static synchronized Map loadDefinitions() {
Map result = new LinkedHashMap<>();
for (JavaBeanDefinition javaBeanDefinition : ServiceLoader.load(JavaBeanDefinition.class)) {
for (Class> o : javaBeanDefinition.types()) {
result.put(o, javaBeanDefinition);
}
}
return result;
}
}