json validation

This commit is contained in:
Michele Artini 2022-12-06 10:39:57 +01:00
parent a147c29c51
commit c68ae255a3
2 changed files with 3 additions and 33 deletions

View File

@ -1,7 +0,0 @@
package eu.dnetlib.is.util;
public @interface JsonResource {
String value();
}

View File

@ -16,10 +16,6 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;
@ -44,7 +40,7 @@ public class ResourceValidator {
if (rtype.getContentType().equals(MediaType.APPLICATION_XML_VALUE)) {
validateXml(type, content);
} else if (rtype.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
validateJSON(type, content);
validateJSON(content);
}
}
@ -76,32 +72,13 @@ public class ResourceValidator {
}
}
private void validateJSON(final String type, final String content) throws InformationServiceException {
final Class<?> clazz = getJsonClass(type);
if (clazz == null) {
log.warn("no registered Class for " + type);
}
private void validateJSON(final String content) throws InformationServiceException {
final ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(content, clazz);
mapper.readValue(content, Object.class);
} catch (final Exception e) {
throw new InformationServiceException(e.getMessage(), e);
}
}
private Class<?> getJsonClass(final String type) {
final ClassLoader classLoader = ResourceValidator.class.getClassLoader();
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.addIncludeFilter(new AnnotationTypeFilter(JsonResource.class));
provider.setResourceLoader(new PathMatchingResourcePatternResolver(classLoader));
for (final BeanDefinition bd : provider.findCandidateComponents("eu.dnetlib")) {
if (bd.getClass().getAnnotation(JsonResource.class).value().equals(type)) { return bd.getClass(); }
}
return null;
}
}