se.hiq.oss.json.schema.JsonSchemaDiscoverer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of json-schema-discovery Show documentation
Show all versions of json-schema-discovery Show documentation
Auto-detected JSON schema classes and provide a repository for easy lookup
package se.hiq.oss.json.schema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import se.hiq.oss.json.schema.repo.JsonSchemaRepository;
import se.hiq.oss.json.schema.repo.JsonSchemaRepositoryFactory;
import se.hiq.oss.json.schema.repo.JsonSchemaRepositoryFactoryImpl;
public class JsonSchemaDiscoverer {
static final AnnotationTypeFilter ANNOTATION_TYPE_FILTER = new AnnotationTypeFilter(JsonSchema.class);
private ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
private JsonSchemaRepositoryFactory repositoryFactory;
public JsonSchemaDiscoverer(final ObjectMapper objectMapper) {
this.repositoryFactory = new JsonSchemaRepositoryFactoryImpl(objectMapper);
scanner.addIncludeFilter(ANNOTATION_TYPE_FILTER);
}
public JsonSchemaRepository discoverSchemas(String basePackage,
String... additionalBasePackage) {
JsonSchemaRepository repo = repositoryFactory.create();
List packageList = new ArrayList<>(Arrays.asList(additionalBasePackage));
packageList.add(basePackage);
Set> schemas = scanForSchemas(packageList);
schemas.stream()
.filter(c -> !c.equals(Object.class))
.forEach(schemaClass -> repo.registerSchemaFor(schemaClass));
return repo;
}
private Set> scanForSchemas(List packageList) {
return packageList.stream().map(packageName -> scanner.findCandidateComponents(packageName))
.flatMap(Set::stream)
.map(beanDefinition -> beanDefinition.getBeanClassName())
.map(className -> {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return Object.class;
}
})
.collect(Collectors.toSet());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy