io.swagger.converter.ModelConverterContextImpl Maven / Gradle / Ivy
The newest version!
package io.swagger.converter;
import io.swagger.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class ModelConverterContextImpl implements ModelConverterContext {
private static final Logger LOGGER = LoggerFactory.getLogger(ModelConverterContextImpl.class);
private final List converters;
private final Map modelByName;
private final HashMap modelByType;
private final Set processedTypes;
public ModelConverterContextImpl(List converters) {
this.converters = converters;
modelByName = new TreeMap();
modelByType = new HashMap();
processedTypes = new HashSet();
}
public ModelConverterContextImpl(ModelConverter converter) {
this(new ArrayList());
converters.add(converter);
}
public Iterator getConverters() {
return converters.iterator();
}
@Override
public void defineModel(String name, Schema model) {
defineModel(name, model, null, null);
}
@Override
public void defineModel(String name, Schema model, Type type, String prevName) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("defineModel %s %s", name, model));
}
modelByName.put(name, model);
if (StringUtils.isNotBlank(prevName) && !prevName.equals(name)) {
modelByName.remove(prevName);
}
if (type != null) {
modelByType.put(type, model);
}
}
public Map getDefinedModels() {
return Collections.unmodifiableMap(modelByName);
}
@Override
public Schema resolve(Type type) {
if (processedTypes.contains(type)) {
return modelByType.get(type);
} else {
processedTypes.add(type);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("resolve %s", type));
}
Iterator converters = this.getConverters();
Schema resolved = null;
if (converters.hasNext()) {
ModelConverter converter = converters.next();
LOGGER.debug("trying extension " + converter);
resolved = converter.resolve(type, this, converters);
}
if (resolved != null) {
modelByType.put(type, resolved);
Schema resolvedImpl = resolved;
if(resolvedImpl.getTitle() != null) {
modelByName.put(resolvedImpl.getTitle(), resolved);
}
}
return resolved;
}
@Override
public Schema resolve(Type type, Annotation[] annotations) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("resolveProperty %s", type));
}
Iterator converters = this.getConverters();
if (converters.hasNext()) {
ModelConverter converter = converters.next();
return converter.resolve(type, this, annotations, converters);
}
return null;
}
}