proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/SubclassClassifier.java
|
SubclassClassifier
|
classify
|
class SubclassClassifier<T, C> implements Classifier<T, C> {
private ConcurrentMap<Class<? extends T>, C> classified;
private C defaultValue;
/**
* Create a {@link SubclassClassifier} with null default value.
*/
public SubclassClassifier() {
this(null);
}
/**
* Create a {@link SubclassClassifier} with supplied default value.
* @param defaultValue the default value
*/
public SubclassClassifier(C defaultValue) {
this(new HashMap<>(), defaultValue);
}
/**
* Create a {@link SubclassClassifier} with supplied default value.
* @param defaultValue the default value
* @param typeMap the map of types
*/
public SubclassClassifier(Map<Class<? extends T>, C> typeMap, C defaultValue) {
super();
this.classified = new ConcurrentHashMap<>(typeMap);
this.defaultValue = defaultValue;
}
/**
* Public setter for the default value for mapping keys that are not found in the map
* (or their subclasses). Defaults to false.
* @param defaultValue the default value to set
*/
public void setDefaultValue(C defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Set the classifications up as a map. The keys are types and these will be mapped
* along with all their subclasses to the corresponding value. The most specific types
* will match first.
* @param map a map from type to class
*/
public void setTypeMap(Map<Class<? extends T>, C> map) {
this.classified = new ConcurrentHashMap<>(map);
}
/**
* The key is the type and this will be mapped along with all subclasses to the
* corresponding value. The most specific types will match first.
* @param type the type of the input object
* @param target the target value for all such types
*/
public void add(Class<? extends T> type, C target) {
this.classified.put(type, target);
}
/**
* Return the value from the type map whose key is the class of the given Throwable,
* or its nearest ancestor if a subclass.
* @return C the classified value
* @param classifiable the classifiable thing
*/
@Override
public C classify(T classifiable) {<FILL_FUNCTION_BODY>}
/**
* Return the default value supplied in the constructor (default false).
* @return C the default value
*/
final public C getDefault() {
return this.defaultValue;
}
protected Map<Class<? extends T>, C> getClassified() {
return this.classified;
}
}
|
if (classifiable == null) {
return this.defaultValue;
}
@SuppressWarnings("unchecked")
Class<? extends T> exceptionClass = (Class<? extends T>) classifiable.getClass();
if (this.classified.containsKey(exceptionClass)) {
return this.classified.get(exceptionClass);
}
// check for subclasses
C value = null;
for (Class<?> cls = exceptionClass.getSuperclass(); !cls.equals(Object.class)
&& value == null; cls = cls.getSuperclass()) {
value = this.classified.get(cls);
}
// check for interfaces subclasses
if (value == null) {
for (Class<?> cls = exceptionClass; !cls.equals(Object.class) && value == null; cls = cls.getSuperclass()) {
for (Class<?> ifc : cls.getInterfaces()) {
value = this.classified.get(ifc);
if (value != null) {
break;
}
}
}
}
// ConcurrentHashMap doesn't allow nulls
if (value != null) {
this.classified.put(exceptionClass, value);
}
if (value == null) {
value = this.defaultValue;
}
return value;
| 692
| 361
| 1,053
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/util/AnnotationMethodResolver.java
|
AnnotationMethodResolver
|
findMethod
|
class AnnotationMethodResolver implements MethodResolver {
private final Class<? extends Annotation> annotationType;
/**
* Create a MethodResolver for the specified Method-level annotation type
* @param annotationType the type of the annotation
*/
public AnnotationMethodResolver(Class<? extends Annotation> annotationType) {
Assert.notNull(annotationType, "annotationType must not be null");
Assert.isTrue(
ObjectUtils.containsElement(annotationType.getAnnotation(Target.class).value(), ElementType.METHOD),
"Annotation [" + annotationType + "] is not a Method-level annotation.");
this.annotationType = annotationType;
}
/**
* Find a <em>single</em> Method on the Class of the given candidate object that
* contains the annotation type for which this resolver is searching.
* @param candidate the instance whose Class will be checked for the annotation
* @return a single matching Method instance or <code>null</code> if the candidate's
* Class contains no Methods with the specified annotation
* @throws IllegalArgumentException if more than one Method has the specified
* annotation
*/
public Method findMethod(Object candidate) {<FILL_FUNCTION_BODY>}
/**
* Find a <em>single</em> Method on the given Class that contains the annotation type
* for which this resolver is searching.
* @param clazz the Class instance to check for the annotation
* @return a single matching Method instance or <code>null</code> if the Class
* contains no Methods with the specified annotation
* @throws IllegalArgumentException if more than one Method has the specified
* annotation
*/
public Method findMethod(final Class<?> clazz) {
Assert.notNull(clazz, "class must not be null");
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(clazz, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class [" + clazz
+ "] with the annotation type [" + annotationType + "]");
annotatedMethod.set(method);
}
});
return annotatedMethod.get();
}
}
|
Assert.notNull(candidate, "candidate object must not be null");
Class<?> targetClass = AopUtils.getTargetClass(candidate);
if (targetClass == null) {
targetClass = candidate.getClass();
}
return this.findMethod(targetClass);
| 577
| 79
| 656
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/util/MethodInvokerUtils.java
|
MethodInvokerUtils
|
getMethodInvokerForSingleArgument
|
class MethodInvokerUtils {
/**
* Create a {@link MethodInvoker} using the provided method name to search.
* @param object to be invoked
* @param methodName of the method to be invoked
* @param paramsRequired boolean indicating whether the parameters are required, if
* false, a no args version of the method will be searched for.
* @param paramTypes - parameter types of the method to search for.
* @return MethodInvoker if the method is found, null if it is not.
*/
public static MethodInvoker getMethodInvokerByName(Object object, String methodName, boolean paramsRequired,
Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
if (method == null) {
String errorMsg = "no method found with name [" + methodName + "] on class ["
+ object.getClass().getSimpleName() + "] compatable with the signature ["
+ getParamTypesString(paramTypes) + "].";
Assert.isTrue(!paramsRequired, errorMsg);
// if no method was found for the given parameters, and the
// parameters aren't required, then try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, new Class[] {});
Assert.notNull(method, errorMsg);
}
return new SimpleMethodInvoker(object, method);
}
/**
* Create a String representation of the array of parameter types.
* @param paramTypes the types of parameters
* @return the paramTypes as String representation
*/
public static String getParamTypesString(Class<?>... paramTypes) {
StringBuilder paramTypesList = new StringBuilder("(");
for (int i = 0; i < paramTypes.length; i++) {
paramTypesList.append(paramTypes[i].getSimpleName());
if (i + 1 < paramTypes.length) {
paramTypesList.append(", ");
}
}
return paramTypesList.append(")").toString();
}
/**
* Create a {@link MethodInvoker} using the provided interface, and method name from
* that interface.
* @param cls the interface to search for the method named
* @param methodName of the method to be invoked
* @param object to be invoked
* @param paramTypes - parameter types of the method to search for.
* @return MethodInvoker if the method is found, null if it is not.
*/
public static MethodInvoker getMethodInvokerForInterface(Class<?> cls, String methodName, Object object,
Class<?>... paramTypes) {
if (cls.isAssignableFrom(object.getClass())) {
return MethodInvokerUtils.getMethodInvokerByName(object, methodName, true, paramTypes);
}
else {
return null;
}
}
/**
* Create a MethodInvoker from the delegate based on the annotationType. Ensure that
* the annotated method has a valid set of parameters.
* @param annotationType the annotation to scan for
* @param target the target object
* @param expectedParamTypes the expected parameter types for the method
* @return a MethodInvoker
*/
public static MethodInvoker getMethodInvokerByAnnotation(final Class<? extends Annotation> annotationType,
final Object target, final Class<?>... expectedParamTypes) {
MethodInvoker mi = MethodInvokerUtils.getMethodInvokerByAnnotation(annotationType, target);
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass()
: target.getClass();
if (mi != null) {
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatable with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
}
}
});
}
return mi;
}
/**
* Create {@link MethodInvoker} for the method with the provided annotation on the
* provided object. Annotations that cannot be applied to methods (i.e. that aren't
* annotated with an element type of METHOD) will cause an exception to be thrown.
* @param annotationType to be searched for
* @param target to be invoked
* @return MethodInvoker for the provided annotation, null if none is found.
*/
public static MethodInvoker getMethodInvokerByAnnotation(final Class<? extends Annotation> annotationType,
final Object target) {
Assert.notNull(target, "Target must not be null");
Assert.notNull(annotationType, "AnnotationType must not be null");
Assert.isTrue(
ObjectUtils.containsElement(annotationType.getAnnotation(Target.class).value(), ElementType.METHOD),
"Annotation [" + annotationType + "] is not a Method-level annotation.");
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass()
: target.getClass();
if (targetClass == null) {
// Proxy with no target cannot have annotations
return null;
}
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(),
"found more than one method on target class [" + targetClass.getSimpleName()
+ "] with the annotation type [" + annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
});
Method method = annotatedMethod.get();
if (method == null) {
return null;
}
else {
return new SimpleMethodInvoker(target, annotatedMethod.get());
}
}
/**
* Create a {@link MethodInvoker} for the delegate from a single public method.
* @param target an object to search for an appropriate method
* @return a MethodInvoker that calls a method on the delegate
* @param <T> the t
* @param <C> the C
*/
public static <C, T> MethodInvoker getMethodInvokerForSingleArgument(Object target) {<FILL_FUNCTION_BODY>}
}
|
final AtomicReference<Method> methodHolder = new AtomicReference<>();
ReflectionUtils.doWithMethods(target.getClass(), method -> {
if ((method.getModifiers() & Modifier.PUBLIC) == 0 || method.isBridge()) {
return;
}
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);
| 1,801
| 213
| 2,014
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/classify/util/SimpleMethodInvoker.java
|
SimpleMethodInvoker
|
invokeMethod
|
class SimpleMethodInvoker implements MethodInvoker {
private final Object object;
private final Method method;
private final Class<?>[] parameterTypes;
private volatile Object target;
public SimpleMethodInvoker(Object object, Method method) {
Assert.notNull(object, "Object to invoke must not be null");
Assert.notNull(method, "Method to invoke must not be null");
this.method = method;
method.setAccessible(true);
this.object = object;
this.parameterTypes = method.getParameterTypes();
}
public SimpleMethodInvoker(Object object, String methodName, Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
if (method == null) {
// try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, new Class[] {});
}
Assert.notNull(method, "No methods found for name: [" + methodName + "] in class: [" + object.getClass()
+ "] with arguments of type: [" + Arrays.toString(paramTypes) + "]");
this.object = object;
this.method = method;
method.setAccessible(true);
this.parameterTypes = method.getParameterTypes();
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.core.configuration.util.MethodInvoker#invokeMethod
* (java.lang.Object[])
*/
@Override
public Object invokeMethod(Object... args) {<FILL_FUNCTION_BODY>}
private Object extractTarget(Object target, Method method) {
if (this.target == null) {
if (target instanceof Advised) {
Object source;
try {
source = ((Advised) target).getTargetSource().getTarget();
}
catch (Exception e) {
throw new IllegalStateException("Could not extract target from proxy", e);
}
if (source instanceof Advised) {
source = extractTarget(source, method);
}
if (method.getDeclaringClass().isAssignableFrom(source.getClass())) {
target = source;
}
}
this.target = target;
}
return this.target;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SimpleMethodInvoker)) {
return false;
}
if (obj == this) {
return true;
}
SimpleMethodInvoker rhs = (SimpleMethodInvoker) obj;
return (rhs.method.equals(this.method)) && (rhs.object.equals(this.object));
}
@Override
public int hashCode() {
int result = 25;
result = 31 * result + this.object.hashCode();
result = 31 * result + this.method.hashCode();
return result;
}
}
|
Assert.state(this.parameterTypes.length == args.length,
"Wrong number of arguments, expected no more than: [" + this.parameterTypes.length + "]");
try {
// Extract the target from an Advised as late as possible
// in case it contains a lazy initialization
Object target = extractTarget(this.object, this.method);
return method.invoke(target, args);
}
catch (Exception e) {
throw new IllegalArgumentException("Unable to invoke method: [" + this.method + "] on object: ["
+ this.object + "] with arguments: [" + Arrays.toString(args) + "]", e);
}
| 775
| 174
| 949
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/annotation/RetryConfiguration.java
|
RetryConfiguration
|
afterPropertiesSet
|
class RetryConfiguration extends AbstractPointcutAdvisor
implements IntroductionAdvisor, BeanFactoryAware, InitializingBean, SmartInitializingSingleton, ImportAware {
@Nullable
protected AnnotationAttributes enableRetry;
private AnnotationAwareRetryOperationsInterceptor advice;
private Pointcut pointcut;
private RetryContextCache retryContextCache;
private List<RetryListener> retryListeners;
private MethodArgumentsKeyGenerator methodArgumentsKeyGenerator;
private NewMethodArgumentsIdentifier newMethodArgumentsIdentifier;
private Sleeper sleeper;
private BeanFactory beanFactory;
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
this.enableRetry = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableRetry.class.getName()));
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void afterSingletonsInstantiated() {
this.retryListeners = findBeans(RetryListener.class);
if (this.retryListeners != null) {
this.advice.setListeners(this.retryListeners);
}
}
private <T> List<T> findBeans(Class<? extends T> type) {
if (this.beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listable = (ListableBeanFactory) this.beanFactory;
if (listable.getBeanNamesForType(type).length > 0) {
ArrayList<T> list = new ArrayList<>(listable.getBeansOfType(type, false, false).values());
OrderComparator.sort(list);
return list;
}
}
return null;
}
private <T> T findBean(Class<? extends T> type) {
if (this.beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listable = (ListableBeanFactory) this.beanFactory;
if (listable.getBeanNamesForType(type, false, false).length == 1) {
return listable.getBean(type);
}
}
return null;
}
/**
* Set the {@code BeanFactory} to be used when looking up executors by qualifier.
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public ClassFilter getClassFilter() {
return this.pointcut.getClassFilter();
}
@Override
public Class<?>[] getInterfaces() {
return new Class[] { org.springframework.retry.interceptor.Retryable.class };
}
@Override
public void validateInterfaces() throws IllegalArgumentException {
}
@Override
public Advice getAdvice() {
return this.advice;
}
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
protected AnnotationAwareRetryOperationsInterceptor buildAdvice() {
AnnotationAwareRetryOperationsInterceptor interceptor = new AnnotationAwareRetryOperationsInterceptor();
if (this.retryContextCache != null) {
interceptor.setRetryContextCache(this.retryContextCache);
}
if (this.methodArgumentsKeyGenerator != null) {
interceptor.setKeyGenerator(this.methodArgumentsKeyGenerator);
}
if (this.newMethodArgumentsIdentifier != null) {
interceptor.setNewItemIdentifier(this.newMethodArgumentsIdentifier);
}
if (this.sleeper != null) {
interceptor.setSleeper(this.sleeper);
}
return interceptor;
}
/**
* Calculate a pointcut for the given retry annotation types, if any.
* @param retryAnnotationTypes the retry annotation types to introspect
* @return the applicable Pointcut object, or {@code null} if none
*/
protected Pointcut buildPointcut(Set<Class<? extends Annotation>> retryAnnotationTypes) {
ComposablePointcut result = null;
for (Class<? extends Annotation> retryAnnotationType : retryAnnotationTypes) {
Pointcut filter = new AnnotationClassOrMethodPointcut(retryAnnotationType);
if (result == null) {
result = new ComposablePointcut(filter);
}
else {
result.union(filter);
}
}
return result;
}
private final class AnnotationClassOrMethodPointcut extends StaticMethodMatcherPointcut {
private final MethodMatcher methodResolver;
AnnotationClassOrMethodPointcut(Class<? extends Annotation> annotationType) {
this.methodResolver = new AnnotationMethodMatcher(annotationType);
setClassFilter(new AnnotationClassOrMethodFilter(annotationType));
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return getClassFilter().matches(targetClass) || this.methodResolver.matches(method, targetClass);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof AnnotationClassOrMethodPointcut)) {
return false;
}
AnnotationClassOrMethodPointcut otherAdvisor = (AnnotationClassOrMethodPointcut) other;
return ObjectUtils.nullSafeEquals(this.methodResolver, otherAdvisor.methodResolver);
}
}
private final class AnnotationClassOrMethodFilter extends AnnotationClassFilter {
private final AnnotationMethodsResolver methodResolver;
AnnotationClassOrMethodFilter(Class<? extends Annotation> annotationType) {
super(annotationType, true);
this.methodResolver = new AnnotationMethodsResolver(annotationType);
}
@Override
public boolean matches(Class<?> clazz) {
return super.matches(clazz) || this.methodResolver.hasAnnotatedMethods(clazz);
}
}
private static class AnnotationMethodsResolver {
private final Class<? extends Annotation> annotationType;
public AnnotationMethodsResolver(Class<? extends Annotation> annotationType) {
this.annotationType = annotationType;
}
public boolean hasAnnotatedMethods(Class<?> clazz) {
final AtomicBoolean found = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(clazz, method -> {
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
AnnotationMethodsResolver.this.annotationType);
if (annotation != null) {
found.set(true);
}
});
return found.get();
}
}
}
|
this.retryContextCache = findBean(RetryContextCache.class);
this.methodArgumentsKeyGenerator = findBean(MethodArgumentsKeyGenerator.class);
this.newMethodArgumentsIdentifier = findBean(NewMethodArgumentsIdentifier.class);
this.sleeper = findBean(Sleeper.class);
Set<Class<? extends Annotation>> retryableAnnotationTypes = new LinkedHashSet<>(1);
retryableAnnotationTypes.add(Retryable.class);
this.pointcut = buildPointcut(retryableAnnotationTypes);
this.advice = buildAdvice();
this.advice.setBeanFactory(this.beanFactory);
if (this.enableRetry != null) {
setOrder(enableRetry.getNumber("order"));
}
| 1,703
| 196
| 1,899
|
<methods>public void <init>() ,public boolean equals(java.lang.Object) ,public int getOrder() ,public int hashCode() ,public void setOrder(int) <variables>private java.lang.Integer order
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/backoff/BackOffPolicyBuilder.java
|
BackOffPolicyBuilder
|
build
|
class BackOffPolicyBuilder {
private static final long DEFAULT_INITIAL_DELAY = 1000L;
private Long delay = DEFAULT_INITIAL_DELAY;
private Long maxDelay;
private Double multiplier;
private Boolean random;
private Sleeper sleeper;
private Supplier<Long> delaySupplier;
private Supplier<Long> maxDelaySupplier;
private Supplier<Double> multiplierSupplier;
private Supplier<Boolean> randomSupplier;
private BackOffPolicyBuilder() {
}
/**
* Creates a new {@link BackOffPolicyBuilder} instance.
* @return the builder instance
*/
public static BackOffPolicyBuilder newBuilder() {
return new BackOffPolicyBuilder();
}
/**
* Creates a new {@link FixedBackOffPolicy} instance with a delay of 1000ms.
* @return the back off policy instance
*/
public static BackOffPolicy newDefaultPolicy() {
return new BackOffPolicyBuilder().build();
}
/**
* A canonical backoff period. Used as an initial value in the exponential case, and
* as a minimum value in the uniform case.
* @param delay the initial or canonical backoff period in milliseconds
* @return this
*/
public BackOffPolicyBuilder delay(long delay) {
this.delay = delay;
return this;
}
/**
* The maximum wait in milliseconds between retries. If less than {@link #delay(long)}
* then a default value is applied depending on the resulting policy.
* @param maxDelay the maximum wait between retries in milliseconds
* @return this
*/
public BackOffPolicyBuilder maxDelay(long maxDelay) {
this.maxDelay = maxDelay;
return this;
}
/**
* If positive, then used as a multiplier for generating the next delay for backoff.
* @param multiplier a multiplier to use to calculate the next backoff delay
* @return this
*/
public BackOffPolicyBuilder multiplier(double multiplier) {
this.multiplier = multiplier;
return this;
}
/**
* In the exponential case ({@link #multiplier} > 0) set this to true to have the
* backoff delays randomized, so that the maximum delay is multiplier times the
* previous delay and the distribution is uniform between the two values.
* @param random the flag to signal randomization is required
* @return this
*/
public BackOffPolicyBuilder random(boolean random) {
this.random = random;
return this;
}
/**
* The {@link Sleeper} instance to be used to back off. Policies default to
* {@link ThreadWaitSleeper}.
* @param sleeper the {@link Sleeper} instance
* @return this
*/
public BackOffPolicyBuilder sleeper(Sleeper sleeper) {
this.sleeper = sleeper;
return this;
}
/**
* Set a supplier for the delay.
* @param delaySupplier the supplier.
* @return this
* @since 2.0
*/
public BackOffPolicyBuilder delaySupplier(Supplier<Long> delaySupplier) {
this.delaySupplier = delaySupplier;
return this;
}
/**
* Set a supplier for the max delay.
* @param maxDelaySupplier the supplier.
* @return this
* @since 2.0
*/
public BackOffPolicyBuilder maxDelaySupplier(Supplier<Long> maxDelaySupplier) {
this.maxDelaySupplier = maxDelaySupplier;
return this;
}
/**
* Set a supplier for the multiplier.
* @param multiplierSupplier the supplier.
* @return this
* @since 2.0
*/
public BackOffPolicyBuilder multiplierSupplier(Supplier<Double> multiplierSupplier) {
this.multiplierSupplier = multiplierSupplier;
return this;
}
/**
* Set a supplier for the random.
* @param randomSupplier the supplier.
* @return this
* @since 2.0
*/
public BackOffPolicyBuilder randomSupplier(Supplier<Boolean> randomSupplier) {
this.randomSupplier = randomSupplier;
return this;
}
/**
* Builds the {@link BackOffPolicy} with the given parameters.
* @return the {@link BackOffPolicy} instance
*/
public BackOffPolicy build() {<FILL_FUNCTION_BODY>}
}
|
if (this.multiplier != null && this.multiplier > 0 || this.multiplierSupplier != null) {
ExponentialBackOffPolicy policy;
if (Boolean.TRUE.equals(this.random)) {
policy = new ExponentialRandomBackOffPolicy();
}
else {
policy = new ExponentialBackOffPolicy();
}
if (this.delay != null) {
policy.setInitialInterval(this.delay);
}
if (this.delaySupplier != null) {
policy.initialIntervalSupplier(this.delaySupplier);
}
if (this.multiplier != null) {
policy.setMultiplier(this.multiplier);
}
if (this.multiplierSupplier != null) {
policy.multiplierSupplier(this.multiplierSupplier);
}
if (this.maxDelay != null && this.delay != null) {
policy.setMaxInterval(
this.maxDelay > this.delay ? this.maxDelay : ExponentialBackOffPolicy.DEFAULT_MAX_INTERVAL);
}
if (this.maxDelaySupplier != null) {
policy.maxIntervalSupplier(this.maxDelaySupplier);
}
if (this.sleeper != null) {
policy.setSleeper(this.sleeper);
}
return policy;
}
if (this.maxDelay != null && this.delay != null && this.maxDelay > this.delay) {
UniformRandomBackOffPolicy policy = new UniformRandomBackOffPolicy();
if (this.delay != null) {
policy.setMinBackOffPeriod(this.delay);
}
if (this.delaySupplier != null) {
policy.minBackOffPeriodSupplier(this.delaySupplier);
}
if (this.maxDelay != null) {
policy.setMaxBackOffPeriod(this.maxDelay);
}
if (this.maxDelaySupplier != null) {
policy.maxBackOffPeriodSupplier(this.maxDelaySupplier);
}
if (this.sleeper != null) {
policy.setSleeper(this.sleeper);
}
return policy;
}
FixedBackOffPolicy policy = new FixedBackOffPolicy();
if (this.delaySupplier != null) {
policy.backOffPeriodSupplier(this.delaySupplier);
}
else if (this.delay != null) {
policy.setBackOffPeriod(this.delay);
}
if (this.sleeper != null) {
policy.setSleeper(this.sleeper);
}
return policy;
| 1,129
| 705
| 1,834
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/backoff/ExponentialBackOffPolicy.java
|
ExponentialBackOffContext
|
getInterval
|
class ExponentialBackOffContext implements BackOffContext {
private final double multiplier;
private long interval;
private final long maxInterval;
private Supplier<Long> initialIntervalSupplier;
private Supplier<Double> multiplierSupplier;
private Supplier<Long> maxIntervalSupplier;
public ExponentialBackOffContext(long interval, double multiplier, long maxInterval,
Supplier<Long> intervalSupplier, Supplier<Double> multiplierSupplier,
Supplier<Long> maxIntervalSupplier) {
this.interval = interval;
this.multiplier = multiplier;
this.maxInterval = maxInterval;
this.initialIntervalSupplier = intervalSupplier;
this.multiplierSupplier = multiplierSupplier;
this.maxIntervalSupplier = maxIntervalSupplier;
}
public synchronized long getSleepAndIncrement() {
long sleep = getInterval();
long max = getMaxInterval();
if (sleep > max) {
sleep = max;
}
else {
this.interval = getNextInterval();
}
return sleep;
}
protected long getNextInterval() {
return (long) (this.interval * getMultiplier());
}
public double getMultiplier() {
return this.multiplierSupplier != null ? this.multiplierSupplier.get() : this.multiplier;
}
public long getInterval() {<FILL_FUNCTION_BODY>}
public long getMaxInterval() {
return this.maxIntervalSupplier != null ? this.maxIntervalSupplier.get() : this.maxInterval;
}
}
|
if (this.initialIntervalSupplier != null) {
this.interval = this.initialIntervalSupplier.get();
this.initialIntervalSupplier = null;
}
return this.interval;
| 429
| 54
| 483
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/backoff/ExponentialRandomBackOffPolicy.java
|
ExponentialRandomBackOffContext
|
getSleepAndIncrement
|
class ExponentialRandomBackOffContext extends ExponentialBackOffPolicy.ExponentialBackOffContext {
private final Random r = new Random();
public ExponentialRandomBackOffContext(long expSeed, double multiplier, long maxInterval,
Supplier<Long> expSeedSupplier, Supplier<Double> multiplierSupplier,
Supplier<Long> maxIntervalSupplier) {
super(expSeed, multiplier, maxInterval, expSeedSupplier, multiplierSupplier, maxIntervalSupplier);
}
@Override
public synchronized long getSleepAndIncrement() {<FILL_FUNCTION_BODY>}
}
|
long next = super.getSleepAndIncrement();
next = (long) (next * (1 + r.nextFloat() * (getMultiplier() - 1)));
if (next > super.getMaxInterval()) {
next = super.getMaxInterval();
}
return next;
| 164
| 81
| 245
|
<methods>public non-sealed void <init>() ,public void backOff(org.springframework.retry.backoff.BackOffContext) throws org.springframework.retry.backoff.BackOffInterruptedException,public long getInitialInterval() ,public long getMaxInterval() ,public double getMultiplier() ,public void initialIntervalSupplier(Supplier<java.lang.Long>) ,public void maxIntervalSupplier(Supplier<java.lang.Long>) ,public void multiplierSupplier(Supplier<java.lang.Double>) ,public void setInitialInterval(long) ,public void setMaxInterval(long) ,public void setMultiplier(double) ,public void setSleeper(org.springframework.retry.backoff.Sleeper) ,public org.springframework.retry.backoff.BackOffContext start(org.springframework.retry.RetryContext) ,public java.lang.String toString() ,public org.springframework.retry.backoff.ExponentialBackOffPolicy withSleeper(org.springframework.retry.backoff.Sleeper) <variables>public static final long DEFAULT_INITIAL_INTERVAL,public static final long DEFAULT_MAX_INTERVAL,public static final double DEFAULT_MULTIPLIER,private long initialInterval,private Supplier<java.lang.Long> initialIntervalSupplier,protected final org.apache.commons.logging.Log logger,private long maxInterval,private Supplier<java.lang.Long> maxIntervalSupplier,private double multiplier,private Supplier<java.lang.Double> multiplierSupplier,private org.springframework.retry.backoff.Sleeper sleeper
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/backoff/FixedBackOffPolicy.java
|
FixedBackOffPolicy
|
doBackOff
|
class FixedBackOffPolicy extends StatelessBackOffPolicy implements SleepingBackOffPolicy<FixedBackOffPolicy> {
/**
* Default back off period - 1000ms.
*/
private static final long DEFAULT_BACK_OFF_PERIOD = 1000L;
/**
* The back off period in milliseconds. Defaults to 1000ms.
*/
private Supplier<Long> backOffPeriod = () -> DEFAULT_BACK_OFF_PERIOD;
private Sleeper sleeper = new ThreadWaitSleeper();
public FixedBackOffPolicy withSleeper(Sleeper sleeper) {
FixedBackOffPolicy res = new FixedBackOffPolicy();
res.backOffPeriodSupplier(backOffPeriod);
res.setSleeper(sleeper);
return res;
}
/**
* Public setter for the {@link Sleeper} strategy.
* @param sleeper the sleeper to set defaults to {@link ThreadWaitSleeper}.
*/
public void setSleeper(Sleeper sleeper) {
this.sleeper = sleeper;
}
/**
* Set the back off period in milliseconds. Cannot be < 1. Default value is 1000ms.
* @param backOffPeriod the back off period
*/
public void setBackOffPeriod(long backOffPeriod) {
this.backOffPeriod = () -> (backOffPeriod > 0 ? backOffPeriod : 1);
}
/**
* Set a supplier for the back off period in milliseconds. Cannot be < 1. Default
* supplier supplies 1000ms.
* @param backOffPeriodSupplier the back off period
* @since 2.0
*/
public void backOffPeriodSupplier(Supplier<Long> backOffPeriodSupplier) {
Assert.notNull(backOffPeriodSupplier, "'backOffPeriodSupplier' cannot be null");
this.backOffPeriod = backOffPeriodSupplier;
}
/**
* The backoff period in milliseconds.
* @return the backoff period
*/
public long getBackOffPeriod() {
return this.backOffPeriod.get();
}
/**
* Pause for the {@link #setBackOffPeriod(long)}.
* @throws BackOffInterruptedException if interrupted during sleep.
*/
protected void doBackOff() throws BackOffInterruptedException {<FILL_FUNCTION_BODY>}
public String toString() {
return "FixedBackOffPolicy[backOffPeriod=" + this.backOffPeriod.get() + "]";
}
}
|
try {
sleeper.sleep(this.backOffPeriod.get());
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new BackOffInterruptedException("Thread interrupted while sleeping", e);
}
| 649
| 70
| 719
|
<methods>public non-sealed void <init>() ,public final void backOff(org.springframework.retry.backoff.BackOffContext) throws org.springframework.retry.backoff.BackOffInterruptedException,public org.springframework.retry.backoff.BackOffContext start(org.springframework.retry.RetryContext) <variables>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/backoff/ObjectWaitSleeper.java
|
ObjectWaitSleeper
|
sleep
|
class ObjectWaitSleeper implements Sleeper {
/*
* (non-Javadoc)
*
* @see org.springframework.batch.retry.backoff.Sleeper#sleep(long)
*/
public void sleep(long backOffPeriod) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
Object mutex = new Object();
synchronized (mutex) {
mutex.wait(backOffPeriod);
}
| 86
| 38
| 124
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/interceptor/RetryInterceptorBuilder.java
|
CircuitBreakerInterceptorBuilder
|
build
|
class CircuitBreakerInterceptorBuilder
extends RetryInterceptorBuilder<StatefulRetryOperationsInterceptor> {
private final StatefulRetryOperationsInterceptor interceptor = new StatefulRetryOperationsInterceptor();
private MethodArgumentsKeyGenerator keyGenerator;
@Override
public CircuitBreakerInterceptorBuilder retryOperations(RetryOperations retryOperations) {
super.retryOperations(retryOperations);
return this;
}
@Override
public CircuitBreakerInterceptorBuilder maxAttempts(int maxAttempts) {
super.maxAttempts(maxAttempts);
return this;
}
@Override
public CircuitBreakerInterceptorBuilder retryPolicy(RetryPolicy policy) {
super.retryPolicy(policy);
return this;
}
public CircuitBreakerInterceptorBuilder keyGenerator(MethodArgumentsKeyGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
return this;
}
@Override
public CircuitBreakerInterceptorBuilder recoverer(MethodInvocationRecoverer<?> recoverer) {
super.recoverer(recoverer);
return this;
}
@Override
public StatefulRetryOperationsInterceptor build() {<FILL_FUNCTION_BODY>}
private CircuitBreakerInterceptorBuilder() {
}
}
|
if (this.recoverer != null) {
this.interceptor.setRecoverer(this.recoverer);
}
if (this.retryOperations != null) {
this.interceptor.setRetryOperations(this.retryOperations);
}
else {
this.interceptor.setRetryOperations(this.retryTemplate);
}
if (this.keyGenerator != null) {
this.interceptor.setKeyGenerator(this.keyGenerator);
}
if (this.label != null) {
this.interceptor.setLabel(this.label);
}
this.interceptor.setRollbackClassifier(new BinaryExceptionClassifier(false));
return this.interceptor;
| 364
| 201
| 565
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/interceptor/RetryOperationsInterceptor.java
|
RetryOperationsInterceptor
|
doWithRetry
|
class RetryOperationsInterceptor implements MethodInterceptor {
private RetryOperations retryOperations = new RetryTemplate();
@Nullable
private MethodInvocationRecoverer<?> recoverer;
private String label;
public void setLabel(String label) {
this.label = label;
}
public void setRetryOperations(RetryOperations retryTemplate) {
Assert.notNull(retryTemplate, "'retryOperations' cannot be null.");
this.retryOperations = retryTemplate;
}
public void setRecoverer(MethodInvocationRecoverer<?> recoverer) {
this.recoverer = recoverer;
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
RetryCallback<Object, Throwable> retryCallback = new MethodInvocationRetryCallback<>(invocation, this.label) {
@Override
public Object doWithRetry(RetryContext context) throws Exception {<FILL_FUNCTION_BODY>}
};
RecoveryCallback<Object> recoveryCallback = (this.recoverer != null)
? new ItemRecovererCallback(invocation.getArguments(), this.recoverer) : null;
try {
return this.retryOperations.execute(retryCallback, recoveryCallback);
}
finally {
RetryContext context = RetrySynchronizationManager.getContext();
if (context != null) {
context.removeAttribute("__proxy__");
}
}
}
private record ItemRecovererCallback(Object[] args,
MethodInvocationRecoverer<?> recoverer) implements RecoveryCallback<Object> {
@Override
public Object recover(RetryContext context) {
return this.recoverer.recover(this.args, context.getLastThrowable());
}
}
}
|
context.setAttribute(RetryContext.NAME, this.label);
context.setAttribute("ARGS", new Args(invocation.getArguments()));
/*
* If we don't copy the invocation carefully it won't keep a reference to
* the other interceptors in the chain. We don't have a choice here but to
* specialise to ReflectiveMethodInvocation (but how often would another
* implementation come along?).
*/
if (this.invocation instanceof ProxyMethodInvocation) {
context.setAttribute("___proxy___", ((ProxyMethodInvocation) this.invocation).getProxy());
try {
return ((ProxyMethodInvocation) this.invocation).invocableClone().proceed();
}
catch (Exception | Error e) {
throw e;
}
catch (Throwable e) {
throw new IllegalStateException(e);
}
}
else {
throw new IllegalStateException(
"MethodInvocation of the wrong type detected - this should not happen with Spring AOP, "
+ "so please raise an issue if you see this exception");
}
| 480
| 293
| 773
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/interceptor/StatefulRetryOperationsInterceptor.java
|
StatefulRetryOperationsInterceptor
|
createKey
|
class StatefulRetryOperationsInterceptor implements MethodInterceptor {
private transient final Log logger = LogFactory.getLog(getClass());
private MethodArgumentsKeyGenerator keyGenerator;
private MethodInvocationRecoverer<?> recoverer;
private NewMethodArgumentsIdentifier newMethodArgumentsIdentifier;
private RetryOperations retryOperations;
private String label;
private Classifier<? super Throwable, Boolean> rollbackClassifier;
private boolean useRawKey;
public StatefulRetryOperationsInterceptor() {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new NeverRetryPolicy());
this.retryOperations = retryTemplate;
}
public void setRetryOperations(RetryOperations retryTemplate) {
Assert.notNull(retryTemplate, "'retryOperations' cannot be null.");
this.retryOperations = retryTemplate;
}
/**
* Public setter for the {@link MethodInvocationRecoverer} to use if the retry is
* exhausted. The recoverer should be able to return an object of the same type as the
* target object because its return value will be used to return to the caller in the
* case of a recovery.
* @param recoverer the {@link MethodInvocationRecoverer} to set
*/
public void setRecoverer(MethodInvocationRecoverer<?> recoverer) {
this.recoverer = recoverer;
}
/**
* Rollback classifier for the retry state. Default to null (meaning rollback for
* all).
* @param rollbackClassifier the rollbackClassifier to set
*/
public void setRollbackClassifier(Classifier<? super Throwable, Boolean> rollbackClassifier) {
this.rollbackClassifier = rollbackClassifier;
}
public void setKeyGenerator(MethodArgumentsKeyGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
}
public void setLabel(String label) {
this.label = label;
}
/**
* Public setter for the {@link NewMethodArgumentsIdentifier}. Only set this if the
* arguments to the intercepted method can be inspected to find out if they have never
* been processed before.
* @param newMethodArgumentsIdentifier the {@link NewMethodArgumentsIdentifier} to set
*/
public void setNewItemIdentifier(NewMethodArgumentsIdentifier newMethodArgumentsIdentifier) {
this.newMethodArgumentsIdentifier = newMethodArgumentsIdentifier;
}
/**
* Set to true to use the raw key generated by the key generator. Should only be set
* to true for cases where the key is guaranteed to be unique in all cases. When
* false, a compound key is used, including invocation metadata. Default: false.
* @param useRawKey the useRawKey to set.
*/
public void setUseRawKey(boolean useRawKey) {
this.useRawKey = useRawKey;
}
/**
* Wrap the method invocation in a stateful retry with the policy and other helpers
* provided. If there is a failure the exception will generally be re-thrown. The only
* time it is not re-thrown is when retry is exhausted and the recovery path is taken
* (though the {@link MethodInvocationRecoverer} provided if there is one). In that
* case the value returned from the method invocation will be the value returned by
* the recoverer (so the return type for that should be the same as the intercepted
* method).
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
* @see MethodInvocationRecoverer#recover(Object[], Throwable)
*
*/
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Executing proxied method in stateful retry: " + invocation.getStaticPart() + "("
+ ObjectUtils.getIdentityHexString(invocation) + ")");
}
Object[] args = invocation.getArguments();
Object defaultKey = Arrays.asList(args);
if (args.length == 1) {
defaultKey = args[0];
}
Object key = createKey(invocation, defaultKey);
RetryState retryState = new DefaultRetryState(key,
this.newMethodArgumentsIdentifier != null && this.newMethodArgumentsIdentifier.isNew(args),
this.rollbackClassifier);
Object result = this.retryOperations.execute(new StatefulMethodInvocationRetryCallback(invocation, label),
this.recoverer != null ? new ItemRecovererCallback(args, this.recoverer) : null, retryState);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Exiting proxied method in stateful retry with result: (" + result + ")");
}
return result;
}
private Object createKey(final MethodInvocation invocation, Object defaultKey) {<FILL_FUNCTION_BODY>}
/**
* @author Dave Syer
*
*/
private static final class StatefulMethodInvocationRetryCallback
extends MethodInvocationRetryCallback<Object, Throwable> {
private StatefulMethodInvocationRetryCallback(MethodInvocation invocation, String label) {
super(invocation, label);
}
@Override
public Object doWithRetry(RetryContext context) throws Exception {
context.setAttribute(RetryContext.NAME, label);
try {
return this.invocation.proceed();
}
catch (Exception | Error e) {
throw e;
}
catch (Throwable e) {
throw new IllegalStateException(e);
}
}
}
/**
* @author Dave Syer
*
*/
private static final class ItemRecovererCallback implements RecoveryCallback<Object> {
private final Object[] args;
private final MethodInvocationRecoverer<?> recoverer;
/**
* @param args the item that failed.
*/
private ItemRecovererCallback(Object[] args, MethodInvocationRecoverer<?> recoverer) {
this.args = Arrays.asList(args).toArray();
this.recoverer = recoverer;
}
@Override
public Object recover(RetryContext context) {
return this.recoverer.recover(this.args, context.getLastThrowable());
}
}
}
|
Object generatedKey = defaultKey;
if (this.keyGenerator != null) {
generatedKey = this.keyGenerator.getKey(invocation.getArguments());
}
if (generatedKey == null) {
// If there's a generator and he still says the key is null, that means he
// really doesn't want to retry.
return null;
}
if (this.useRawKey) {
return generatedKey;
}
String name = StringUtils.hasText(label) ? label : invocation.getMethod().toGenericString();
return Arrays.asList(name, generatedKey);
| 1,666
| 160
| 1,826
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/listener/MethodInvocationRetryListenerSupport.java
|
MethodInvocationRetryListenerSupport
|
close
|
class MethodInvocationRetryListenerSupport implements RetryListener {
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {<FILL_FUNCTION_BODY>}
@Override
public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) {
if (callback instanceof MethodInvocationRetryCallback) {
MethodInvocationRetryCallback<T, E> methodInvocationRetryCallback = (MethodInvocationRetryCallback<T, E>) callback;
doOnSuccess(context, methodInvocationRetryCallback, result);
}
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
if (callback instanceof MethodInvocationRetryCallback) {
MethodInvocationRetryCallback<T, E> methodInvocationRetryCallback = (MethodInvocationRetryCallback<T, E>) callback;
doOnError(context, methodInvocationRetryCallback, throwable);
}
}
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
if (callback instanceof MethodInvocationRetryCallback) {
MethodInvocationRetryCallback<T, E> methodInvocationRetryCallback = (MethodInvocationRetryCallback<T, E>) callback;
return doOpen(context, methodInvocationRetryCallback);
}
// in case that the callback is not for a reflective method invocation
// just go forward with the execution
return true;
}
/**
* Called after the final attempt (successful or not). Allow the listener to clean up
* any resource it is holding before control returns to the retry caller.
* @param context the current {@link RetryContext}.
* @param callback the current {@link RetryCallback}.
* @param throwable the last exception that was thrown by the callback.
* @param <E> the exception type
* @param <T> the return value
*/
protected <T, E extends Throwable> void doClose(RetryContext context, MethodInvocationRetryCallback<T, E> callback,
Throwable throwable) {
}
/**
* Called after a successful attempt; allow the listener to throw a new exception to
* cause a retry (according to the retry policy), based on the result returned by the
* {@link RetryCallback#doWithRetry(RetryContext)}
* @param <T> the return type.
* @param context the current {@link RetryContext}.
* @param callback the current {@link RetryCallback}.
* @param result the result returned by the callback method.
* @since 2.0
*/
protected <T, E extends Throwable> void doOnSuccess(RetryContext context,
MethodInvocationRetryCallback<T, E> callback, T result) {
}
/**
* Called after every unsuccessful attempt at a retry.
* @param context the current {@link RetryContext}.
* @param callback the current {@link RetryCallback}.
* @param throwable the last exception that was thrown by the callback.
* @param <T> the return value
* @param <E> the exception to throw
*/
protected <T, E extends Throwable> void doOnError(RetryContext context,
MethodInvocationRetryCallback<T, E> callback, Throwable throwable) {
}
/**
* Called before the first attempt in a retry. For instance, implementers can set up
* state that is needed by the policies in the {@link RetryOperations}. The whole
* retry can be vetoed by returning false from this method, in which case a
* {@link TerminatedRetryException} will be thrown.
* @param <T> the type of object returned by the callback
* @param <E> the type of exception it declares may be thrown
* @param context the current {@link RetryContext}.
* @param callback the current {@link RetryCallback}.
* @return true if the retry should proceed.
*/
protected <T, E extends Throwable> boolean doOpen(RetryContext context,
MethodInvocationRetryCallback<T, E> callback) {
return true;
}
}
|
if (callback instanceof MethodInvocationRetryCallback) {
MethodInvocationRetryCallback<T, E> methodInvocationRetryCallback = (MethodInvocationRetryCallback<T, E>) callback;
doClose(context, methodInvocationRetryCallback, throwable);
}
| 1,105
| 74
| 1,179
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/BinaryExceptionClassifierRetryPolicy.java
|
BinaryExceptionClassifierRetryPolicy
|
canRetry
|
class BinaryExceptionClassifierRetryPolicy implements RetryPolicy {
private final BinaryExceptionClassifier exceptionClassifier;
public BinaryExceptionClassifierRetryPolicy(BinaryExceptionClassifier exceptionClassifier) {
this.exceptionClassifier = exceptionClassifier;
}
public BinaryExceptionClassifier getExceptionClassifier() {
return exceptionClassifier;
}
@Override
public boolean canRetry(RetryContext context) {<FILL_FUNCTION_BODY>}
@Override
public void close(RetryContext status) {
}
@Override
public void registerThrowable(RetryContext context, Throwable throwable) {
RetryContextSupport simpleContext = ((RetryContextSupport) context);
simpleContext.registerThrowable(throwable);
}
@Override
public RetryContext open(RetryContext parent) {
return new RetryContextSupport(parent);
}
}
|
Throwable t = context.getLastThrowable();
return t == null || exceptionClassifier.classify(t);
| 221
| 33
| 254
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/CircuitBreakerRetryPolicy.java
|
CircuitBreakerRetryContext
|
isOpen
|
class CircuitBreakerRetryContext extends RetryContextSupport {
private volatile RetryContext context;
private final RetryPolicy policy;
private volatile long start = System.currentTimeMillis();
private final long timeout;
private final long openWindow;
private final AtomicInteger shortCircuitCount = new AtomicInteger();
public CircuitBreakerRetryContext(RetryContext parent, RetryPolicy policy, long timeout, long openWindow) {
super(parent);
this.policy = policy;
this.timeout = timeout;
this.openWindow = openWindow;
this.context = createDelegateContext(policy, parent);
setAttribute("state.global", true);
}
public void reset() {
shortCircuitCount.set(0);
setAttribute(CIRCUIT_SHORT_COUNT, shortCircuitCount.get());
}
public void incrementShortCircuitCount() {
shortCircuitCount.incrementAndGet();
setAttribute(CIRCUIT_SHORT_COUNT, shortCircuitCount.get());
}
private RetryContext createDelegateContext(RetryPolicy policy, RetryContext parent) {
RetryContext context = policy.open(parent);
reset();
return context;
}
public boolean isOpen() {<FILL_FUNCTION_BODY>}
@Override
public int getRetryCount() {
return this.context.getRetryCount();
}
@Override
public String toString() {
return this.context.toString();
}
}
|
long time = System.currentTimeMillis() - this.start;
boolean retryable = this.policy.canRetry(this.context);
if (!retryable) {
if (time > this.timeout) {
logger.trace("Closing");
this.context = createDelegateContext(policy, getParent());
this.start = System.currentTimeMillis();
retryable = this.policy.canRetry(this.context);
}
else if (time < this.openWindow) {
if (!hasAttribute(CIRCUIT_OPEN) || (Boolean) getAttribute(CIRCUIT_OPEN) == false) {
logger.trace("Opening circuit");
setAttribute(CIRCUIT_OPEN, true);
this.start = System.currentTimeMillis();
}
return true;
}
}
else {
if (time > this.openWindow) {
logger.trace("Resetting context");
this.start = System.currentTimeMillis();
this.context = createDelegateContext(policy, getParent());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Open: " + !retryable);
}
setAttribute(CIRCUIT_OPEN, !retryable);
return !retryable;
| 402
| 345
| 747
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/CompositeRetryPolicy.java
|
CompositeRetryPolicy
|
open
|
class CompositeRetryPolicy implements RetryPolicy {
RetryPolicy[] policies = new RetryPolicy[0];
private boolean optimistic = false;
/**
* Setter for optimistic.
* @param optimistic should this retry policy be optimistic
*/
public void setOptimistic(boolean optimistic) {
this.optimistic = optimistic;
}
/**
* Setter for policies.
* @param policies the {@link RetryPolicy} policies
*/
public void setPolicies(RetryPolicy[] policies) {
this.policies = Arrays.asList(policies).toArray(new RetryPolicy[policies.length]);
}
/**
* Delegate to the policies that were in operation when the context was created. If
* any of them cannot retry then return false, otherwise return true.
* @param context the {@link RetryContext}
* @see org.springframework.retry.RetryPolicy#canRetry(org.springframework.retry.RetryContext)
*/
@Override
public boolean canRetry(RetryContext context) {
RetryContext[] contexts = ((CompositeRetryContext) context).contexts;
RetryPolicy[] policies = ((CompositeRetryContext) context).policies;
boolean retryable = true;
if (this.optimistic) {
retryable = false;
for (int i = 0; i < contexts.length; i++) {
if (policies[i].canRetry(contexts[i])) {
retryable = true;
}
}
}
else {
for (int i = 0; i < contexts.length; i++) {
if (!policies[i].canRetry(contexts[i])) {
retryable = false;
}
}
}
return retryable;
}
/**
* Delegate to the policies that were in operation when the context was created. If
* any of them fails to close the exception is propagated (and those later in the
* chain are closed before re-throwing).
*
* @see org.springframework.retry.RetryPolicy#close(org.springframework.retry.RetryContext)
* @param context the {@link RetryContext}
*/
@Override
public void close(RetryContext context) {
RetryContext[] contexts = ((CompositeRetryContext) context).contexts;
RetryPolicy[] policies = ((CompositeRetryContext) context).policies;
RuntimeException exception = null;
for (int i = 0; i < contexts.length; i++) {
try {
policies[i].close(contexts[i]);
}
catch (RuntimeException e) {
if (exception == null) {
exception = e;
}
}
}
if (exception != null) {
throw exception;
}
}
/**
* Creates a new context that copies the existing policies and keeps a list of the
* contexts from each one.
*
* @see org.springframework.retry.RetryPolicy#open(RetryContext)
*/
@Override
public RetryContext open(RetryContext parent) {<FILL_FUNCTION_BODY>}
/**
* Delegate to the policies that were in operation when the context was created.
*
* @see org.springframework.retry.RetryPolicy#close(org.springframework.retry.RetryContext)
*/
@Override
public void registerThrowable(RetryContext context, Throwable throwable) {
RetryContext[] contexts = ((CompositeRetryContext) context).contexts;
RetryPolicy[] policies = ((CompositeRetryContext) context).policies;
for (int i = 0; i < contexts.length; i++) {
policies[i].registerThrowable(contexts[i], throwable);
}
((RetryContextSupport) context).registerThrowable(throwable);
}
/**
* @return the lower 'maximum number of attempts before failure' between all policies
* that have a 'maximum number of attempts before failure' set, if at least one is
* present among the policies, return {@link RetryPolicy#NO_MAXIMUM_ATTEMPTS_SET}
* otherwise
*/
@Override
public int getMaxAttempts() {
return Arrays.stream(policies)
.map(RetryPolicy::getMaxAttempts)
.filter(maxAttempts -> maxAttempts != NO_MAXIMUM_ATTEMPTS_SET)
.sorted()
.findFirst()
.orElse(NO_MAXIMUM_ATTEMPTS_SET);
}
private static class CompositeRetryContext extends RetryContextSupport {
RetryContext[] contexts;
RetryPolicy[] policies;
public CompositeRetryContext(RetryContext parent, List<RetryContext> contexts, RetryPolicy[] policies) {
super(parent);
this.contexts = contexts.toArray(new RetryContext[contexts.size()]);
this.policies = policies;
}
}
}
|
List<RetryContext> list = new ArrayList<>();
for (RetryPolicy policy : this.policies) {
list.add(policy.open(parent));
}
return new CompositeRetryContext(parent, list, this.policies);
| 1,311
| 70
| 1,381
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.java
|
ExceptionClassifierRetryContext
|
getContext
|
class ExceptionClassifierRetryContext extends RetryContextSupport implements RetryPolicy {
final private Classifier<Throwable, RetryPolicy> exceptionClassifier;
// Dynamic: depends on the latest exception:
private RetryPolicy policy;
// Dynamic: depends on the policy:
private RetryContext context;
final private Map<RetryPolicy, RetryContext> contexts = new HashMap<>();
public ExceptionClassifierRetryContext(RetryContext parent,
Classifier<Throwable, RetryPolicy> exceptionClassifier) {
super(parent);
this.exceptionClassifier = exceptionClassifier;
}
public boolean canRetry(RetryContext context) {
return this.context == null || policy.canRetry(this.context);
}
public void close(RetryContext context) {
// Only close those policies that have been used (opened):
for (RetryPolicy policy : contexts.keySet()) {
policy.close(getContext(policy, context.getParent()));
}
}
public RetryContext open(RetryContext parent) {
return this;
}
public void registerThrowable(RetryContext context, Throwable throwable) {
policy = exceptionClassifier.classify(throwable);
Assert.notNull(policy, "Could not locate policy for exception=[" + throwable + "].");
this.context = getContext(policy, context.getParent());
policy.registerThrowable(this.context, throwable);
}
private RetryContext getContext(RetryPolicy policy, RetryContext parent) {<FILL_FUNCTION_BODY>}
}
|
RetryContext context = contexts.get(policy);
if (context == null) {
context = policy.open(parent);
contexts.put(policy, context);
}
return context;
| 417
| 57
| 474
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/ExpressionRetryPolicy.java
|
ExpressionRetryPolicy
|
getExpression
|
class ExpressionRetryPolicy extends SimpleRetryPolicy implements BeanFactoryAware {
private static final Log logger = LogFactory.getLog(ExpressionRetryPolicy.class);
private static final TemplateParserContext PARSER_CONTEXT = new TemplateParserContext();
private final Expression expression;
private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
/**
* Construct an instance with the provided {@link Expression}.
* @param expression the expression
*/
public ExpressionRetryPolicy(Expression expression) {
Assert.notNull(expression, "'expression' cannot be null");
this.expression = expression;
}
/**
* Construct an instance with the provided expression.
* @param expressionString the expression.
*/
public ExpressionRetryPolicy(String expressionString) {
Assert.notNull(expressionString, "'expressionString' cannot be null");
this.expression = getExpression(expressionString);
}
/**
* Construct an instance with the provided {@link Expression}.
* @param maxAttempts the max attempts
* @param retryableExceptions the exceptions
* @param traverseCauses true to examine causes
* @param expression the expression
*/
public ExpressionRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
boolean traverseCauses, Expression expression) {
super(maxAttempts, retryableExceptions, traverseCauses);
Assert.notNull(expression, "'expression' cannot be null");
this.expression = expression;
}
/**
* Construct an instance with the provided expression.
* @param maxAttempts the max attempts
* @param retryableExceptions the exceptions
* @param traverseCauses true to examine causes
* @param expressionString the expression.
* @param defaultValue the default action
*/
public ExpressionRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
boolean traverseCauses, String expressionString, boolean defaultValue) {
super(maxAttempts, retryableExceptions, traverseCauses, defaultValue);
Assert.notNull(expressionString, "'expressionString' cannot be null");
this.expression = getExpression(expressionString);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
}
public ExpressionRetryPolicy withBeanFactory(BeanFactory beanFactory) {
setBeanFactory(beanFactory);
return this;
}
@Override
public boolean canRetry(RetryContext context) {
Throwable lastThrowable = context.getLastThrowable();
if (lastThrowable == null) {
return super.canRetry(context);
}
else {
return super.canRetry(context)
&& this.expression.getValue(this.evaluationContext, lastThrowable, Boolean.class);
}
}
/**
* Get expression based on the expression string. At the moment supports both literal
* and template expressions. Template expressions are deprecated.
* @param expression the expression string
* @return literal expression or template expression
*/
private static Expression getExpression(String expression) {<FILL_FUNCTION_BODY>}
/**
* Check if the expression is a template
* @param expression the expression string
* @return true if the expression string is a template
*/
public static boolean isTemplate(String expression) {
return expression.contains(PARSER_CONTEXT.getExpressionPrefix())
&& expression.contains(PARSER_CONTEXT.getExpressionSuffix());
}
}
|
if (isTemplate(expression)) {
logger.warn("#{...} syntax is not required for this run-time expression "
+ "and is deprecated in favor of a simple expression string");
return new SpelExpressionParser().parseExpression(expression, PARSER_CONTEXT);
}
return new SpelExpressionParser().parseExpression(expression);
| 915
| 87
| 1,002
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(int, Map<Class<? extends java.lang.Throwable>,java.lang.Boolean>) ,public void <init>(int, Map<Class<? extends java.lang.Throwable>,java.lang.Boolean>, boolean) ,public void <init>(int, Map<Class<? extends java.lang.Throwable>,java.lang.Boolean>, boolean, boolean) ,public void <init>(int, org.springframework.classify.BinaryExceptionClassifier) ,public boolean canRetry(org.springframework.retry.RetryContext) ,public void close(org.springframework.retry.RetryContext) ,public int getMaxAttempts() ,public void maxAttemptsSupplier(Supplier<java.lang.Integer>) ,public org.springframework.retry.RetryContext open(org.springframework.retry.RetryContext) ,public void registerThrowable(org.springframework.retry.RetryContext, java.lang.Throwable) ,public void setMaxAttempts(int) ,public transient void setNotRecoverable(Class<? extends java.lang.Throwable>[]) ,public java.lang.String toString() <variables>public static final int DEFAULT_MAX_ATTEMPTS,private int maxAttempts,private Supplier<java.lang.Integer> maxAttemptsSupplier,private org.springframework.classify.BinaryExceptionClassifier recoverableClassifier,private org.springframework.classify.BinaryExceptionClassifier retryableClassifier
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/MapRetryContextCache.java
|
MapRetryContextCache
|
put
|
class MapRetryContextCache implements RetryContextCache {
/**
* Default value for maximum capacity of the cache. This is set to a reasonably low
* value (4096) to avoid users inadvertently filling the cache with item keys that are
* inconsistent.
*/
public static final int DEFAULT_CAPACITY = 4096;
private final Map<Object, RetryContext> map = Collections.synchronizedMap(new HashMap<>());
private int capacity;
/**
* Create a {@link MapRetryContextCache} with default capacity.
*/
public MapRetryContextCache() {
this(DEFAULT_CAPACITY);
}
/**
* @param defaultCapacity the default capacity
*/
public MapRetryContextCache(int defaultCapacity) {
super();
this.capacity = defaultCapacity;
}
/**
* Public setter for the capacity. Prevents the cache from growing unboundedly if
* items that fail are misidentified and two references to an identical item actually
* do not have the same key. This can happen when users implement equals and hashCode
* based on mutable fields, for instance.
* @param capacity the capacity to set
*/
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public RetryContext get(Object key) {
return map.get(key);
}
public void put(Object key, RetryContext context) {<FILL_FUNCTION_BODY>}
public void remove(Object key) {
map.remove(key);
}
}
|
if (map.size() >= capacity) {
throw new RetryCacheCapacityExceededException("Retry cache capacity limit breached. "
+ "Do you need to re-consider the implementation of the key generator, "
+ "or the equals and hashCode of the items that failed?");
}
map.put(key, context);
| 417
| 89
| 506
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/SoftReferenceMapRetryContextCache.java
|
SoftReferenceMapRetryContextCache
|
containsKey
|
class SoftReferenceMapRetryContextCache implements RetryContextCache {
/**
* Default value for maximum capacity of the cache. This is set to a reasonably low
* value (4096) to avoid users inadvertently filling the cache with item keys that are
* inconsistent.
*/
public static final int DEFAULT_CAPACITY = 4096;
private final Map<Object, SoftReference<RetryContext>> map = Collections.synchronizedMap(new HashMap<>());
private int capacity;
/**
* Create a {@link SoftReferenceMapRetryContextCache} with default capacity.
*/
public SoftReferenceMapRetryContextCache() {
this(DEFAULT_CAPACITY);
}
/**
* @param defaultCapacity the default capacity
*/
public SoftReferenceMapRetryContextCache(int defaultCapacity) {
super();
this.capacity = defaultCapacity;
}
/**
* Public setter for the capacity. Prevents the cache from growing unboundedly if
* items that fail are misidentified and two references to an identical item actually
* do not have the same key. This can happen when users implement equals and hashCode
* based on mutable fields, for instance.
* @param capacity the capacity to set
*/
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public boolean containsKey(Object key) {<FILL_FUNCTION_BODY>}
public RetryContext get(Object key) {
return map.get(key).get();
}
public void put(Object key, RetryContext context) {
if (map.size() >= capacity) {
throw new RetryCacheCapacityExceededException("Retry cache capacity limit breached. "
+ "Do you need to re-consider the implementation of the key generator, "
+ "or the equals and hashCode of the items that failed?");
}
map.put(key, new SoftReference<>(context));
}
public void remove(Object key) {
map.remove(key);
}
}
|
if (!map.containsKey(key)) {
return false;
}
if (map.get(key).get() == null) {
// our reference was garbage collected
map.remove(key);
}
return map.containsKey(key);
| 511
| 69
| 580
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/policy/TimeoutRetryPolicy.java
|
TimeoutRetryPolicy
|
registerThrowable
|
class TimeoutRetryPolicy implements RetryPolicy {
/**
* Default value for timeout (milliseconds).
*/
public static final long DEFAULT_TIMEOUT = 1000;
private long timeout;
/**
* Create a new instance with the timeout set to {@link #DEFAULT_TIMEOUT}.
*/
public TimeoutRetryPolicy() {
this(DEFAULT_TIMEOUT);
}
/**
* Create a new instance with a configurable timeout.
* @param timeout timeout in milliseconds
* @since 2.0.2
*/
public TimeoutRetryPolicy(long timeout) {
this.timeout = timeout;
}
/**
* Setter for timeout in milliseconds. Default is {@link #DEFAULT_TIMEOUT}.
* @param timeout how long to wait until a timeout
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/**
* The value of the timeout.
* @return the timeout in milliseconds
*/
public long getTimeout() {
return timeout;
}
/**
* Only permits a retry if the timeout has not expired. Does not check the exception
* at all.
*
* @see org.springframework.retry.RetryPolicy#canRetry(org.springframework.retry.RetryContext)
*/
public boolean canRetry(RetryContext context) {
return ((TimeoutRetryContext) context).isAlive();
}
public void close(RetryContext context) {
}
public RetryContext open(RetryContext parent) {
return new TimeoutRetryContext(parent, timeout);
}
public void registerThrowable(RetryContext context, Throwable throwable) {<FILL_FUNCTION_BODY>}
private static class TimeoutRetryContext extends RetryContextSupport {
private final long timeout;
private final long start;
public TimeoutRetryContext(RetryContext parent, long timeout) {
super(parent);
this.start = System.currentTimeMillis();
this.timeout = timeout;
}
public boolean isAlive() {
return (System.currentTimeMillis() - start) <= timeout;
}
}
}
|
((RetryContextSupport) context).registerThrowable(throwable);
// otherwise no-op - we only time out, otherwise retry everything...
| 552
| 39
| 591
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/stats/DefaultRetryStatistics.java
|
DefaultRetryStatistics
|
toString
|
class DefaultRetryStatistics extends AttributeAccessorSupport
implements RetryStatistics, MutableRetryStatistics {
private String name;
private final AtomicInteger startedCount = new AtomicInteger();
private final AtomicInteger completeCount = new AtomicInteger();
private final AtomicInteger recoveryCount = new AtomicInteger();
private final AtomicInteger errorCount = new AtomicInteger();
private final AtomicInteger abortCount = new AtomicInteger();
DefaultRetryStatistics() {
}
public DefaultRetryStatistics(String name) {
this.name = name;
}
@Override
public int getCompleteCount() {
return completeCount.get();
}
@Override
public int getStartedCount() {
return startedCount.get();
}
@Override
public int getErrorCount() {
return errorCount.get();
}
@Override
public int getAbortCount() {
return abortCount.get();
}
@Override
public String getName() {
return name;
}
@Override
public int getRecoveryCount() {
return recoveryCount.get();
}
public void setName(String name) {
this.name = name;
}
@Override
public void incrementStartedCount() {
this.startedCount.incrementAndGet();
}
@Override
public void incrementCompleteCount() {
this.completeCount.incrementAndGet();
}
@Override
public void incrementRecoveryCount() {
this.recoveryCount.incrementAndGet();
}
@Override
public void incrementErrorCount() {
this.errorCount.incrementAndGet();
}
@Override
public void incrementAbortCount() {
this.abortCount.incrementAndGet();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DefaultRetryStatistics [name=" + name + ", startedCount=" + startedCount + ", completeCount="
+ completeCount + ", recoveryCount=" + recoveryCount + ", errorCount=" + errorCount + ", abortCount="
+ abortCount + "]";
| 462
| 73
| 535
|
<methods>public void <init>() ,public java.lang.String[] attributeNames() ,public T computeAttribute(java.lang.String, Function<java.lang.String,T>) ,public boolean equals(java.lang.Object) ,public java.lang.Object getAttribute(java.lang.String) ,public boolean hasAttribute(java.lang.String) ,public int hashCode() ,public java.lang.Object removeAttribute(java.lang.String) ,public void setAttribute(java.lang.String, java.lang.Object) <variables>private final Map<java.lang.String,java.lang.Object> attributes
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/stats/DefaultStatisticsRepository.java
|
DefaultStatisticsRepository
|
getStatistics
|
class DefaultStatisticsRepository implements StatisticsRepository {
private final ConcurrentMap<String, MutableRetryStatistics> map = new ConcurrentHashMap<>();
private RetryStatisticsFactory factory = new DefaultRetryStatisticsFactory();
public void setRetryStatisticsFactory(RetryStatisticsFactory factory) {
this.factory = factory;
}
@Override
public RetryStatistics findOne(String name) {
return map.get(name);
}
@Override
public Iterable<RetryStatistics> findAll() {
return new ArrayList<>(map.values());
}
@Override
public void addStarted(String name) {
getStatistics(name).incrementStartedCount();
}
@Override
public void addError(String name) {
getStatistics(name).incrementErrorCount();
}
@Override
public void addRecovery(String name) {
getStatistics(name).incrementRecoveryCount();
}
@Override
public void addComplete(String name) {
getStatistics(name).incrementCompleteCount();
}
@Override
public void addAbort(String name) {
getStatistics(name).incrementAbortCount();
}
private MutableRetryStatistics getStatistics(String name) {<FILL_FUNCTION_BODY>}
}
|
MutableRetryStatistics stats;
if (!map.containsKey(name)) {
map.putIfAbsent(name, factory.create(name));
}
stats = map.get(name);
return stats;
| 331
| 63
| 394
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/stats/ExponentialAverageRetryStatistics.java
|
ExponentialAverageRetryStatistics
|
getRollingErrorRate
|
class ExponentialAverageRetryStatistics extends DefaultRetryStatistics {
private long window = 15000;
private ExponentialAverage started;
private ExponentialAverage error;
private ExponentialAverage complete;
private ExponentialAverage recovery;
private ExponentialAverage abort;
public ExponentialAverageRetryStatistics(String name) {
super(name);
init();
}
private void init() {
started = new ExponentialAverage(window);
error = new ExponentialAverage(window);
complete = new ExponentialAverage(window);
abort = new ExponentialAverage(window);
recovery = new ExponentialAverage(window);
}
/**
* Window in milliseconds for exponential decay factor in rolling average.
* @param window the window to set
*/
public void setWindow(long window) {
this.window = window;
init();
}
public int getRollingStartedCount() {
return (int) Math.round(started.getValue());
}
public int getRollingErrorCount() {
return (int) Math.round(error.getValue());
}
public int getRollingAbortCount() {
return (int) Math.round(abort.getValue());
}
public int getRollingRecoveryCount() {
return (int) Math.round(recovery.getValue());
}
public int getRollingCompleteCount() {
return (int) Math.round(complete.getValue());
}
public double getRollingErrorRate() {<FILL_FUNCTION_BODY>}
@Override
public void incrementStartedCount() {
super.incrementStartedCount();
started.increment();
}
@Override
public void incrementCompleteCount() {
super.incrementCompleteCount();
complete.increment();
}
@Override
public void incrementRecoveryCount() {
super.incrementRecoveryCount();
recovery.increment();
}
@Override
public void incrementErrorCount() {
super.incrementErrorCount();
error.increment();
}
@Override
public void incrementAbortCount() {
super.incrementAbortCount();
abort.increment();
}
private class ExponentialAverage {
private final double alpha;
private volatile long lastTime = System.currentTimeMillis();
private volatile double value = 0;
public ExponentialAverage(long window) {
alpha = 1. / window;
}
public synchronized void increment() {
long time = System.currentTimeMillis();
value = value * Math.exp(-alpha * (time - lastTime)) + 1;
lastTime = time;
}
public double getValue() {
long time = System.currentTimeMillis();
return value * Math.exp(-alpha * (time - lastTime));
}
}
}
|
if (Math.round(started.getValue()) == 0) {
return 0.;
}
return (abort.getValue() + recovery.getValue()) / started.getValue();
| 751
| 48
| 799
|
<methods>public void <init>(java.lang.String) ,public int getAbortCount() ,public int getCompleteCount() ,public int getErrorCount() ,public java.lang.String getName() ,public int getRecoveryCount() ,public int getStartedCount() ,public void incrementAbortCount() ,public void incrementCompleteCount() ,public void incrementErrorCount() ,public void incrementRecoveryCount() ,public void incrementStartedCount() ,public void setName(java.lang.String) ,public java.lang.String toString() <variables>private final java.util.concurrent.atomic.AtomicInteger abortCount,private final java.util.concurrent.atomic.AtomicInteger completeCount,private final java.util.concurrent.atomic.AtomicInteger errorCount,private java.lang.String name,private final java.util.concurrent.atomic.AtomicInteger recoveryCount,private final java.util.concurrent.atomic.AtomicInteger startedCount
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/stats/StatisticsListener.java
|
StatisticsListener
|
onError
|
class StatisticsListener implements RetryListener {
private final StatisticsRepository repository;
public StatisticsListener(StatisticsRepository repository) {
this.repository = repository;
}
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
String name = getName(context);
if (name != null) {
if (!isExhausted(context) || isGlobal(context)) {
// If exhausted and stateful then the retry callback was not called. If
// exhausted and stateless it was called, but the started counter was
// already incremented.
repository.addStarted(name);
}
if (isRecovered(context)) {
repository.addRecovery(name);
}
else if (isExhausted(context)) {
repository.addAbort(name);
}
else if (isClosed(context)) {
repository.addComplete(name);
}
RetryStatistics stats = repository.findOne(name);
if (stats instanceof AttributeAccessor) {
AttributeAccessor accessor = (AttributeAccessor) stats;
for (String key : new String[] { CircuitBreakerRetryPolicy.CIRCUIT_OPEN,
CircuitBreakerRetryPolicy.CIRCUIT_SHORT_COUNT }) {
if (context.hasAttribute(key)) {
accessor.setAttribute(key, context.getAttribute(key));
}
}
}
}
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {<FILL_FUNCTION_BODY>}
private boolean isGlobal(RetryContext context) {
return context.hasAttribute("state.global");
}
private boolean isExhausted(RetryContext context) {
return context.hasAttribute(RetryContext.EXHAUSTED);
}
private boolean isClosed(RetryContext context) {
return context.hasAttribute(RetryContext.CLOSED);
}
private boolean isRecovered(RetryContext context) {
return context.hasAttribute(RetryContext.RECOVERED);
}
private boolean hasState(RetryContext context) {
return context.hasAttribute(RetryContext.STATE_KEY);
}
private String getName(RetryContext context) {
return (String) context.getAttribute(RetryContext.NAME);
}
}
|
String name = getName(context);
if (name != null) {
if (!hasState(context)) {
// Stateless retry involves starting the retry callback once per error
// without closing the context, so we need to increment the started count
repository.addStarted(name);
}
repository.addError(name);
}
| 639
| 92
| 731
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/support/DefaultRetryState.java
|
DefaultRetryState
|
rollbackFor
|
class DefaultRetryState implements RetryState {
final private Object key;
final private boolean forceRefresh;
final private Classifier<? super Throwable, Boolean> rollbackClassifier;
/**
* Create a {@link DefaultRetryState} representing the state for a new retry attempt.
*
* @see RetryOperations#execute(RetryCallback, RetryState)
* @see RetryOperations#execute(RetryCallback, RecoveryCallback, RetryState)
* @param key the key for the state to allow this retry attempt to be recognised
* @param forceRefresh true if the attempt is known to be a brand new state (could not
* have previously failed)
* @param rollbackClassifier the rollback classifier to set. The rollback classifier
* answers true if the exception provided should cause a rollback.
*/
public DefaultRetryState(Object key, boolean forceRefresh,
Classifier<? super Throwable, Boolean> rollbackClassifier) {
this.key = key;
this.forceRefresh = forceRefresh;
this.rollbackClassifier = rollbackClassifier;
}
/**
* Defaults the force refresh flag to false.
* @see DefaultRetryState#DefaultRetryState(Object, boolean, Classifier)
* @param key the key
* @param rollbackClassifier the rollback {@link Classifier}
*/
public DefaultRetryState(Object key, Classifier<? super Throwable, Boolean> rollbackClassifier) {
this(key, false, rollbackClassifier);
}
/**
* Defaults the rollback classifier to null.
* @see DefaultRetryState#DefaultRetryState(Object, boolean, Classifier)
* @param key the key
* @param forceRefresh whether to force a refresh
*/
public DefaultRetryState(Object key, boolean forceRefresh) {
this(key, forceRefresh, null);
}
/**
* Defaults the force refresh flag (to false) and the rollback classifier (to null).
* @param key the key to use
* @see DefaultRetryState#DefaultRetryState(Object, boolean, Classifier)
*/
public DefaultRetryState(Object key) {
this(key, false, null);
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.retry.IRetryState#getKey()
*/
public Object getKey() {
return key;
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.retry.IRetryState#isForceRefresh()
*/
public boolean isForceRefresh() {
return forceRefresh;
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.retry.RetryState#rollbackFor(java.lang.Throwable )
*/
public boolean rollbackFor(Throwable exception) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("[%s: key=%s, forceRefresh=%b]", getClass().getSimpleName(), key, forceRefresh);
}
}
|
if (rollbackClassifier == null) {
return true;
}
return rollbackClassifier.classify(exception);
| 804
| 36
| 840
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/support/RetrySimulation.java
|
RetrySimulation
|
getPercentile
|
class RetrySimulation {
private final List<SleepSequence> sleepSequences = new ArrayList<>();
private final List<Long> sleepHistogram = new ArrayList<>();
public RetrySimulation() {
}
/**
* Add a sequence of sleeps to the simulation.
* @param sleeps the times to be created as a {@link SleepSequence}
*/
public void addSequence(List<Long> sleeps) {
sleepHistogram.addAll(sleeps);
sleepSequences.add(new SleepSequence(sleeps));
}
/**
* @return Returns a list of all the unique sleep values which were executed within
* all simulations.
*/
public List<Double> getPercentiles() {
List<Double> res = new ArrayList<>();
for (double percentile : new double[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 }) {
res.add(getPercentile(percentile / 100));
}
return res;
}
public double getPercentile(double p) {<FILL_FUNCTION_BODY>}
/**
* @return the longest total time slept by a retry sequence.
*/
public SleepSequence getLongestTotalSleepSequence() {
SleepSequence longest = null;
for (SleepSequence sequence : sleepSequences) {
if (longest == null || sequence.getTotalSleep() > longest.getTotalSleep()) {
longest = sequence;
}
}
return longest;
}
public static class SleepSequence {
private final List<Long> sleeps;
private final long longestSleep;
private final long totalSleep;
public SleepSequence(List<Long> sleeps) {
this.sleeps = sleeps;
this.longestSleep = Collections.max(sleeps);
long totalSleep = 0;
for (Long sleep : sleeps) {
totalSleep += sleep;
}
this.totalSleep = totalSleep;
}
public List<Long> getSleeps() {
return sleeps;
}
/**
* @return the longest individual sleep within this sequence
*/
public long getLongestSleep() {
return longestSleep;
}
public long getTotalSleep() {
return totalSleep;
}
public String toString() {
return "totalSleep=" + totalSleep + ": " + sleeps.toString();
}
}
}
|
Collections.sort(sleepHistogram);
int size = sleepHistogram.size();
double pos = p * (size - 1);
int i0 = (int) pos;
int i1 = i0 + 1;
double weight = pos - i0;
return sleepHistogram.get(i0) * (1 - weight) + sleepHistogram.get(i1) * weight;
| 661
| 104
| 765
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/support/RetrySimulator.java
|
RetrySimulator
|
executeSimulation
|
class RetrySimulator {
private final SleepingBackOffPolicy<?> backOffPolicy;
private final RetryPolicy retryPolicy;
public RetrySimulator(SleepingBackOffPolicy<?> backOffPolicy, RetryPolicy retryPolicy) {
this.backOffPolicy = backOffPolicy;
this.retryPolicy = retryPolicy;
}
/**
* Execute the simulator for a give # of iterations.
* @param numSimulations Number of simulations to run
* @return the outcome of all simulations
*/
public RetrySimulation executeSimulation(int numSimulations) {<FILL_FUNCTION_BODY>}
/**
* Execute a single simulation
* @return The sleeps which occurred within the single simulation.
*/
public List<Long> executeSingleSimulation() {
StealingSleeper stealingSleeper = new StealingSleeper();
SleepingBackOffPolicy<?> stealingBackoff = backOffPolicy.withSleeper(stealingSleeper);
RetryTemplate template = new RetryTemplate();
template.setBackOffPolicy(stealingBackoff);
template.setRetryPolicy(retryPolicy);
try {
template.execute(new FailingRetryCallback());
}
catch (FailingRetryException e) {
}
catch (Throwable e) {
throw new RuntimeException("Unexpected exception", e);
}
return stealingSleeper.getSleeps();
}
static class FailingRetryCallback implements RetryCallback<Object, Exception> {
public Object doWithRetry(RetryContext context) throws Exception {
throw new FailingRetryException();
}
}
@SuppressWarnings("serial")
static class FailingRetryException extends Exception {
}
@SuppressWarnings("serial")
static class StealingSleeper implements Sleeper {
private final List<Long> sleeps = new ArrayList<>();
public void sleep(long backOffPeriod) throws InterruptedException {
sleeps.add(backOffPeriod);
}
public List<Long> getSleeps() {
return sleeps;
}
}
}
|
RetrySimulation simulation = new RetrySimulation();
for (int i = 0; i < numSimulations; i++) {
simulation.addSequence(executeSingleSimulation());
}
return simulation;
| 566
| 60
| 626
|
<no_super_class>
|
spring-projects_spring-retry
|
spring-retry/src/main/java/org/springframework/retry/support/RetrySynchronizationManager.java
|
RetrySynchronizationManager
|
clear
|
class RetrySynchronizationManager {
private RetrySynchronizationManager() {
}
private static final ThreadLocal<RetryContext> context = new ThreadLocal<>();
private static final Map<Thread, RetryContext> contexts = new ConcurrentHashMap<>();
private static boolean useThreadLocal = true;
/**
* Set to false to store the context in a map (keyed by the current thread) instead of
* in a {@link ThreadLocal}. Recommended when using virtual threads.
* @param use true to use a {@link ThreadLocal} (default true).
* @since 2.0.3
*/
public static void setUseThreadLocal(boolean use) {
useThreadLocal = use;
}
/**
* Return true if contexts are held in a ThreadLocal (default) rather than a Map.
* @return the useThreadLocal
* @since 2.0.3
*/
public static boolean isUseThreadLocal() {
return useThreadLocal;
}
/**
* Public accessor for the locally enclosing {@link RetryContext}.
* @return the current retry context, or null if there isn't one
*/
@Nullable
public static RetryContext getContext() {
if (useThreadLocal) {
return context.get();
}
else {
return contexts.get(Thread.currentThread());
}
}
/**
* Method for registering a context - should only be used by {@link RetryOperations}
* implementations to ensure that {@link #getContext()} always returns the correct
* value.
* @param context the new context to register
* @return the old context if there was one
*/
@Nullable
public static RetryContext register(RetryContext context) {
if (useThreadLocal) {
RetryContext oldContext = getContext();
RetrySynchronizationManager.context.set(context);
return oldContext;
}
else {
RetryContext oldContext = contexts.get(Thread.currentThread());
contexts.put(Thread.currentThread(), context);
return oldContext;
}
}
/**
* Clear the current context at the end of a batch - should only be used by
* {@link RetryOperations} implementations.
* @return the old value if there was one.
*/
@Nullable
public static RetryContext clear() {<FILL_FUNCTION_BODY>}
}
|
RetryContext value = getContext();
RetryContext parent = value == null ? null : value.getParent();
if (useThreadLocal) {
RetrySynchronizationManager.context.set(parent);
}
else {
if (parent != null) {
contexts.put(Thread.currentThread(), parent);
}
else {
contexts.remove(Thread.currentThread());
}
}
return value;
| 600
| 121
| 721
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/conditions/SpecPropertiesCondition.java
|
SpecPropertiesCondition
|
matches
|
class SpecPropertiesCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>}
}
|
final BindResult<SpringDocConfigProperties> result = Binder.get(context.getEnvironment())
.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
if (result.isBound()) {
SpringDocConfigProperties springDocConfigProperties = result.get();
if (springDocConfigProperties.getOpenApi() != null)
return true;
Set<GroupConfig> groupConfigs = springDocConfigProperties.getGroupConfigs();
return groupConfigs.stream().anyMatch(config -> config.getOpenApi() != null);
}
return false;
| 46
| 154
| 200
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocConfiguration.java
|
QuerydslProvider
|
queryDslQuerydslPredicateOperationCustomizer
|
class QuerydslProvider {
/**
* Query dsl querydsl predicate operation customizer querydsl predicate operation customizer.
*
* @param querydslBindingsFactory the querydsl bindings factory
* @param springDocConfigProperties the spring doc config properties
* @return the querydsl predicate operation customizer
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
QuerydslPredicateOperationCustomizer queryDslQuerydslPredicateOperationCustomizer(Optional<QuerydslBindingsFactory> querydslBindingsFactory,
SpringDocConfigProperties springDocConfigProperties) {<FILL_FUNCTION_BODY>}
}
|
if (querydslBindingsFactory.isPresent()) {
getConfig().addRequestWrapperToIgnore(Predicate.class);
return new QuerydslPredicateOperationCustomizer(querydslBindingsFactory.get(), springDocConfigProperties);
}
return null;
| 171
| 70
| 241
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocDataRestConfiguration.java
|
SpringRepositoryRestResourceProviderConfiguration
|
springRepositoryRestResourceProvider
|
class SpringRepositoryRestResourceProviderConfiguration {
static {
getConfig().replaceParameterObjectWithClass(DefaultedPageable.class, DefaultPageable.class)
.addRequestWrapperToIgnore(RootResourceInformation.class, PersistentEntityResourceAssembler.class, ETag.class, Sort.class)
.addResponseWrapperToIgnore(RootResourceInformation.class);
}
/**
* Spring repository rest resource provider spring repository rest resource provider.
*
* @param mappings the mappings
* @param repositories the repositories
* @param associations the associations
* @param applicationContext the application context
* @param dataRestRouterOperationService the data rest router operation service
* @param persistentEntities the persistent entities
* @param mapper the mapper
* @param springDocDataRestUtils the spring doc data rest utils
* @return the spring repository rest resource provider
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
SpringRepositoryRestResourceProvider springRepositoryRestResourceProvider(ResourceMappings mappings,
Repositories repositories, Associations associations, ApplicationContext applicationContext,
DataRestRouterOperationService dataRestRouterOperationService, PersistentEntities persistentEntities,
ObjectMapper mapper, SpringDocDataRestUtils springDocDataRestUtils) {<FILL_FUNCTION_BODY>}
/**
* Data rest router operation builder data rest router operation service.
*
* @param dataRestOperationService the data rest operation service
* @param springDocConfigProperties the spring doc config properties
* @param repositoryRestConfiguration the repository rest configuration
* @param dataRestHalProvider the data rest hal provider
* @return the data rest router operation service
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
DataRestRouterOperationService dataRestRouterOperationBuilder(DataRestOperationService dataRestOperationService,
SpringDocConfigProperties springDocConfigProperties, RepositoryRestConfiguration repositoryRestConfiguration, DataRestHalProvider dataRestHalProvider) {
return new DataRestRouterOperationService(dataRestOperationService, springDocConfigProperties, repositoryRestConfiguration, dataRestHalProvider);
}
/**
* Data rest operation builder data rest operation builder.
*
* @param dataRestRequestService the data rest request builder
* @param tagsBuilder the tags builder
* @param dataRestResponseService the data rest response builder
* @param operationService the operation service
* @return the data rest operation builder
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
DataRestOperationService dataRestOperationBuilder(DataRestRequestService dataRestRequestService, DataRestTagsService tagsBuilder,
DataRestResponseService dataRestResponseService, OperationService operationService) {
return new DataRestOperationService(dataRestRequestService, tagsBuilder, dataRestResponseService, operationService);
}
/**
* Data rest request builder data rest request builder.
*
* @param localSpringDocParameterNameDiscoverer the local spring doc parameter name discoverer
* @param parameterBuilder the parameter builder
* @param requestBodyService the request body builder
* @param requestBuilder the request builder
* @param springDocDataRestUtils the spring doc data rest utils
* @return the data rest request builder
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
DataRestRequestService dataRestRequestBuilder(SpringDocParameterNameDiscoverer localSpringDocParameterNameDiscoverer, GenericParameterService parameterBuilder,
RequestBodyService requestBodyService, AbstractRequestService requestBuilder, SpringDocDataRestUtils springDocDataRestUtils) {
return new DataRestRequestService(localSpringDocParameterNameDiscoverer, parameterBuilder,
requestBodyService, requestBuilder, springDocDataRestUtils);
}
/**
* Data rest response builder data rest response builder.
*
* @param genericResponseService the generic response builder
* @param springDocDataRestUtils the spring doc data rest utils
* @return the data rest response builder
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
DataRestResponseService dataRestResponseBuilder(GenericResponseService genericResponseService, SpringDocDataRestUtils springDocDataRestUtils) {
return new DataRestResponseService(genericResponseService, springDocDataRestUtils);
}
/**
* Data rest tags builder data rest tags builder.
*
* @param openAPIService the open api builder
* @return the data rest tags builder
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
DataRestTagsService dataRestTagsBuilder(OpenAPIService openAPIService) {
return new DataRestTagsService(openAPIService);
}
/**
* Spring doc data rest utils spring doc data rest utils.
*
* @param linkRelationProvider the link relation provider
* @param repositoryRestConfiguration the repository rest configuration
* @return the spring doc data rest utils
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
SpringDocDataRestUtils springDocDataRestUtils(LinkRelationProvider linkRelationProvider, RepositoryRestConfiguration repositoryRestConfiguration) {
return new SpringDocDataRestUtils(linkRelationProvider, repositoryRestConfiguration);
}
}
|
return new SpringRepositoryRestResourceProvider(mappings, repositories, associations, applicationContext,
dataRestRouterOperationService, persistentEntities, mapper, springDocDataRestUtils);
| 1,320
| 47
| 1,367
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocHateoasConfiguration.java
|
SpringDocHateoasConfiguration
|
linksSchemaCustomizer
|
class SpringDocHateoasConfiguration {
/**
* Hateoas hal provider hateoas hal provider.
*
* @param hateoasPropertiesOptional the hateoas properties optional
* @param objectMapperProvider the object mapper provider
* @return the hateoas hal provider
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
HateoasHalProvider hateoasHalProvider(Optional<HateoasProperties> hateoasPropertiesOptional, ObjectMapperProvider objectMapperProvider) {
return new HateoasHalProvider(hateoasPropertiesOptional, objectMapperProvider);
}
/**
* Collection model content converter collection model content converter.
*
* @param halProvider the hal provider
* @param linkRelationProvider the link relation provider
* @return the collection model content converter
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
CollectionModelContentConverter collectionModelContentConverter(HateoasHalProvider halProvider, LinkRelationProvider linkRelationProvider) {
return halProvider.isHalEnabled() ? new CollectionModelContentConverter(linkRelationProvider) : null;
}
/**
* Registers an OpenApiCustomizer and a jackson mixin to ensure the definition of `Links` matches the serialized
* output. This is done because the customer serializer converts the data to a map before serializing it.
*
* @param halProvider the hal provider
* @param springDocConfigProperties the spring doc config properties
* @param objectMapperProvider the object mapper provider
* @return the open api customizer
* @see org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider) org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)
*/
@Bean(Constants.LINKS_SCHEMA_CUSTOMISER)
@ConditionalOnMissingBean(name = Constants.LINKS_SCHEMA_CUSTOMISER)
@Lazy(false)
GlobalOpenApiCustomizer linksSchemaCustomizer(HateoasHalProvider halProvider, SpringDocConfigProperties springDocConfigProperties,
ObjectMapperProvider objectMapperProvider) {<FILL_FUNCTION_BODY>}
}
|
if (!halProvider.isHalEnabled()) {
return openApi -> {
};
}
objectMapperProvider.jsonMapper().addMixIn(RepresentationModel.class, RepresentationModelLinksOASMixin.class);
return new OpenApiHateoasLinksCustomizer(springDocConfigProperties);
| 753
| 83
| 836
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocJacksonKotlinModuleConfiguration.java
|
SpringDocJacksonKotlinModuleConfiguration
|
springdocKotlinObjectMapperProvider
|
class SpringDocJacksonKotlinModuleConfiguration {
/**
* Instantiates a new objectMapperProvider with a kotlin module.
*
* @param springDocConfigProperties the spring doc config properties
*/
@Bean
@Primary
ObjectMapperProvider springdocKotlinObjectMapperProvider(SpringDocConfigProperties springDocConfigProperties) {<FILL_FUNCTION_BODY>}
}
|
ObjectMapperProvider mapperProvider = new ObjectMapperProvider(springDocConfigProperties);
mapperProvider.jsonMapper().registerModule(new KotlinModule.Builder().build());
return mapperProvider;
| 99
| 53
| 152
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocRequiredModule.java
|
RespectSchemaRequiredAnnotationIntrospector
|
hasRequiredMarker
|
class RespectSchemaRequiredAnnotationIntrospector extends SwaggerAnnotationIntrospector {
@Override
public Boolean hasRequiredMarker(AnnotatedMember annotatedMember) {<FILL_FUNCTION_BODY>}
}
|
Schema schemaAnnotation = annotatedMember.getAnnotation(Schema.class);
if (schemaAnnotation != null) {
Schema.RequiredMode requiredMode = schemaAnnotation.requiredMode();
if (schemaAnnotation.required() || requiredMode == Schema.RequiredMode.REQUIRED) {
return true;
}
else if (requiredMode == Schema.RequiredMode.NOT_REQUIRED || StringUtils.isNotEmpty(schemaAnnotation.defaultValue())) {
return false;
}
}
return super.hasRequiredMarker(annotatedMember);
| 54
| 139
| 193
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(com.fasterxml.jackson.core.Version) ,public void <init>(java.lang.String, com.fasterxml.jackson.core.Version) ,public void <init>(java.lang.String, com.fasterxml.jackson.core.Version, Map<Class<?>,JsonDeserializer<?>>) ,public void <init>(java.lang.String, com.fasterxml.jackson.core.Version, List<JsonSerializer<?>>) ,public void <init>(java.lang.String, com.fasterxml.jackson.core.Version, Map<Class<?>,JsonDeserializer<?>>, List<JsonSerializer<?>>) ,public com.fasterxml.jackson.databind.module.SimpleModule addAbstractTypeMapping(Class<T>, Class<? extends T>) ,public com.fasterxml.jackson.databind.module.SimpleModule addDeserializer(Class<T>, JsonDeserializer<? extends T>) ,public com.fasterxml.jackson.databind.module.SimpleModule addKeyDeserializer(Class<?>, com.fasterxml.jackson.databind.KeyDeserializer) ,public com.fasterxml.jackson.databind.module.SimpleModule addKeySerializer(Class<? extends T>, JsonSerializer<T>) ,public com.fasterxml.jackson.databind.module.SimpleModule addSerializer(JsonSerializer<?>) ,public com.fasterxml.jackson.databind.module.SimpleModule addSerializer(Class<? extends T>, JsonSerializer<T>) ,public com.fasterxml.jackson.databind.module.SimpleModule addValueInstantiator(Class<?>, com.fasterxml.jackson.databind.deser.ValueInstantiator) ,public java.lang.String getModuleName() ,public java.lang.Object getTypeId() ,public transient com.fasterxml.jackson.databind.module.SimpleModule registerSubtypes(Class<?>[]) ,public transient com.fasterxml.jackson.databind.module.SimpleModule registerSubtypes(com.fasterxml.jackson.databind.jsontype.NamedType[]) ,public com.fasterxml.jackson.databind.module.SimpleModule registerSubtypes(Collection<Class<?>>) ,public void setAbstractTypes(com.fasterxml.jackson.databind.module.SimpleAbstractTypeResolver) ,public com.fasterxml.jackson.databind.module.SimpleModule setDeserializerModifier(com.fasterxml.jackson.databind.deser.BeanDeserializerModifier) ,public void setDeserializers(com.fasterxml.jackson.databind.module.SimpleDeserializers) ,public void setKeyDeserializers(com.fasterxml.jackson.databind.module.SimpleKeyDeserializers) ,public void setKeySerializers(com.fasterxml.jackson.databind.module.SimpleSerializers) ,public com.fasterxml.jackson.databind.module.SimpleModule setMixInAnnotation(Class<?>, Class<?>) ,public com.fasterxml.jackson.databind.module.SimpleModule setSerializerModifier(com.fasterxml.jackson.databind.ser.BeanSerializerModifier) ,public void setSerializers(com.fasterxml.jackson.databind.module.SimpleSerializers) ,public void setValueInstantiators(com.fasterxml.jackson.databind.module.SimpleValueInstantiators) ,public void setupModule(com.fasterxml.jackson.databind.Module.SetupContext) ,public com.fasterxml.jackson.core.Version version() <variables>private static final java.util.concurrent.atomic.AtomicInteger MODULE_ID_SEQ,protected com.fasterxml.jackson.databind.module.SimpleAbstractTypeResolver _abstractTypes,protected com.fasterxml.jackson.databind.deser.BeanDeserializerModifier _deserializerModifier,protected com.fasterxml.jackson.databind.module.SimpleDeserializers _deserializers,protected final boolean _hasExplicitName,protected com.fasterxml.jackson.databind.module.SimpleKeyDeserializers _keyDeserializers,protected com.fasterxml.jackson.databind.module.SimpleSerializers _keySerializers,protected HashMap<Class<?>,Class<?>> _mixins,protected final java.lang.String _name,protected com.fasterxml.jackson.databind.PropertyNamingStrategy _namingStrategy,protected com.fasterxml.jackson.databind.ser.BeanSerializerModifier _serializerModifier,protected com.fasterxml.jackson.databind.module.SimpleSerializers _serializers,protected LinkedHashSet<com.fasterxml.jackson.databind.jsontype.NamedType> _subtypes,protected com.fasterxml.jackson.databind.module.SimpleValueInstantiators _valueInstantiators,protected final com.fasterxml.jackson.core.Version _version,private static final long serialVersionUID
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocSecurityConfiguration.java
|
SpringSecurityLoginEndpointConfiguration
|
springSecurityLoginEndpointCustomiser
|
class SpringSecurityLoginEndpointConfiguration {
/**
* Spring security login endpoint customiser open api customiser.
*
* @param applicationContext the application context
* @return the open api customiser
*/
@Bean
@ConditionalOnProperty(SPRINGDOC_SHOW_LOGIN_ENDPOINT)
@Lazy(false)
OpenApiCustomizer springSecurityLoginEndpointCustomiser(ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
}
|
FilterChainProxy filterChainProxy = applicationContext.getBean(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME, FilterChainProxy.class);
return openAPI -> {
for (SecurityFilterChain filterChain : filterChainProxy.getFilterChains()) {
Optional<UsernamePasswordAuthenticationFilter> optionalFilter =
filterChain.getFilters().stream()
.filter(UsernamePasswordAuthenticationFilter.class::isInstance)
.map(UsernamePasswordAuthenticationFilter.class::cast)
.findAny();
Optional<DefaultLoginPageGeneratingFilter> optionalDefaultLoginPageGeneratingFilter =
filterChain.getFilters().stream()
.filter(DefaultLoginPageGeneratingFilter.class::isInstance)
.map(DefaultLoginPageGeneratingFilter.class::cast)
.findAny();
if (optionalFilter.isPresent()) {
UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter = optionalFilter.get();
Operation operation = new Operation();
Schema<?> schema = new ObjectSchema()
.addProperty(usernamePasswordAuthenticationFilter.getUsernameParameter(), new StringSchema())
.addProperty(usernamePasswordAuthenticationFilter.getPasswordParameter(), new StringSchema());
String mediaType = org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
if (optionalDefaultLoginPageGeneratingFilter.isPresent()) {
DefaultLoginPageGeneratingFilter defaultLoginPageGeneratingFilter = optionalDefaultLoginPageGeneratingFilter.get();
Field formLoginEnabledField = FieldUtils.getDeclaredField(DefaultLoginPageGeneratingFilter.class, "formLoginEnabled", true);
try {
boolean formLoginEnabled = (boolean) formLoginEnabledField.get(defaultLoginPageGeneratingFilter);
if (formLoginEnabled)
mediaType = org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
}
catch (IllegalAccessException e) {
LOGGER.warn(e.getMessage());
}
}
RequestBody requestBody = new RequestBody().content(new Content().addMediaType(mediaType, new MediaType().schema(schema)));
operation.requestBody(requestBody);
ApiResponses apiResponses = new ApiResponses();
apiResponses.addApiResponse(String.valueOf(HttpStatus.OK.value()), new ApiResponse().description(HttpStatus.OK.getReasonPhrase()));
apiResponses.addApiResponse(String.valueOf(HttpStatus.FORBIDDEN.value()), new ApiResponse().description(HttpStatus.FORBIDDEN.getReasonPhrase()));
operation.responses(apiResponses);
operation.addTagsItem("login-endpoint");
PathItem pathItem = new PathItem().post(operation);
try {
Field requestMatcherField = AbstractAuthenticationProcessingFilter.class.getDeclaredField("requiresAuthenticationRequestMatcher");
requestMatcherField.setAccessible(true);
AntPathRequestMatcher requestMatcher = (AntPathRequestMatcher) requestMatcherField.get(usernamePasswordAuthenticationFilter);
String loginPath = requestMatcher.getPattern();
requestMatcherField.setAccessible(false);
openAPI.getPaths().addPathItem(loginPath, pathItem);
}
catch (NoSuchFieldException | IllegalAccessException |
ClassCastException ignored) {
// Exception escaped
LOGGER.trace(ignored.getMessage());
}
}
}
};
| 122
| 868
| 990
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocSecurityOAuth2EndpointUtils.java
|
SpringDocSecurityOAuth2EndpointUtils
|
findEndpoint
|
class SpringDocSecurityOAuth2EndpointUtils<T> {
/**
* The Oauth 2 endpoint filter.
*/
private T oauth2EndpointFilter;
/**
* Instantiates a new Spring doc security o auth 2 endpoint utils.
*
* @param oauth2EndpointFilter the oauth 2 endpoint filter
*/
public SpringDocSecurityOAuth2EndpointUtils(T oauth2EndpointFilter) {
this.oauth2EndpointFilter = oauth2EndpointFilter;
}
/**
* Find endpoint object.
*
* @param filterChain the filter chain
* @return the object
*/
public Object findEndpoint(SecurityFilterChain filterChain) {<FILL_FUNCTION_BODY>}
}
|
Optional<?> oAuth2EndpointFilterOptional =
filterChain.getFilters().stream()
.filter(((Class <?>) oauth2EndpointFilter)::isInstance)
.map(((Class <?>) oauth2EndpointFilter)::cast)
.findAny();
return oAuth2EndpointFilterOptional.orElse(null);
| 182
| 94
| 276
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocSpecPropertiesConfiguration.java
|
SpecificationStringPropertiesCustomizerBeanPostProcessor
|
postProcessAfterInitialization
|
class SpecificationStringPropertiesCustomizerBeanPostProcessor implements BeanPostProcessor {
private final SpringDocConfigProperties springDocConfigProperties;
public SpecificationStringPropertiesCustomizerBeanPostProcessor(
SpringDocConfigProperties springDocConfigProperties
) {
this.springDocConfigProperties = springDocConfigProperties;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof GroupedOpenApi groupedOpenApi) {
Set<GroupConfig> groupConfigs = springDocConfigProperties.getGroupConfigs();
for (GroupConfig groupConfig : groupConfigs) {
if(groupConfig.getGroup().equals(groupedOpenApi.getGroup())) {
groupedOpenApi.addAllOpenApiCustomizer(List.of(new SpecPropertiesCustomizer(
groupConfig.getOpenApi()
)));
}
}
}
return bean;
| 116
| 128
| 244
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocUIConfiguration.java
|
SpringDocUIConfiguration
|
afterPropertiesSet
|
class SpringDocUIConfiguration implements InitializingBean {
/**
* The constant SPRINGDOC_CONFIG_PROPERTIES.
*/
public static final String SPRINGDOC_CONFIG_PROPERTIES = "springdoc.config.properties";
/**
* The constant SPRINGDOC_SWAGGERUI_VERSION.
*/
private static final String SPRINGDOC_SWAGGERUI_VERSION = "springdoc.swagger-ui.version";
/**
* The Swagger ui config properties.
*/
private final Optional<SwaggerUiConfigProperties> optionalSwaggerUiConfigProperties;
/**
* Instantiates a new Spring doc hints.
*
* @param optionalSwaggerUiConfigProperties the swagger ui config properties
*/
public SpringDocUIConfiguration(Optional<SwaggerUiConfigProperties> optionalSwaggerUiConfigProperties) {
this.optionalSwaggerUiConfigProperties = optionalSwaggerUiConfigProperties;
}
@Override
public void afterPropertiesSet() {<FILL_FUNCTION_BODY>}
}
|
optionalSwaggerUiConfigProperties.ifPresent(swaggerUiConfigProperties -> {
if (StringUtils.isEmpty(swaggerUiConfigProperties.getVersion())) {
try {
Resource resource = new ClassPathResource(AntPathMatcher.DEFAULT_PATH_SEPARATOR + SPRINGDOC_CONFIG_PROPERTIES);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
swaggerUiConfigProperties.setVersion(props.getProperty(SPRINGDOC_SWAGGERUI_VERSION));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
| 260
| 164
| 424
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/hints/SpringDocDataRestHints.java
|
SpringDocDataRestHints
|
registerHints
|
class SpringDocDataRestHints implements RuntimeHintsRegistrar {
//spring-data-rest
static String[] springDataRestTypeNames = { "org.springframework.data.rest.webmvc.config.DelegatingHandlerMapping",
"org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping",
"org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController",
"org.springframework.data.rest.webmvc.RepositorySearchController",
"org.springframework.data.rest.webmvc.RepositorySchemaController",
"org.springframework.data.rest.webmvc.RepositoryEntityController",
"org.springdoc.webflux.core.fn.SpringdocRouteBuilder",
"org.springdoc.webflux.core.visitor.RouterFunctionVisitor"
};
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
//springdoc
hints.reflection().registerField(
FieldUtils.getField(TypedResourceDescription.class, "type", true));
hints.reflection().registerField(
FieldUtils.getDeclaredField(DelegatingMethodParameter.class, "additionalParameterAnnotations", true));
//spring-data-rest
Arrays.stream(springDataRestTypeNames).forEach(springDataRestTypeName ->
hints.reflection()
.registerTypeIfPresent(classLoader, springDataRestTypeName,
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS
))
);
| 241
| 208
| 449
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/hints/SpringDocHints.java
|
SpringDocHints
|
registerHints
|
class SpringDocHints implements RuntimeHintsRegistrar {
static Class[] typesToRegister = {
//swagger-models
io.swagger.v3.oas.models.security.SecurityScheme.Type.class,
io.swagger.v3.oas.models.security.SecurityScheme.In.class,
io.swagger.v3.oas.models.media.Encoding.class,
io.swagger.v3.oas.models.info.Contact.class,
io.swagger.v3.oas.models.info.License.class,
io.swagger.v3.oas.models.security.OAuthFlow.class, io.swagger.v3.oas.models.security.OAuthFlows.class,
io.swagger.v3.oas.models.security.SecurityScheme.class,
io.swagger.v3.oas.models.tags.Tag.class,
io.swagger.v3.oas.models.servers.ServerVariable.class,
io.swagger.v3.oas.models.servers.Server.class,
io.swagger.v3.oas.models.security.SecurityRequirement.class,
io.swagger.v3.oas.models.info.Info.class,
io.swagger.v3.oas.models.parameters.RequestBody.class,
io.swagger.v3.oas.models.media.Schema.class,
io.swagger.v3.oas.models.media.Content.class,
io.swagger.v3.oas.models.media.ArraySchema.class,
io.swagger.v3.oas.models.responses.ApiResponse.class,
io.swagger.v3.oas.models.responses.ApiResponses.class,
io.swagger.v3.oas.models.ExternalDocumentation.class,
io.swagger.v3.oas.models.links.LinkParameter.class,
io.swagger.v3.oas.models.links.Link.class,
io.swagger.v3.oas.models.parameters.Parameter.class,
io.swagger.v3.oas.models.Operation.class,
io.swagger.v3.oas.models.headers.Header.class,
ModelConverter.class,
ModelConverters.class,
SpecFilter.class,
MediaType.class,
ApiResponsesSerializer.class,
PathsSerializer.class,
ComponentsMixin.class,
ExtensionsMixin.class,
OpenAPIMixin.class,
OperationMixin.class,
SchemaMixin.class,
Schema31Mixin.class,
Components31Mixin.class,
OpenAPI31Mixin.class,
Discriminator31Mixin.class,
Paths.class,
XML.class,
UUIDSchema.class,
PathItem.class,
ServerVariables.class,
OpenAPI.class,
Components.class,
StringSchema.class,
DateTimeSchema.class,
Discriminator.class,
BooleanSchema.class,
FileSchema.class,
IntegerSchema.class,
MapSchema.class,
ObjectSchema.class,
Scopes.class,
DateSchema.class,
ComposedSchema.class,
BinarySchema.class,
ByteArraySchema.class,
EmailSchema.class,
Example.class,
EncodingProperty.class,
NumberSchema.class,
PasswordSchema.class,
CookieParameter.class,
HeaderParameter.class,
PathParameter.class,
QueryParameter.class,
DateSchemaMixin.class,
ExampleMixin.class,
MediaTypeMixin.class,
//springdoc classes
org.springdoc.core.annotations.ParameterObject.class,
org.springdoc.core.converters.models.Pageable.class,
org.springdoc.core.extractor.DelegatingMethodParameter.class,
// spring
org.springframework.core.MethodParameter.class
};
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
hints.proxies()
.registerJdkProxy(org.springframework.web.context.request.NativeWebRequest.class);
hints.reflection()
.registerType(java.lang.Module.class,
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS))
.registerType(java.lang.ModuleLayer.class, MemberCategory.INVOKE_DECLARED_METHODS)
.registerType(java.lang.module.Configuration.class, MemberCategory.INVOKE_DECLARED_METHODS)
.registerType(java.lang.module.ResolvedModule.class, MemberCategory.INVOKE_DECLARED_METHODS);
//swagger-models
Arrays.stream(typesToRegister).forEach(aClass ->
hints.reflection().registerType(aClass,
hint -> hint.withMembers(
MemberCategory.DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS
)));
//springdoc
hints.reflection().registerField(FieldUtils.getDeclaredField(io.swagger.v3.core.converter.ModelConverters.class, "converters", true));
hints.reflection().registerType(org.springdoc.core.utils.Constants.class, hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS));
hints.resources().registerPattern(SpringDocUIConfiguration.SPRINGDOC_CONFIG_PROPERTIES)
.registerResourceBundle("sun.util.resources.LocaleNames");
| 1,142
| 460
| 1,602
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/hints/SpringDocSecurityHints.java
|
SpringDocSecurityHints
|
registerHints
|
class SpringDocSecurityHints implements RuntimeHintsRegistrar {
//spring-security
static String[] springSecurityTypeNames = { "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
"org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter",
"org.springframework.security.web.util.matcher.OrRequestMatcher"
};
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
//spring-security
Arrays.stream(springSecurityTypeNames).forEach(springDataRestTypeName ->
hints.reflection()
.registerTypeIfPresent(classLoader, springDataRestTypeName,
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS
))
);
| 133
| 126
| 259
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configurer/SpringdocActuatorBeanFactoryConfigurer.java
|
SpringdocActuatorBeanFactoryConfigurer
|
postProcessBeanFactory
|
class SpringdocActuatorBeanFactoryConfigurer extends SpringdocBeanFactoryConfigurer {
/**
* The Grouped open apis.
*/
private final List<GroupedOpenApi> groupedOpenApis;
/**
* Instantiates a new Springdoc actuator bean factory configurer.
*
* @param groupedOpenApis the grouped open apis
*/
public SpringdocActuatorBeanFactoryConfigurer(List<GroupedOpenApi> groupedOpenApis) {
this.groupedOpenApis = groupedOpenApis;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
}
|
final BindResult<WebEndpointProperties> result = Binder.get(environment)
.bind(MANAGEMENT_ENDPOINTS_WEB, WebEndpointProperties.class);
final BindResult<SpringDocConfigProperties> springDocConfigPropertiesBindResult = Binder.get(environment)
.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
if (result.isBound() && springDocConfigPropertiesBindResult.isBound()) {
WebEndpointProperties webEndpointProperties = result.get();
SpringDocConfigProperties springDocConfigProperties = springDocConfigPropertiesBindResult.get();
List<GroupedOpenApi> newGroups = new ArrayList<>();
ActuatorOpenApiCustomizer actuatorOpenApiCustomizer = new ActuatorOpenApiCustomizer(webEndpointProperties);
beanFactory.registerSingleton("actuatorOpenApiCustomizer", actuatorOpenApiCustomizer);
ActuatorOperationCustomizer actuatorCustomizer = new ActuatorOperationCustomizer(springDocConfigProperties);
beanFactory.registerSingleton("actuatorCustomizer", actuatorCustomizer);
GroupedOpenApi actuatorGroup = GroupedOpenApi.builder().group(ACTUATOR_DEFAULT_GROUP)
.pathsToMatch(webEndpointProperties.getBasePath() + ALL_PATTERN)
.pathsToExclude(webEndpointProperties.getBasePath() + HEALTH_PATTERN)
.build();
// Add the actuator group
newGroups.add(actuatorGroup);
if (CollectionUtils.isEmpty(groupedOpenApis)) {
GroupedOpenApi defaultGroup = GroupedOpenApi.builder().group(DEFAULT_GROUP_NAME)
.pathsToMatch(ALL_PATTERN)
.pathsToExclude(webEndpointProperties.getBasePath() + ALL_PATTERN)
.build();
// Register the default group
newGroups.add(defaultGroup);
}
newGroups.forEach(elt -> beanFactory.registerSingleton(elt.getGroup(), elt));
}
initBeanFactoryPostProcessor(beanFactory);
| 178
| 525
| 703
|
<methods>public non-sealed void <init>() ,public static void initBeanFactoryPostProcessor(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) ,public void postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) ,public void setEnvironment(org.springframework.core.env.Environment) <variables>protected org.springframework.core.env.Environment environment
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configurer/SpringdocBeanFactoryConfigurer.java
|
SpringdocBeanFactoryConfigurer
|
postProcessBeanFactory
|
class SpringdocBeanFactoryConfigurer implements EnvironmentAware, BeanFactoryPostProcessor {
/**
* The Environment.
*/
@Nullable
protected Environment environment;
/**
* Init bean factory post processor.
*
* @param beanFactory the bean factory
*/
public static void initBeanFactoryPostProcessor(ConfigurableListableBeanFactory beanFactory) {
for (String beanName : beanFactory.getBeanNamesForType(OpenAPIService.class, true, false))
beanFactory.getBeanDefinition(beanName).setScope(SCOPE_PROTOTYPE);
for (String beanName : beanFactory.getBeanNamesForType(OpenAPI.class, true, false))
beanFactory.getBeanDefinition(beanName).setScope(SCOPE_PROTOTYPE);
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
}
|
final BindResult<SpringDocConfigProperties> result = Binder.get(environment)
.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
if (result.isBound()) {
SpringDocConfigProperties springDocGroupConfig = result.get();
List<GroupedOpenApi> groupedOpenApis = springDocGroupConfig.getGroupConfigs().stream()
.map(elt -> {
GroupedOpenApi.Builder builder = GroupedOpenApi.builder();
if (!CollectionUtils.isEmpty(elt.getPackagesToScan()))
builder.packagesToScan(elt.getPackagesToScan().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getPathsToMatch()))
builder.pathsToMatch(elt.getPathsToMatch().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getProducesToMatch()))
builder.producesToMatch(elt.getProducesToMatch().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getConsumesToMatch()))
builder.consumesToMatch(elt.getConsumesToMatch().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getHeadersToMatch()))
builder.headersToMatch(elt.getHeadersToMatch().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getPathsToExclude()))
builder.pathsToExclude(elt.getPathsToExclude().toArray(new String[0]));
if (!CollectionUtils.isEmpty(elt.getPackagesToExclude()))
builder.packagesToExclude(elt.getPackagesToExclude().toArray(new String[0]));
if (StringUtils.isNotEmpty(elt.getDisplayName()))
builder.displayName(elt.getDisplayName());
if (Optional.ofNullable(elt.getOpenApi()).isPresent()) {
builder.addOpenApiCustomizer(new SpecPropertiesCustomizer(elt.getOpenApi()));
}
return builder.group(elt.getGroup()).build();
})
.toList();
groupedOpenApis.forEach(elt -> beanFactory.registerSingleton(elt.getGroup(), elt));
}
initBeanFactoryPostProcessor(beanFactory);
| 255
| 580
| 835
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/AdditionalModelsConverter.java
|
AdditionalModelsConverter
|
resolve
|
class AdditionalModelsConverter implements ModelConverter {
/**
* The constant modelToClassMap.
*/
private static final Map<Class, Class> modelToClassMap = new HashMap<>();
/**
* The constant modelToSchemaMap.
*/
private static final Map<Class, Schema> modelToSchemaMap = new HashMap<>();
/**
* The constant paramObjectReplacementMap.
*/
private static final Map<Class, Class> paramObjectReplacementMap = new HashMap<>();
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AdditionalModelsConverter.class);
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Additional models converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public AdditionalModelsConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
/**
* Replace with class.
*
* @param source the source
* @param target the target
*/
public static void replaceWithClass(Class source, Class target) {
modelToClassMap.put(source, target);
}
/**
* Replace with schema.
*
* @param source the source
* @param target the target
*/
public static void replaceWithSchema(Class source, Schema target) {
modelToSchemaMap.put(source, target);
}
/**
* Replace ParameterObject with class.
*
* @param source the source
* @param target the target
*/
public static void replaceParameterObjectWithClass(Class source, Class target) {
paramObjectReplacementMap.put(source, target);
}
/**
* Gets replacement.
*
* @param clazz the clazz
* @return the replacement
*/
public static Class getParameterObjectReplacement(Class clazz) {
return paramObjectReplacementMap.getOrDefault(clazz, clazz);
}
/**
* Disable replacement.
*
* @param clazz the clazz
*/
public static void disableReplacement(Class clazz) {
modelToClassMap.remove(clazz);
}
/**
* Resolve schema.
*
* @param type the type
* @param context the context
* @param chain the chain
* @return the schema
*/
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
/**
* Remove from schema map.
*
* @param clazz the clazz
*/
public static void removeFromSchemaMap(Class clazz) {
modelToSchemaMap.remove(clazz);
}
/**
* Remove from class map.
*
* @param clazz the clazz
*/
public static void removeFromClassMap(Class clazz) {
modelToClassMap.remove(clazz);
}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (modelToSchemaMap.containsKey(cls))
try {
return springDocObjectMapper.jsonMapper()
.readValue(springDocObjectMapper.jsonMapper().writeValueAsString(modelToSchemaMap.get(cls)), new TypeReference<Schema>() {});
}
catch (JsonProcessingException e) {
LOGGER.warn("Json Processing Exception occurred: {}", e.getMessage());
}
if (modelToClassMap.containsKey(cls))
type = new AnnotatedType(modelToClassMap.get(cls)).resolveAsRef(true);
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 774
| 228
| 1,002
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/CollectionModelContentConverter.java
|
CollectionModelContentConverter
|
resolve
|
class CollectionModelContentConverter implements ModelConverter {
/**
* The Link relation provider.
*/
private final LinkRelationProvider linkRelationProvider;
/**
* Instantiates a new Collection model content converter.
*
* @param linkRelationProvider the link relation provider
*/
public CollectionModelContentConverter(LinkRelationProvider linkRelationProvider) {
this.linkRelationProvider = linkRelationProvider;
}
@Override
public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
/**
* Gets entity type.
*
* @param type the type
* @return the entity type
*/
private Class<?> getEntityType(AnnotatedType type) {
Class<?> containerEntityType = ((CollectionType) (type.getType())).getContentType().getRawClass();
if (EntityModel.class.isAssignableFrom(containerEntityType)) {
TypeBindings typeBindings = ((CollectionType) type.getType()).getContentType().getBindings();
if (!CollectionUtils.isEmpty(typeBindings.getTypeParameters()))
return typeBindings.getBoundType(0).getRawClass();
}
return containerEntityType;
}
}
|
if (chain.hasNext() && type != null && type.getType() instanceof CollectionType
&& "_embedded".equalsIgnoreCase(type.getPropertyName())) {
Schema<?> schema = chain.next().resolve(type, context, chain);
if (schema instanceof ArraySchema) {
Class<?> entityType = getEntityType(type);
String entityClassName = linkRelationProvider.getCollectionResourceRelFor(entityType).value();
return new ObjectSchema()
.name("_embedded")
.addProperties(entityClassName, schema);
}
}
return chain.hasNext() ? chain.next().resolve(type, context, chain) : null;
| 324
| 173
| 497
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/FileSupportConverter.java
|
FileSupportConverter
|
resolve
|
class FileSupportConverter implements ModelConverter {
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new File support converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public FileSupportConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (isFile(cls))
return new FileSchema();
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 148
| 99
| 247
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/JavaTypeToIgnoreConverter.java
|
JavaTypeToIgnoreConverter
|
resolve
|
class JavaTypeToIgnoreConverter implements ModelConverter {
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Request type to ignore converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public JavaTypeToIgnoreConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
if (type.isSchemaProperty()) {
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
Class<?> cls = javaType.getRawClass();
if (ConverterUtils.isJavaTypeToIgnore(cls))
return null;
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 153
| 103
| 256
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/ModelConverterRegistrar.java
|
ModelConverterRegistrar
|
isSameConverter
|
class ModelConverterRegistrar {
/**
* The constant modelConvertersInstance.
*/
private final ModelConverters modelConvertersInstance;
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ModelConverterRegistrar.class);
/**
* Instantiates a new Model converter registrar.
*
* @param modelConverters spring registered model converter beans which have to be registered in {@link ModelConverters} instance
* @param springDocConfigProperties the spring doc config properties
*/
public ModelConverterRegistrar(List<ModelConverter> modelConverters, SpringDocConfigProperties springDocConfigProperties) {
modelConvertersInstance = ModelConverters.getInstance(springDocConfigProperties.isOpenapi31());
for (ModelConverter modelConverter : modelConverters) {
Optional<ModelConverter> registeredConverterOptional = getRegisteredConverterSameAs(modelConverter);
registeredConverterOptional.ifPresent(modelConvertersInstance::removeConverter);
modelConvertersInstance.addConverter(modelConverter);
}
}
/**
* Gets registered converter same as.
*
* @param modelConverter the model converter
* @return the registered converter same as
*/
@SuppressWarnings("unchecked")
private Optional<ModelConverter> getRegisteredConverterSameAs(ModelConverter modelConverter) {
try {
Field convertersField = FieldUtils.getDeclaredField(ModelConverters.class, "converters", true);
List<ModelConverter> modelConverters = (List<ModelConverter>) convertersField.get(modelConvertersInstance);
return modelConverters.stream()
.filter(registeredModelConverter -> isSameConverter(registeredModelConverter, modelConverter))
.findFirst();
}
catch (IllegalAccessException exception) {
LOGGER.warn(exception.getMessage());
}
return Optional.empty();
}
/**
* Is same converter boolean.
*
* @param modelConverter1 the model converter 1
* @param modelConverter2 the model converter 2
* @return the boolean
*/
private boolean isSameConverter(ModelConverter modelConverter1, ModelConverter modelConverter2) {<FILL_FUNCTION_BODY>}
}
|
// comparing by the converter type
Class<? extends ModelConverter> modelConverter1Class = modelConverter1.getClass();
Class<? extends ModelConverter> modelConverter2Class = modelConverter2.getClass();
return modelConverter1Class.equals(modelConverter2Class);
| 571
| 70
| 641
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/PageableOpenAPIConverter.java
|
PageableOpenAPIConverter
|
resolve
|
class PageableOpenAPIConverter implements ModelConverter {
/**
* The constant PAGEABLE_TO_REPLACE.
*/
private static final String PAGEABLE_TO_REPLACE = "org.springframework.data.domain.Pageable";
/**
* The constant PAGE_REQUEST_TO_REPLACE.
*/
private static final String PAGE_REQUEST_TO_REPLACE = "org.springframework.data.domain.PageRequest";
/**
* The constant PAGEABLE.
*/
private static final AnnotatedType PAGEABLE = new AnnotatedType(Pageable.class).resolveAsRef(true);
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Pageable open api converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public PageableOpenAPIConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
/**
* Resolve schema.
*
* @param type the type
* @param context the context
* @param chain the chain
* @return the schema
*/
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (PAGEABLE_TO_REPLACE.equals(cls.getCanonicalName()) || PAGE_REQUEST_TO_REPLACE.equals(cls.getCanonicalName())) {
if (!type.isSchemaProperty())
type = PAGEABLE;
else
type.name(cls.getSimpleName() + StringUtils.capitalize(type.getParent().getType()));
}
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 343
| 182
| 525
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/PolymorphicModelConverter.java
|
PolymorphicModelConverter
|
resolve
|
class PolymorphicModelConverter implements ModelConverter {
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Polymorphic model converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public PolymorphicModelConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
private static Schema<?> getResolvedSchema(JavaType javaType, Schema<?> resolvedSchema) {
if (resolvedSchema instanceof ObjectSchema && resolvedSchema.getProperties() != null) {
if (resolvedSchema.getProperties().containsKey(javaType.getRawClass().getName()))
resolvedSchema = resolvedSchema.getProperties().get(javaType.getRawClass().getName());
else if (resolvedSchema.getProperties().containsKey(javaType.getRawClass().getSimpleName()))
resolvedSchema = resolvedSchema.getProperties().get(javaType.getRawClass().getSimpleName());
}
return resolvedSchema;
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
/**
* Compose polymorphic schema.
*
* @param type the type
* @param schema the schema
* @param schemas the schemas
* @return the schema
*/
private Schema composePolymorphicSchema(AnnotatedType type, Schema schema, Collection<Schema> schemas) {
String ref = schema.get$ref();
List<Schema> composedSchemas = schemas.stream()
.filter(ComposedSchema.class::isInstance)
.map(ComposedSchema.class::cast)
.filter(s -> s.getAllOf() != null)
.filter(s -> s.getAllOf().stream().anyMatch(s2 -> ref.equals(s2.get$ref())))
.map(s -> new Schema().$ref(AnnotationsUtils.COMPONENTS_REF + s.getName()))
.toList();
if (composedSchemas.isEmpty()) return schema;
ComposedSchema result = new ComposedSchema();
if (isConcreteClass(type)) result.addOneOfItem(schema);
composedSchemas.forEach(result::addOneOfItem);
return result;
}
/**
* Is concrete class boolean.
*
* @param type the type
* @return the boolean
*/
private boolean isConcreteClass(AnnotatedType type) {
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
Class<?> clazz = javaType.getRawClass();
return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface();
}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
if (chain.hasNext()) {
Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
resolvedSchema = getResolvedSchema(javaType, resolvedSchema);
if (resolvedSchema == null || resolvedSchema.get$ref() == null)
return resolvedSchema;
return composePolymorphicSchema(type, resolvedSchema, context.getDefinedModels().values());
}
}
return null;
| 723
| 148
| 871
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/PropertyCustomizingConverter.java
|
PropertyCustomizingConverter
|
resolve
|
class PropertyCustomizingConverter implements ModelConverter {
/**
* The Property customizers.
*/
private final Optional<List<PropertyCustomizer>> propertyCustomizers;
/**
* Instantiates a new Property customizing converter.
*
* @param customizers the customizers
*/
public PropertyCustomizingConverter(Optional<List<PropertyCustomizer>> customizers) {
this.propertyCustomizers = customizers;
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
if (chain.hasNext()) {
Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
if (type.isSchemaProperty() && propertyCustomizers.isPresent()) {
List<PropertyCustomizer> propertyCustomizerList = propertyCustomizers.get();
for (PropertyCustomizer propertyCustomizer : propertyCustomizerList)
resolvedSchema = propertyCustomizer.customize(resolvedSchema, type);
}
return resolvedSchema;
}
return null;
| 147
| 125
| 272
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/ResponseSupportConverter.java
|
ResponseSupportConverter
|
resolve
|
class ResponseSupportConverter implements ModelConverter {
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Response support converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public ResponseSupportConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (isResponseTypeWrapper(cls) && !isFluxTypeWrapper(cls)) {
JavaType innerType = javaType.getBindings().getBoundType(0);
if (innerType == null)
return new StringSchema();
return context.resolve(new AnnotatedType(innerType)
.jsonViewAnnotation(type.getJsonViewAnnotation())
.ctxAnnotations((type.getCtxAnnotations()))
.resolveAsRef(true));
}
else if (isResponseTypeToIgnore(cls))
return null;
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 148
| 217
| 365
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/SchemaPropertyDeprecatingConverter.java
|
SchemaPropertyDeprecatingConverter
|
isDeprecated
|
class SchemaPropertyDeprecatingConverter implements ModelConverter {
/**
* The constant DEPRECATED_ANNOTATIONS.
*/
private static final List<Class<? extends Annotation>> DEPRECATED_ANNOTATIONS = Collections.synchronizedList(new ArrayList<>());
static {
DEPRECATED_ANNOTATIONS.add(Deprecated.class);
}
/**
* Contains deprecated annotation boolean.
*
* @param annotations the annotations
* @return the boolean
*/
public static boolean containsDeprecatedAnnotation(Annotation[] annotations) {
return annotations != null && Stream.of(annotations).map(Annotation::annotationType).anyMatch(DEPRECATED_ANNOTATIONS::contains);
}
/**
* Add deprecated type.
*
* @param cls the cls
*/
public static void addDeprecatedType(Class<? extends Annotation> cls) {
DEPRECATED_ANNOTATIONS.add(cls);
}
/**
* Is deprecated boolean.
*
* @param method the annotated element
* @return the boolean
*/
public static boolean isDeprecated(Method method) {<FILL_FUNCTION_BODY>}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
if (chain.hasNext()) {
Schema<?> resolvedSchema = chain.next().resolve(type, context, chain);
if (type.isSchemaProperty() && containsDeprecatedAnnotation(type.getCtxAnnotations()))
resolvedSchema.setDeprecated(true);
return resolvedSchema;
}
return null;
}
}
|
Class<?> declaringClass = method.getDeclaringClass();
boolean deprecatedMethod = DEPRECATED_ANNOTATIONS.stream().anyMatch(annoClass -> AnnotatedElementUtils.findMergedAnnotation(method, annoClass) != null);
boolean deprecatedClass = DEPRECATED_ANNOTATIONS.stream().anyMatch(annoClass -> AnnotatedElementUtils.findMergedAnnotation(declaringClass, annoClass) != null);
return deprecatedClass || deprecatedMethod;
| 427
| 134
| 561
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/SortOpenAPIConverter.java
|
SortOpenAPIConverter
|
resolve
|
class SortOpenAPIConverter implements ModelConverter {
private static final String SORT_TO_REPLACE = "org.springframework.data.domain.Sort";
/**
* The constant SORT.
*/
private static final AnnotatedType SORT = new AnnotatedType(Sort.class).resolveAsRef(true);
/**
* The Spring doc object mapper.
*/
private final ObjectMapperProvider springDocObjectMapper;
/**
* Instantiates a new Sort open api converter.
*
* @param springDocObjectMapper the spring doc object mapper
*/
public SortOpenAPIConverter(ObjectMapperProvider springDocObjectMapper) {
this.springDocObjectMapper = springDocObjectMapper;
}
/**
* Resolve schema.
*
* @param type the type
* @param context the context
* @param chain the chain
* @return the schema
*/
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (SORT_TO_REPLACE.equals(cls.getCanonicalName())) {
if (!type.isSchemaProperty())
type = SORT;
else
type.name(cls.getSimpleName() + StringUtils.capitalize(type.getParent().getType()));
}
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 265
| 159
| 424
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/WebFluxSupportConverter.java
|
WebFluxSupportConverter
|
resolve
|
class WebFluxSupportConverter implements ModelConverter {
/**
* The Object mapper provider.
*/
private final ObjectMapperProvider objectMapperProvider;
/**
* Instantiates a new Web flux support converter.
*
* @param objectMapperProvider the object mapper provider
*/
public WebFluxSupportConverter(ObjectMapperProvider objectMapperProvider) {
this.objectMapperProvider = objectMapperProvider;
getConfig().addResponseWrapperToIgnore(Publisher.class)
.addFluxWrapperToIgnore(Flux.class);
}
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {<FILL_FUNCTION_BODY>}
}
|
JavaType javaType = objectMapperProvider.jsonMapper().constructType(type.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (isFluxTypeWrapper(cls)) {
JavaType innerType = javaType.getBindings().getBoundType(0);
if (innerType == null)
return new StringSchema();
else if (innerType.getBindings() != null && isResponseTypeWrapper(innerType.getRawClass())) {
type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
return this.resolve(type, context, chain);
}
else {
ArrayType arrayType = ArrayType.construct(innerType, null);
type = new AnnotatedType(arrayType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
}
}
}
return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
| 177
| 267
| 444
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/models/Pageable.java
|
Pageable
|
setSort
|
class Pageable {
/**
* The Page.
*/
@Min(0)
@Parameter(description = "Zero-based page index (0..N)", schema = @Schema(type = "integer", defaultValue = "0"))
private Integer page;
/**
* The Size.
*/
@Min(1)
@Parameter(description = "The size of the page to be returned", schema = @Schema(type = "integer", defaultValue = "20"))
private Integer size;
/**
* The Sort.
*/
@Parameter(description = "Sorting criteria in the format: property,(asc|desc). "
+ "Default sort order is ascending. " + "Multiple sort criteria are supported."
, name = "sort"
, array = @ArraySchema(schema = @Schema(type = "string")))
private List<String> sort;
/**
* Instantiates a new Pageable.
*
* @param page the page
* @param size the size
* @param sort the sort
*/
public Pageable(int page, int size, List<String> sort) {
this.page = page;
this.size = size;
this.sort = sort;
}
/**
* Gets page.
*
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* Sets page.
*
* @param page the page
*/
public void setPage(Integer page) {
this.page = page;
}
/**
* Gets size.
*
* @return the size
*/
public Integer getSize() {
return size;
}
/**
* Sets size.
*
* @param size the size
*/
public void setSize(Integer size) {
this.size = size;
}
/**
* Gets sort.
*
* @return the sort
*/
public List<String> getSort() {
return sort;
}
/**
* Sets sort.
*
* @param sort the sort
*/
public void setSort(List<String> sort) {<FILL_FUNCTION_BODY>}
/**
* Add sort.
*
* @param sort the sort
*/
public void addSort(String sort) {
this.sort.add(sort);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pageable pageable = (Pageable) o;
return Objects.equals(page, pageable.page) &&
Objects.equals(size, pageable.size) &&
Objects.equals(sort, pageable.sort);
}
@Override
public int hashCode() {
return Objects.hash(page, size, sort);
}
@Override
public String toString() {
return "Pageable{" +
"page=" + page +
", size=" + size +
", sort=" + sort +
'}';
}
}
|
if (sort == null) {
this.sort.clear();
}
else {
this.sort = sort;
}
| 777
| 38
| 815
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/converters/models/Sort.java
|
Sort
|
equals
|
class Sort {
/**
* The Sort.
*/
@Parameter(description = "Sorting criteria in the format: property,(asc|desc). "
+ "Default sort order is ascending. " + "Multiple sort criteria are supported."
, name = "sort"
, array = @ArraySchema(schema = @Schema(type = "string")))
private List<String> sort;
/**
* Instantiates a new Sort.
*
* @param sort the sort
*/
public Sort(List<String> sort) {
this.sort = sort;
}
/**
* Gets sort.
*
* @return the sort
*/
public List<String> getSort() {
return sort;
}
/**
* Sets sort.
*
* @param sort the sort
*/
public void setSort(List<String> sort) {
if (sort == null) {
this.sort.clear();
}
else {
this.sort = sort;
}
}
/**
* Add sort.
*
* @param sort the sort
*/
public void addSort(String sort) {
this.sort.add(sort);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(sort);
}
@Override
public String toString() {
return "Sort{" +
"sort=" + sort +
'}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Sort sort = (Sort) o;
return Objects.equals(this.sort, sort.sort);
| 385
| 62
| 447
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/ActuatorOpenApiCustomizer.java
|
ActuatorOpenApiCustomizer
|
handleActuatorPathParam
|
class ActuatorOpenApiCustomizer implements GlobalOpenApiCustomizer {
/**
* The Path pathern.
*/
private final Pattern pathPathern = Pattern.compile("\\{(.*?)}");
/**
* The Web endpoint properties.
*/
private final WebEndpointProperties webEndpointProperties;
/**
* Instantiates a new Actuator open api customizer.
*
* @param webEndpointProperties the web endpoint properties
*/
public ActuatorOpenApiCustomizer(WebEndpointProperties webEndpointProperties) {
this.webEndpointProperties = webEndpointProperties;
}
private Stream<Entry<String, PathItem>> actuatorPathEntryStream(OpenAPI openApi, String relativeSubPath) {
String pathPrefix = webEndpointProperties.getBasePath() + Optional.ofNullable(relativeSubPath).orElse("");
return Optional.ofNullable(openApi.getPaths())
.map(Paths::entrySet)
.map(Set::stream)
.map(s -> s.filter(entry -> entry.getKey().startsWith(pathPrefix)))
.orElse(Stream.empty());
}
private void handleActuatorPathParam(OpenAPI openApi) {<FILL_FUNCTION_BODY>}
private void handleActuatorOperationIdUniqueness(OpenAPI openApi) {
Set<String> usedOperationIds = new HashSet<>();
actuatorPathEntryStream(openApi, null)
.sorted(Comparator.comparing(Entry::getKey))
.forEachOrdered(stringPathItemEntry -> {
stringPathItemEntry.getValue().readOperations().forEach(operation -> {
String initialOperationId = operation.getOperationId();
String uniqueOperationId = operation.getOperationId();
int counter = 1;
while (!usedOperationIds.add(uniqueOperationId)) {
uniqueOperationId = initialOperationId + "_" + ++counter;
}
operation.setOperationId(uniqueOperationId);
});
});
}
@Override
public void customise(OpenAPI openApi) {
handleActuatorPathParam(openApi);
handleActuatorOperationIdUniqueness(openApi);
}
}
|
actuatorPathEntryStream(openApi, DEFAULT_PATH_SEPARATOR).forEach(stringPathItemEntry -> {
String path = stringPathItemEntry.getKey();
Matcher matcher = pathPathern.matcher(path);
while (matcher.find()) {
String pathParam = matcher.group(1);
PathItem pathItem = stringPathItemEntry.getValue();
pathItem.readOperations().forEach(operation -> {
List<Parameter> existingParameters = operation.getParameters();
Optional<Parameter> existingParam = Optional.empty();
if (!CollectionUtils.isEmpty(existingParameters))
existingParam = existingParameters.stream().filter(p -> pathParam.equals(p.getName())).findAny();
if (!existingParam.isPresent())
operation.addParametersItem(new PathParameter().name(pathParam).schema(new StringSchema()));
});
}
});
| 549
| 235
| 784
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/ActuatorOperationCustomizer.java
|
ActuatorOperationCustomizer
|
customize
|
class ActuatorOperationCustomizer implements GlobalOperationCustomizer {
/**
* The constant OPERATION.
*/
private static final String OPERATION = "operation";
/**
* The constant PARAMETER.
*/
private static final String PARAMETER = "parameter";
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ActuatorOperationCustomizer.class);
/**
* The regex pattern for operationId lookup.
*/
private static final Pattern pattern = Pattern.compile(".*'([^']*)'.*");
/**
* The Spring doc config properties.
*/
private final SpringDocConfigProperties springDocConfigProperties;
/**
* Instantiates a new Actuator operation customizer.
*
* @param springDocConfigProperties the spring doc config properties
*/
public ActuatorOperationCustomizer(SpringDocConfigProperties springDocConfigProperties) {
this.springDocConfigProperties = springDocConfigProperties;
}
@Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {<FILL_FUNCTION_BODY>}
}
|
if (operation.getTags() != null && operation.getTags().contains(getTag().getName())) {
Field operationFiled = FieldUtils.getDeclaredField(handlerMethod.getBean().getClass(), OPERATION, true);
Object actuatorOperation;
if (operationFiled != null) {
try {
actuatorOperation = operationFiled.get(handlerMethod.getBean());
Field actuatorOperationFiled = FieldUtils.getDeclaredField(actuatorOperation.getClass(), OPERATION, true);
if (actuatorOperationFiled != null) {
AbstractDiscoveredOperation discoveredOperation = (AbstractDiscoveredOperation) actuatorOperationFiled.get(actuatorOperation);
OperationMethod operationMethod = discoveredOperation.getOperationMethod();
if (OperationType.WRITE.equals(operationMethod.getOperationType())) {
for (OperationParameter operationParameter : operationMethod.getParameters()) {
Field parameterField = FieldUtils.getDeclaredField(operationParameter.getClass(), PARAMETER, true);
Parameter parameter = (Parameter) parameterField.get(operationParameter);
Schema<?> schema = AnnotationsUtils.resolveSchemaFromType(parameter.getType(), null, null, springDocConfigProperties.isOpenapi31());
if (parameter.getAnnotation(Selector.class) == null) {
operation.setRequestBody(new RequestBody()
.content(new Content().addMediaType(org.springframework.http.MediaType.APPLICATION_JSON_VALUE, new MediaType().schema(schema))));
}
}
}
}
}
catch (IllegalAccessException e) {
LOGGER.warn(e.getMessage());
}
}
String summary = handlerMethod.toString();
Matcher matcher = pattern.matcher(summary);
String operationId = operation.getOperationId();
while (matcher.find()) {
operationId = matcher.group(1);
}
if (operation.getSummary() == null && !summary.contains("$"))
operation.setSummary(summary);
operation.setOperationId(operationId);
}
return operation;
| 283
| 543
| 826
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/OpenApiHateoasLinksCustomizer.java
|
OpenApiHateoasLinksCustomizer
|
customise
|
class OpenApiHateoasLinksCustomizer extends SpecFilter implements GlobalOpenApiCustomizer {
/**
* The Spring doc config properties.
*/
private final SpringDocConfigProperties springDocConfigProperties;
/**
* Instantiates a new Open api hateoas links customiser.
*
* @param springDocConfigProperties the spring doc config properties
*/
public OpenApiHateoasLinksCustomizer(SpringDocConfigProperties springDocConfigProperties) {
this.springDocConfigProperties = springDocConfigProperties;
}
@Override
public void customise(OpenAPI openApi) {<FILL_FUNCTION_BODY>}
}
|
ResolvedSchema resolvedLinkSchema = ModelConverters.getInstance(springDocConfigProperties.isOpenapi31())
.resolveAsResolvedSchema(new AnnotatedType(Link.class));
openApi
.schema("Link", resolvedLinkSchema.schema)
.schema("Links", new MapSchema()
.additionalProperties(new StringSchema())
.additionalProperties(new ObjectSchema().$ref(AnnotationsUtils.COMPONENTS_REF + "Link")));
if (springDocConfigProperties.isRemoveBrokenReferenceDefinitions())
this.removeBrokenReferenceDefinitions(openApi);
| 159
| 152
| 311
|
<methods>public void <init>() ,public io.swagger.v3.oas.models.OpenAPI filter(io.swagger.v3.oas.models.OpenAPI, io.swagger.v3.core.filter.OpenAPISpecFilter, Map<java.lang.String,List<java.lang.String>>, Map<java.lang.String,java.lang.String>, Map<java.lang.String,List<java.lang.String>>) <variables>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/SpecPropertiesCustomizer.java
|
SpecPropertiesCustomizer
|
customizePaths
|
class SpecPropertiesCustomizer implements GlobalOpenApiCustomizer {
/**
* The Open api properties.
*/
private final OpenAPI openApiProperties;
/**
* Instantiates a new Spec properties customizer.
*
* @param springDocConfigProperties the spring doc config properties
*/
public SpecPropertiesCustomizer(SpringDocConfigProperties springDocConfigProperties) {
this.openApiProperties = springDocConfigProperties.getOpenApi();
}
/**
* Instantiates a new Spec properties customizer.
*
* @param openApiProperties the open api properties
*/
public SpecPropertiesCustomizer(OpenAPI openApiProperties) {
this.openApiProperties = openApiProperties;
}
@Override
public void customise(OpenAPI openApi) {
customizeOpenApi(openApi, openApiProperties);
}
/**
* Customize open api.
*
* @param openApi the open api
* @param openApiProperties the open api properties
*/
private void customizeOpenApi(OpenAPI openApi, OpenAPI openApiProperties) {
if (openApiProperties != null) {
Info infoProperties = openApiProperties.getInfo();
if (infoProperties != null)
customizeInfo(openApi, infoProperties);
Components componentsProperties = openApiProperties.getComponents();
if (componentsProperties != null)
customizeComponents(openApi, componentsProperties);
Paths pathsProperties = openApiProperties.getPaths();
if (pathsProperties != null)
customizePaths(openApi, pathsProperties);
}
}
/**
* Customize paths.
*
* @param openApi the open api
* @param pathsProperties the paths properties
*/
private void customizePaths(OpenAPI openApi, Paths pathsProperties) {<FILL_FUNCTION_BODY>}
/**
* Customize components.
*
* @param openApi the open api
* @param componentsProperties the components properties
*/
private void customizeComponents(OpenAPI openApi, Components componentsProperties) {
Components components = openApi.getComponents();
if (components == null || CollectionUtils.isEmpty(components.getSchemas())) {
openApi.components(componentsProperties);
}
else {
Map<String, Schema> schemaMap = components.getSchemas();
schemaMap.forEach((key, schema) -> {
Schema schemaProperties = componentsProperties.getSchemas().get(key);
if (schemaProperties != null) {
resolveString(schema::setDescription, schemaProperties::getDescription);
Map<String, Schema> properties = schema.getProperties();
if (CollectionUtils.isEmpty(properties)) {
return;
}
properties.forEach((propKey, propSchema) -> {
Schema propSchemaProperties = (Schema) schemaProperties.getProperties().get(propKey);
if (propSchemaProperties != null) {
resolveString(propSchema::description, propSchemaProperties::getDescription);
resolveString(propSchema::title, propSchemaProperties::getTitle);
resolveString(propSchema::example, propSchemaProperties::getExample);
}
});
}
});
}
}
/**
* Customize info.
*
* @param openApi the open api
* @param infoProperties the info properties
*/
private void customizeInfo(OpenAPI openApi, Info infoProperties) {
Info info = openApi.getInfo();
if (info != null) {
resolveString(info::title, infoProperties::getTitle);
resolveString(info::description, infoProperties::getDescription);
resolveString(info::version, infoProperties::getVersion);
resolveString(info::termsOfService, infoProperties::getTermsOfService);
resolveString(info::summary, infoProperties::getSummary);
License license = info.getLicense();
License licenseProperties = infoProperties.getLicense();
if (license != null) {
resolveString(license::name, licenseProperties::getName);
resolveString(license::url, licenseProperties::getUrl);
}
else
info.license(licenseProperties);
Contact contact = info.getContact();
Contact contactProperties = infoProperties.getContact();
if (contact != null) {
resolveString(contact::name, contactProperties::getName);
resolveString(contact::email, contactProperties::getEmail);
resolveString(contact::url, contactProperties::getUrl);
}
else
info.contact(contactProperties);
}
else
openApi.info(infoProperties);
}
/**
* Resolve string.
*
* @param setter the setter
* @param getter the value
*/
private void resolveString(Consumer<String> setter, Supplier<Object> getter) {
String value = (String) getter.get();
if (StringUtils.isNotBlank(value)) {
setter.accept(value);
}
}
/**
* Resolve set.
*
* @param setter the setter
* @param getter the getter
*/
private void resolveSet(Consumer<List> setter, Supplier<List> getter) {
List value = getter.get();
if (!CollectionUtils.isEmpty(value)) {
setter.accept(value);
}
}
}
|
Paths paths = openApi.getPaths();
if (paths == null) {
openApi.paths(pathsProperties);
}
else {
paths.forEach((path, pathItem) -> {
if (path.startsWith("/")) {
path = path.substring(1); // Remove the leading '/'
}
PathItem pathItemProperties = pathsProperties.get(path);
if (pathItemProperties != null) {
resolveString(pathItem::description, pathItemProperties::getDescription);
resolveString(pathItem::summary, pathItemProperties::getSummary);
Map<HttpMethod, Operation> operationMap = pathItem.readOperationsMap();
Map<HttpMethod, Operation> operationMapProperties = pathItemProperties.readOperationsMap();
operationMapProperties.forEach((httpMethod, operationProperties) -> {
Operation operationToCustomize = operationMap.get(httpMethod);
if (operationToCustomize != null) {
resolveString(operationToCustomize::description, operationProperties::getDescription);
resolveString(operationToCustomize::summary, operationProperties::getSummary);
resolveSet(operationToCustomize::tags, operationProperties::getTags);
}
});
}});
}
| 1,373
| 321
| 1,694
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/SpringDocCustomizers.java
|
SpringDocCustomizers
|
afterPropertiesSet
|
class SpringDocCustomizers implements ApplicationContextAware, InitializingBean {
/**
* The Open api customisers.
*/
private final Optional<List<OpenApiCustomizer>> openApiCustomizers;
/**
* The Operation customizers.
*/
private final Optional<List<OperationCustomizer>> operationCustomizers;
/**
* The RouterOperation customizers.
*/
private final Optional<List<RouterOperationCustomizer>> routerOperationCustomizers;
/**
* The Data rest router operation customizers.
*/
private final Optional<List<DataRestRouterOperationCustomizer>> dataRestRouterOperationCustomizers;
/**
* The Context.
*/
private ApplicationContext context;
/**
* The method filters to use.
*/
private final Optional<List<OpenApiMethodFilter>> methodFilters;
/**
* The Global open api customizers.
*/
private Optional<List<GlobalOpenApiCustomizer>> globalOpenApiCustomizers;
/**
* The Global operation customizers.
*/
private Optional<List<GlobalOperationCustomizer>> globalOperationCustomizers;
/**
* The Global open api method filters.
*/
private Optional<List<GlobalOpenApiMethodFilter>> globalOpenApiMethodFilters;
/**
* Instantiates a new Spring doc customizers.
*
* @param openApiCustomizers the open api customizers
* @param operationCustomizers the operation customizers
* @param routerOperationCustomizers the router operation customizers
* @param dataRestRouterOperationCustomizers the data rest router operation customizers
* @param methodFilters the method filters
* @param globalOpenApiCustomizers the global open api customizers
* @param globalOperationCustomizers the global operation customizers
* @param globalOpenApiMethodFilters the global open api method filters
*/
public SpringDocCustomizers(Optional<List<OpenApiCustomizer>> openApiCustomizers,
Optional<List<OperationCustomizer>> operationCustomizers,
Optional<List<RouterOperationCustomizer>> routerOperationCustomizers,
Optional<List<DataRestRouterOperationCustomizer>> dataRestRouterOperationCustomizers,
Optional<List<OpenApiMethodFilter>> methodFilters,
Optional<List<GlobalOpenApiCustomizer>> globalOpenApiCustomizers, Optional<List<GlobalOperationCustomizer>> globalOperationCustomizers,
Optional<List<GlobalOpenApiMethodFilter>> globalOpenApiMethodFilters) {
this.openApiCustomizers = openApiCustomizers;
this.operationCustomizers = operationCustomizers;
this.globalOpenApiCustomizers = globalOpenApiCustomizers;
this.globalOperationCustomizers = globalOperationCustomizers;
this.globalOpenApiMethodFilters = globalOpenApiMethodFilters;
operationCustomizers.ifPresent(customizers -> customizers.removeIf(Objects::isNull));
this.routerOperationCustomizers = routerOperationCustomizers;
this.dataRestRouterOperationCustomizers = dataRestRouterOperationCustomizers;
this.methodFilters = methodFilters;
}
/**
* Instantiates a new Spring doc customizers.
*
* @param openApiCustomizers the open api customizers
* @param operationCustomizers the operation customizers
* @param routerOperationCustomizers the router operation customizers
* @param openApiMethodFilters the open api method filters
*/
public SpringDocCustomizers(Optional<List<OpenApiCustomizer>> openApiCustomizers, Optional<List<OperationCustomizer>> operationCustomizers,
Optional<List<RouterOperationCustomizer>> routerOperationCustomizers, Optional<List<OpenApiMethodFilter>> openApiMethodFilters) {
this.openApiCustomizers = openApiCustomizers;
this.operationCustomizers = operationCustomizers;
this.routerOperationCustomizers = routerOperationCustomizers;
this.methodFilters = openApiMethodFilters;
this.dataRestRouterOperationCustomizers = Optional.empty();
}
/**
* Gets open api customizers.
*
* @return the open api customizers
*/
public Optional<List<OpenApiCustomizer>> getOpenApiCustomizers() {
return openApiCustomizers;
}
/**
* Gets operation customizers.
*
* @return the operation customizers
*/
public Optional<List<OperationCustomizer>> getOperationCustomizers() {
return operationCustomizers;
}
/**
* Gets router operation customizers.
*
* @return the router operation customizers
*/
public Optional<List<RouterOperationCustomizer>> getRouterOperationCustomizers() {
return routerOperationCustomizers;
}
/**
* Gets data rest router operation customizers.
*
* @return the data rest router operation customizers
*/
public Optional<List<DataRestRouterOperationCustomizer>> getDataRestRouterOperationCustomizers() {
return dataRestRouterOperationCustomizers;
}
/**
* Gets method filters.
*
* @return the method filters
*/
public Optional<List<OpenApiMethodFilter>> getMethodFilters() {
return methodFilters;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
/**
* Gets global open api customizers.
*
* @return the global open api customizers
*/
public Optional<List<GlobalOpenApiCustomizer>> getGlobalOpenApiCustomizers() {
return globalOpenApiCustomizers;
}
/**
* Gets global operation customizers.
*
* @return the global operation customizers
*/
public Optional<List<GlobalOperationCustomizer>> getGlobalOperationCustomizers() {
return globalOperationCustomizers;
}
/**
* Gets global open api method filters.
*
* @return the global open api method filters
*/
public Optional<List<GlobalOpenApiMethodFilter>> getGlobalOpenApiMethodFilters() {
return globalOpenApiMethodFilters;
}
@Override
public void afterPropertiesSet() {<FILL_FUNCTION_BODY>}
}
|
//add the default customizers
Map<String, OpenApiCustomizer> existingOpenApiCustomizers = context.getBeansOfType(OpenApiCustomizer.class);
if (!CollectionUtils.isEmpty(existingOpenApiCustomizers) && existingOpenApiCustomizers.containsKey(LINKS_SCHEMA_CUSTOMISER))
this.openApiCustomizers.ifPresent(openApiCustomizersList -> openApiCustomizersList.add(existingOpenApiCustomizers.get(LINKS_SCHEMA_CUSTOMISER)));
| 1,474
| 132
| 1,606
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/data/DataRestRepository.java
|
DataRestRepository
|
getReturnType
|
class DataRestRepository {
/**
* The Domain type.
*/
private Class<?> domainType;
/**
* The Repository type.
*/
private Class<?> repositoryType;
/**
* The Relation name.
*/
private String relationName;
/**
* The Controller type.
*/
private ControllerType controllerType;
/**
* The Is collection like.
*/
private boolean isCollectionLike;
/**
* The Is map.
*/
private boolean isMap;
/**
* The Property type.
*/
private Class<?> propertyType;
/**
* The Persistent entity.
*/
private PersistentEntity persistentEntity;
/**
* The Locale.
*/
private Locale locale;
/**
* Instantiates a new Data rest repository.
*
* @param domainType the domain type
* @param repositoryType the repository type
* @param locale the locale
*/
public DataRestRepository(Class<?> domainType, Class<?> repositoryType, Locale locale) {
this.domainType = domainType;
this.repositoryType = repositoryType;
this.locale = locale;
}
/**
* Gets domain type.
*
* @return the domain type
*/
public Class<?> getDomainType() {
if (!ControllerType.GENERAL.equals(controllerType))
return domainType;
return null;
}
/**
* Sets domain type.
*
* @param domainType the domain type
*/
public void setDomainType(Class<?> domainType) {
this.domainType = domainType;
}
/**
* Gets repository type.
*
* @return the repository type
*/
public Class<?> getRepositoryType() {
return repositoryType;
}
/**
* Sets repository type.
*
* @param repositoryType the repository type
*/
public void setRepositoryType(Class<?> repositoryType) {
this.repositoryType = repositoryType;
}
/**
* Gets relation name.
*
* @return the relation name
*/
public String getRelationName() {
return relationName;
}
/**
* Sets relation name.
*
* @param relationName the relation name
*/
public void setRelationName(String relationName) {
this.relationName = relationName;
}
/**
* Gets controller type.
*
* @return the controller type
*/
public ControllerType getControllerType() {
return controllerType;
}
/**
* Sets controller type.
*
* @param controllerType the controller type
*/
public void setControllerType(ControllerType controllerType) {
this.controllerType = controllerType;
}
/**
* Is collection like boolean.
*
* @return the boolean
*/
public boolean isCollectionLike() {
return isCollectionLike;
}
/**
* Sets collection like.
*
* @param collectionLike the collection like
*/
public void setCollectionLike(boolean collectionLike) {
isCollectionLike = collectionLike;
}
/**
* Is map boolean.
*
* @return the boolean
*/
public boolean isMap() {
return isMap;
}
/**
* Sets map.
*
* @param map the map
*/
public void setMap(boolean map) {
isMap = map;
}
/**
* Gets property type.
*
* @return the property type
*/
public Class<?> getPropertyType() {
return propertyType;
}
/**
* Sets property type.
*
* @param propertyType the property type
*/
public void setPropertyType(Class<?> propertyType) {
this.propertyType = propertyType;
}
/**
* Gets persistent entity.
*
* @return the persistent entity
*/
public PersistentEntity getPersistentEntity() {
return persistentEntity;
}
/**
* Sets persistent entity.
*
* @param persistentEntity the persistent entity
*/
public void setPersistentEntity(PersistentEntity persistentEntity) {
this.persistentEntity = persistentEntity;
}
/**
* Gets locale.
*
* @return the locale
*/
public Locale getLocale() {
return locale;
}
/**
* Sets locale.
*
* @param locale the locale
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
* Gets return type.
*
* @return the return type
*/
public Class getReturnType() {<FILL_FUNCTION_BODY>}
}
|
Class returnedEntityType = domainType;
if (ControllerType.PROPERTY.equals(controllerType))
returnedEntityType = propertyType;
else if (ControllerType.GENERAL.equals(controllerType))
returnedEntityType = null;
return returnedEntityType;
| 1,189
| 75
| 1,264
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/data/DataRestTagsService.java
|
DataRestTagsService
|
buildTags
|
class DataRestTagsService {
/**
* The Open api builder.
*/
private final OpenAPIService openAPIService;
/**
* Instantiates a new Data rest tags builder.
*
* @param openAPIService the open api builder
*/
public DataRestTagsService(OpenAPIService openAPIService) {
this.openAPIService = openAPIService;
}
/**
* Build search tags.
*
* @param operation the operation
* @param handlerMethod the handler method
* @param dataRestRepository the repository data rest
* @param method the method
*/
public void buildSearchTags(Operation operation, HandlerMethod handlerMethod,
DataRestRepository dataRestRepository, Method method) {
buildTags(operation, handlerMethod, dataRestRepository, method);
}
/**
* Build entity tags.
*
* @param operation the operation
* @param handlerMethod the handler method
* @param dataRestRepository the repository data rest
*/
public void buildEntityTags(Operation operation, HandlerMethod handlerMethod,
DataRestRepository dataRestRepository) {
buildTags(operation, handlerMethod, dataRestRepository, null);
}
/**
* Build tags.
* @param operation the operation
* @param handlerMethod the handler method
* @param dataRestRepository the repository data rest
* @param method
*/
private void buildTags(Operation operation, HandlerMethod handlerMethod,
DataRestRepository dataRestRepository, Method method) {<FILL_FUNCTION_BODY>}
}
|
String tagName = handlerMethod.getBeanType().getSimpleName();
if (SpringRepositoryRestResourceProvider.REPOSITORY_SCHEMA_CONTROLLER.equals(handlerMethod.getBeanType().getName())
|| AlpsController.class.equals(handlerMethod.getBeanType())
|| ProfileController.class.equals(handlerMethod.getBeanType())) {
tagName = ProfileController.class.getSimpleName();
operation.addTagsItem(OpenAPIService.splitCamelCase(tagName));
}
else {
Class<?> domainType = dataRestRepository.getDomainType();
Set<Tag> tags = new HashSet<>();
Set<String> tagsStr = new HashSet<>();
Class<?> repositoryType = dataRestRepository.getRepositoryType();
openAPIService.buildTagsFromClass(repositoryType, tags, tagsStr, dataRestRepository.getLocale());
if (!CollectionUtils.isEmpty(tagsStr))
tagsStr.forEach(operation::addTagsItem);
else {
tagName = tagName.replace("Repository", domainType.getSimpleName());
operation.addTagsItem(OpenAPIService.splitCamelCase(tagName));
}
final SecurityService securityParser = openAPIService.getSecurityParser();
Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> allSecurityTags = securityParser.getSecurityRequirementsForClass(repositoryType);
if (method != null)
allSecurityTags = securityParser.getSecurityRequirementsForMethod(method, allSecurityTags);
if (!CollectionUtils.isEmpty(allSecurityTags))
securityParser.buildSecurityRequirement(allSecurityTags.toArray(new io.swagger.v3.oas.annotations.security.SecurityRequirement[0]), operation);
}
| 388
| 457
| 845
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/discoverer/SpringDocParameterNameDiscoverer.java
|
SpringDocParameterNameDiscoverer
|
getParameterNames
|
class SpringDocParameterNameDiscoverer extends DefaultParameterNameDiscoverer {
/**
* The Standard reflection parameter name discoverer.
*/
private final StandardReflectionParameterNameDiscoverer standardReflectionParameterNameDiscoverer = new StandardReflectionParameterNameDiscoverer();
@Override
@Nullable
public String[] getParameterNames(Method method) {<FILL_FUNCTION_BODY>}
}
|
String[] params = super.getParameterNames(method);
if(ArrayUtils.isEmpty(params) || Objects.requireNonNull(params).length!=method.getParameters().length)
params = standardReflectionParameterNameDiscoverer.getParameterNames(method);
return params;
| 99
| 73
| 172
|
<methods>public void <init>() <variables>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/extractor/DelegatingMethodParameter.java
|
DelegatingMethodParameter
|
customize
|
class DelegatingMethodParameter extends MethodParameter {
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(DelegatingMethodParameter.class);
/**
* The Delegate.
*/
private final MethodParameter delegate;
/**
* The Additional parameter annotations.
*/
private final Annotation[] additionalParameterAnnotations;
/**
* The Parameter name.
*/
private final String parameterName;
/**
* The Is parameter object.
*/
private final boolean isParameterObject;
/**
* The Is not required.
*/
private boolean isNotRequired;
/**
* Instantiates a new Delegating method parameter.
*
* @param delegate the delegate
* @param parameterName the parameter name
* @param additionalParameterAnnotations the additional parameter annotations
* @param isParameterObject the is parameter object
* @param isNotRequired the is required
*/
DelegatingMethodParameter(MethodParameter delegate, String parameterName, Annotation[] additionalParameterAnnotations, boolean isParameterObject, boolean isNotRequired) {
super(delegate);
this.delegate = delegate;
this.additionalParameterAnnotations = additionalParameterAnnotations;
this.parameterName = parameterName;
this.isParameterObject = isParameterObject;
this.isNotRequired = isNotRequired;
}
/**
* Customize method parameter [ ].
*
* @param pNames the p names
* @param parameters the parameters
* @param optionalDelegatingMethodParameterCustomizer the optional delegating method parameter customizer
* @param defaultFlatParamObject the default flat param object
* @return the method parameter [ ]
*/
public static MethodParameter[] customize(String[] pNames, MethodParameter[] parameters,
Optional<DelegatingMethodParameterCustomizer> optionalDelegatingMethodParameterCustomizer, boolean defaultFlatParamObject) {<FILL_FUNCTION_BODY>}
/**
* Return a variant of this {@code MethodParameter} which refers to the
* given containing class.
* @param methodParameter the method parameter
* @param containingClass a specific containing class (potentially a subclass of the declaring class, e.g. substituting a type variable) A copy of spring withContainingClass, to keep compatibility with older spring versions
* @return the method parameter
* @see #getParameterType() #getParameterType()
*/
public static MethodParameter changeContainingClass(MethodParameter methodParameter, @Nullable Class<?> containingClass) {
MethodParameter result = methodParameter.clone();
try {
Field containingClassField = FieldUtils.getDeclaredField(result.getClass(), "containingClass", true);
containingClassField.set(result, containingClass);
Field parameterTypeField = FieldUtils.getDeclaredField(result.getClass(), "parameterType", true);
parameterTypeField.set(result, null);
}
catch (IllegalAccessException e) {
LOGGER.warn(e.getMessage());
}
return result;
}
@Override
@NonNull
public Annotation[] getParameterAnnotations() {
return ArrayUtils.addAll(delegate.getParameterAnnotations(), additionalParameterAnnotations);
}
@Override
public String getParameterName() {
return parameterName;
}
@Override
public Method getMethod() {
return delegate.getMethod();
}
@Override
public Constructor<?> getConstructor() {
return delegate.getConstructor();
}
@Override
public Class<?> getDeclaringClass() {
return delegate.getDeclaringClass();
}
@Override
public Member getMember() {
return delegate.getMember();
}
@Override
public AnnotatedElement getAnnotatedElement() {
return delegate.getAnnotatedElement();
}
@Override
public Executable getExecutable() {
return delegate.getExecutable();
}
@Override
public MethodParameter withContainingClass(Class<?> containingClass) {
return delegate.withContainingClass(containingClass);
}
@Override
public Class<?> getContainingClass() {
return delegate.getContainingClass();
}
@Override
public Class<?> getParameterType() {
return delegate.getParameterType();
}
@Override
public Type getGenericParameterType() {
return delegate.getGenericParameterType();
}
@Override
public Class<?> getNestedParameterType() {
return delegate.getNestedParameterType();
}
@Override
public Type getNestedGenericParameterType() {
return delegate.getNestedGenericParameterType();
}
@Override
public void initParameterNameDiscovery(ParameterNameDiscoverer parameterNameDiscoverer) {
delegate.initParameterNameDiscovery(parameterNameDiscoverer);
}
/**
* Is not required boolean.
*
* @return the boolean
*/
public boolean isNotRequired() {
return isNotRequired;
}
/**
* Sets not required.
*
* @param notRequired the not required
*/
public void setNotRequired(boolean notRequired) {
isNotRequired = notRequired;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
DelegatingMethodParameter that = (DelegatingMethodParameter) o;
return Objects.equals(delegate, that.delegate) &&
Arrays.equals(additionalParameterAnnotations, that.additionalParameterAnnotations) &&
Objects.equals(parameterName, that.parameterName);
}
@Override
public int hashCode() {
int result = Objects.hash(super.hashCode(), delegate, parameterName);
result = 31 * result + Arrays.hashCode(additionalParameterAnnotations);
return result;
}
/**
* Is parameter object boolean.
*
* @return the boolean
*/
public boolean isParameterObject() {
return isParameterObject;
}
}
|
List<MethodParameter> explodedParameters = new ArrayList<>();
for (int i = 0; i < parameters.length; ++i) {
MethodParameter p = parameters[i];
Class<?> paramClass = AdditionalModelsConverter.getParameterObjectReplacement(p.getParameterType());
boolean hasFlatAnnotation = p.hasParameterAnnotation(ParameterObject.class) || AnnotatedElementUtils.isAnnotated(paramClass, ParameterObject.class);
boolean hasNotFlatAnnotation = Arrays.stream(p.getParameterAnnotations())
.anyMatch(annotation -> Arrays.asList(RequestBody.class, RequestPart.class).contains(annotation.annotationType()));
if (!MethodParameterPojoExtractor.isSimpleType(paramClass)
&& (hasFlatAnnotation || (defaultFlatParamObject && !hasNotFlatAnnotation && !AbstractRequestService.isRequestTypeToIgnore(paramClass)))) {
MethodParameterPojoExtractor.extractFrom(paramClass).forEach(methodParameter -> {
optionalDelegatingMethodParameterCustomizer.ifPresent(customizer -> customizer.customize(p, methodParameter));
explodedParameters.add(methodParameter);
});
}
else {
String name = pNames != null ? pNames[i] : p.getParameterName();
explodedParameters.add(new DelegatingMethodParameter(p, name, null, false, false));
}
}
return explodedParameters.toArray(new MethodParameter[0]);
| 1,525
| 375
| 1,900
|
<methods>public void <init>(org.springframework.core.MethodParameter) ,public void <init>(java.lang.reflect.Method, int) ,public void <init>(Constructor<?>, int) ,public void <init>(java.lang.reflect.Method, int, int) ,public void <init>(Constructor<?>, int, int) ,public org.springframework.core.MethodParameter clone() ,public void decreaseNestingLevel() ,public boolean equals(java.lang.Object) ,public static org.springframework.core.MethodParameter forExecutable(java.lang.reflect.Executable, int) ,public static org.springframework.core.MethodParameter forFieldAwareConstructor(Constructor<?>, int, java.lang.String) ,public static org.springframework.core.MethodParameter forMethodOrConstructor(java.lang.Object, int) ,public static org.springframework.core.MethodParameter forParameter(java.lang.reflect.Parameter) ,public java.lang.reflect.AnnotatedElement getAnnotatedElement() ,public Constructor<?> getConstructor() ,public Class<?> getContainingClass() ,public Class<?> getDeclaringClass() ,public java.lang.reflect.Executable getExecutable() ,public java.lang.reflect.Type getGenericParameterType() ,public java.lang.reflect.Member getMember() ,public java.lang.reflect.Method getMethod() ,public A getMethodAnnotation(Class<A>) ,public java.lang.annotation.Annotation[] getMethodAnnotations() ,public java.lang.reflect.Type getNestedGenericParameterType() ,public Class<?> getNestedParameterType() ,public int getNestingLevel() ,public java.lang.reflect.Parameter getParameter() ,public A getParameterAnnotation(Class<A>) ,public java.lang.annotation.Annotation[] getParameterAnnotations() ,public int getParameterIndex() ,public java.lang.String getParameterName() ,public Class<?> getParameterType() ,public java.lang.Integer getTypeIndexForCurrentLevel() ,public java.lang.Integer getTypeIndexForLevel(int) ,public boolean hasMethodAnnotation(Class<A>) ,public boolean hasParameterAnnotation(Class<A>) ,public boolean hasParameterAnnotations() ,public int hashCode() ,public void increaseNestingLevel() ,public void initParameterNameDiscovery(org.springframework.core.ParameterNameDiscoverer) ,public boolean isOptional() ,public org.springframework.core.MethodParameter nested() ,public org.springframework.core.MethodParameter nested(java.lang.Integer) ,public org.springframework.core.MethodParameter nestedIfOptional() ,public void setTypeIndexForCurrentLevel(int) ,public java.lang.String toString() ,public org.springframework.core.MethodParameter withContainingClass(Class<?>) ,public org.springframework.core.MethodParameter withTypeIndex(int) <variables>private static final java.lang.annotation.Annotation[] EMPTY_ANNOTATION_ARRAY,private volatile Class<?> containingClass,private final java.lang.reflect.Executable executable,private volatile java.lang.reflect.Type genericParameterType,private volatile org.springframework.core.MethodParameter nestedMethodParameter,private int nestingLevel,private volatile java.lang.reflect.Parameter parameter,private volatile java.lang.annotation.Annotation[] parameterAnnotations,private final int parameterIndex,volatile java.lang.String parameterName,private volatile org.springframework.core.ParameterNameDiscoverer parameterNameDiscoverer,private volatile Class<?> parameterType,Map<java.lang.Integer,java.lang.Integer> typeIndexesPerLevel
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/RouterFunctionData.java
|
RouterFunctionData
|
getRequestMethod
|
class RouterFunctionData {
/**
* The Path.
*/
private String path;
/**
* The Consumes.
*/
private List<String> consumes = new ArrayList<>();
/**
* The Produces.
*/
private List<String> produces = new ArrayList<>();
/**
* The Headers.
*/
private List<String> headers = new ArrayList<>();
/**
* The Params.
*/
private List<String> params = new ArrayList<>();
/**
* The Query params.
*/
private Map<String, String> queryParams = new LinkedHashMap<>();
/**
* The Methods.
*/
private RequestMethod[] methods;
/**
* The Attributes.
*/
private Map<String, Object> attributes = new LinkedHashMap<>();
/**
* Instantiates a new Router function data.
*/
public RouterFunctionData() {
}
/**
* Instantiates a new Router function data.
*
* @param nestedOrPath the nested or path
* @param functionData the function data
*/
public RouterFunctionData(String nestedOrPath, RouterFunctionData functionData) {
this.path = nestedOrPath + functionData.getPath();
this.consumes = Arrays.asList(functionData.getConsumes());
this.produces = Arrays.asList(functionData.getProduces());
this.headers = Arrays.asList(functionData.getHeaders());
this.params = Arrays.asList(functionData.getParams());
this.queryParams = functionData.getQueryParams();
this.methods = functionData.getMethods();
this.attributes = functionData.getAttributes();
}
/**
* Gets path.
*
* @return the path
*/
public String getPath() {
return path;
}
/**
* Sets path.
*
* @param path the path
*/
public void setPath(String path) {
this.path = path;
}
/**
* Gets query params.
*
* @return the query params
*/
public Map<String, String> getQueryParams() {
return queryParams;
}
/**
* Add query params.
*
* @param name the name
* @param value the value
*/
public void addQueryParams(String name, String value) {
this.queryParams.put(name, value);
}
/**
* Get headers string [ ].
*
* @return the string [ ]
*/
public String[] getHeaders() {
return headers.toArray(new String[headers.size()]);
}
/**
* Add headers.
*
* @param headers the headers
*/
public void addHeaders(String headers) {
if (StringUtils.isNotBlank(headers))
this.headers.add(headers);
}
/**
* Get methods request method [ ].
*
* @return the request method [ ]
*/
public RequestMethod[] getMethods() {
return methods;
}
/**
* Sets methods.
*
* @param methods the methods
*/
public void setMethods(Set<HttpMethod> methods) {
this.methods = getMethod(methods);
}
/**
* Get consumes string [ ].
*
* @return the string [ ]
*/
public String[] getConsumes() {
return consumes.toArray(new String[consumes.size()]);
}
/**
* Get params string [ ].
*
* @return the string [ ]
*/
public String[] getParams() {
return params.toArray(new String[params.size()]);
}
/**
* Add params.
*
* @param params the params
*/
public void addParams(String params) {
if (StringUtils.isNotBlank(params)) this.params.add(params);
}
/**
* Add consumes.
*
* @param consumes the consumes
*/
public void addConsumes(String consumes) {
if (StringUtils.isNotBlank(consumes))
this.consumes.add(consumes);
}
/**
* Add produces.
*
* @param produces the produces
*/
public void addProduces(String produces) {
if (StringUtils.isNotBlank(produces))
this.produces.add(produces);
}
/**
* Add produces.
*
* @param produces the produces
*/
public void addProduces(List<String> produces) {
this.produces.addAll(produces);
}
/**
* Add consumes.
*
* @param consumes the consumes
*/
public void addConsumes(List<String> consumes) {
this.consumes.addAll(consumes);
}
/**
* Get method request method [ ].
*
* @param methods the methods
* @return the request method [ ]
*/
private RequestMethod[] getMethod(Set<HttpMethod> methods) {
if (!CollectionUtils.isEmpty(methods)) {
return methods.stream().map(this::getRequestMethod).toArray(RequestMethod[]::new);
}
return ArrayUtils.toArray();
}
/**
* Get produces string [ ].
*
* @return the string [ ]
*/
public String[] getProduces() {
return produces.toArray(new String[produces.size()]);
}
/**
* Gets request method.
*
* @param httpMethod the http method
* @return the request method
*/
private RequestMethod getRequestMethod(HttpMethod httpMethod) {<FILL_FUNCTION_BODY>}
/**
* Gets attributes.
*
* @return the attributes
*/
public Map<String, Object> getAttributes() {
return attributes;
}
/**
* Add attributes.
*
* @param attributes the attributes
*/
public void addAttributes(Map<String, Object> attributes) {
this.attributes.putAll(attributes);
}
}
|
RequestMethod requestMethod = null;
switch (httpMethod.name()) {
case "GET" -> requestMethod = RequestMethod.GET;
case "POST" -> requestMethod = RequestMethod.POST;
case "PUT" -> requestMethod = RequestMethod.PUT;
case "DELETE" -> requestMethod = RequestMethod.DELETE;
case "PATCH" -> requestMethod = RequestMethod.PATCH;
case "HEAD" -> requestMethod = RequestMethod.HEAD;
case "OPTIONS" -> requestMethod = RequestMethod.OPTIONS;
case "TRACE" -> requestMethod = RequestMethod.TRACE;
default ->
throw new IllegalStateException("Unexpected value: " + httpMethod.name());
}
return requestMethod;
| 1,538
| 196
| 1,734
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/apiresponse/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The Use return type schema.
*/
boolean useReturnTypeSchema = false;
/**
* A short description of the response.
*
*/
private String description = "";
/**
* The HTTP response code, or 'default', for the supplied response. May only have 1 default entry.
*
*/
private String responseCode = "default";
/**
* An array of response headers. Allows additional information to be included with response.
*
*/
private Header[] headers = {};
/**
* An array of operation links that can be followed from the response.
*
*/
private Link[] links = {};
/**
* An array containing descriptions of potential response payloads, for different media types.
*
*/
private Content[] content = {};
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* A reference to a response defined in components responses.
*
* @since swagger -core 2.0.3
*/
private String ref = "";
/**
* Instantiates a new Api response builder.
*/
private Builder() {
}
/**
* Builder api response builder.
*
* @return the api response builder
*/
public static Builder responseBuilder() {
return new Builder();
}
/**
* Description api response builder.
*
* @param description the description
* @return the api response builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Response code api response builder.
*
* @param responseCode the response code
* @return the api response builder
*/
public Builder responseCode(String responseCode) {
this.responseCode = responseCode;
return this;
}
/**
* Header api response builder.
*
* @param headers the headers
* @return the api response builder
*/
public Builder header(org.springdoc.core.fn.builders.header.Builder headers) {
this.headers = ArrayUtils.add(this.headers, headers.build());
return this;
}
/**
* Link api response builder.
*
* @param linkBuilder the link builder
* @return the api response builder
*/
public Builder link(org.springdoc.core.fn.builders.link.Builder linkBuilder) {
this.links = ArrayUtils.add(this.links, linkBuilder.build());
return this;
}
/**
* Content api response builder.
*
* @param contentBuilder the content builder
* @return the api response builder
*/
public Builder content(org.springdoc.core.fn.builders.content.Builder contentBuilder) {
this.content = ArrayUtils.add(this.content, contentBuilder.build());
return this;
}
/**
* Implementation api response builder.
*
* @param clazz the clazz
* @return the api response builder
*/
public Builder implementation(Class clazz) {
this.content = ArrayUtils.add(this.content, org.springdoc.core.fn.builders.content.Builder.contentBuilder().schema(org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().implementation(clazz)).build());
return this;
}
/**
* Implementation array api response builder.
*
* @param clazz the clazz
* @return the api response builder
*/
public Builder implementationArray(Class clazz) {
this.content = ArrayUtils.add(this.content, org.springdoc.core.fn.builders.content.Builder.contentBuilder().array(org.springdoc.core.fn.builders.arrayschema.Builder.arraySchemaBuilder().schema(org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().implementation(clazz))).build());
return this;
}
/**
* Extension api response builder.
*
* @param extensionBuilder the extension builder
* @return the api response builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Ref api response builder.
*
* @param ref the ref
* @return the api response builder
*/
public Builder ref(String ref) {
this.ref = ref;
return this;
}
/**
* Build api response.
*
* @return the api response
*/
public ApiResponse build() {<FILL_FUNCTION_BODY>}
}
|
return new ApiResponse() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String description() {
return description;
}
@Override
public String responseCode() {
return responseCode;
}
@Override
public Header[] headers() {
return headers;
}
@Override
public Link[] links() {
return links;
}
@Override
public Content[] content() {
return content;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public String ref() {
return ref;
}
@Override
public boolean useReturnTypeSchema() {
return useReturnTypeSchema;
}
};
| 1,168
| 214
| 1,382
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/arrayschema/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The schema of the items in the array
*/
private Schema schema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* Allows to define the properties to be resolved into properties of the schema of type `array` (not the ones of the
* `items` of such schema which are defined in schema}.
*/
private Schema arraySchema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* sets the maximum number of items in an array. Ignored if value is Integer.MIN_VALUE.
*/
private int maxItems = Integer.MIN_VALUE;
/**
* sets the minimum number of items in an array. Ignored if value is Integer.MAX_VALUE.
*/
private int minItems = Integer.MAX_VALUE;
/**
* determines whether an array of items will be unique
*/
private boolean uniqueItems;
/**
* The list of optional extensions
*/
private Extension[] extensions = {};
/**
* The Contains.
*/
private Schema contains = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Max contain.
*/
private int maxContains= 0;
/**
* The Min contains.
*/
private int minContains= 0;
/**
* The Unevaluated items.
*/
private Schema unevaluatedItems= org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Prefix items.
*/
private Schema[] prefixItems = {};
/**
* Instantiates a new Array schema builder.
*/
private Builder() {
}
/**
* Builder array schema builder.
*
* @return the array schema builder
*/
public static Builder arraySchemaBuilder() {
return new Builder();
}
/**
* Schema array schema builder.
*
* @param schemaBuilder the schema builder
* @return the array schema builder
*/
public Builder schema(org.springdoc.core.fn.builders.schema.Builder schemaBuilder) {
this.schema = schemaBuilder.build();
return this;
}
/**
* Array schema array schema builder.
*
* @param schemaBuilder the schema builder
* @return the array schema builder
*/
public Builder arraySchema(org.springdoc.core.fn.builders.schema.Builder schemaBuilder) {
this.arraySchema = schemaBuilder.build();
return this;
}
/**
* Max items array schema builder.
*
* @param maxItems the max items
* @return the array schema builder
*/
public Builder maxItems(int maxItems) {
this.maxItems = maxItems;
return this;
}
/**
* Min items array schema builder.
*
* @param minItems the min items
* @return the array schema builder
*/
public Builder minItems(int minItems) {
this.minItems = minItems;
return this;
}
/**
* Unique items array schema builder.
*
* @param uniqueItems the unique items
* @return the array schema builder
*/
public Builder uniqueItems(boolean uniqueItems) {
this.uniqueItems = uniqueItems;
return this;
}
/**
* Extension array schema builder.
*
* @param extensionBuilder the extension builder
* @return the array schema builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build array schema.
*
* @return the array schema
*/
public ArraySchema build() {<FILL_FUNCTION_BODY>}
}
|
return new ArraySchema() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public Schema items() {
return null;
}
@Override
public Schema schema() {
return schema;
}
@Override
public Schema arraySchema() {
return arraySchema;
}
@Override
public int maxItems() {
return maxItems;
}
@Override
public int minItems() {
return minItems;
}
@Override
public boolean uniqueItems() {
return uniqueItems;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public Schema contains() {
return contains;
}
@Override
public int maxContains() {
return maxContains;
}
@Override
public int minContains() {
return minContains;
}
@Override
public Schema unevaluatedItems() {
return unevaluatedItems;
}
@Override
public Schema[] prefixItems() {
return prefixItems;
}
};
| 963
| 308
| 1,271
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/content/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The schema properties defined for schema provided in @Schema
*/
private final Schema additionalPropertiesSchema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Additional properties array schema.
*/
private final ArraySchema additionalPropertiesArraySchema = org.springdoc.core.fn.builders.arrayschema.Builder.arraySchemaBuilder().build();
/**
* The schema properties defined for schema provided in @Schema
*/
private final SchemaProperty[] schemaProperties = {};
/**
* The media type that this object applies to.
*/
private String mediaType = "";
/**
* An array of examples used to show the use of the associated schema.
*/
private ExampleObject[] examples = {};
/**
* The schema defining the type used for the content.
*/
private Schema schema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The schema of the array that defines the type used for the content.
*/
private ArraySchema array = org.springdoc.core.fn.builders.arrayschema.Builder.arraySchemaBuilder().build();
/**
* An array of encodings
* The key, being the property name, MUST exist in the schema as a property.
*/
private Encoding[] encodings = {};
/**
* The list of optional extensions
*/
private Extension[] extensions = {};
/**
* The Dependent schemas.
*/
private DependentSchema[] dependentSchemas = {};
/**
* The Content schem.
*/
private Schema contentSchema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Property names.
*/
private Schema propertyNames = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The If.
*/
private Schema _if = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Then.
*/
private Schema _then = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Else.
*/
private Schema _else = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The Not.
*/
private Schema not = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* The One of.
*/
private Schema[] oneOf = {};
/**
* The Any of.
*/
private Schema[] anyOf = {};
/**
* The All of.
*/
private Schema[] allOf ={};
/**
* Instantiates a new Content builder.
*/
private Builder() {
}
/**
* Builder content builder.
*
* @return the content builder
*/
public static Builder contentBuilder() {
return new Builder();
}
/**
* Media type content builder.
*
* @param mediaType the media type
* @return the content builder
*/
public Builder mediaType(String mediaType) {
this.mediaType = mediaType;
return this;
}
/**
* Example content builder.
*
* @param exampleObjectBuilder the example object builder
* @return the content builder
*/
public Builder example(org.springdoc.core.fn.builders.exampleobject.Builder exampleObjectBuilder) {
this.examples = ArrayUtils.add(this.examples, exampleObjectBuilder.build());
return this;
}
/**
* Schema content builder.
*
* @param schemaBuilder the schema builder
* @return the content builder
*/
public Builder schema(org.springdoc.core.fn.builders.schema.Builder schemaBuilder) {
this.schema = schemaBuilder.build();
return this;
}
/**
* Array content builder.
*
* @param arraySchemaBuilder the array schema builder
* @return the content builder
*/
public Builder array(org.springdoc.core.fn.builders.arrayschema.Builder arraySchemaBuilder) {
this.array = arraySchemaBuilder.build();
return this;
}
/**
* Encoding content builder.
*
* @param encodingBuilder the encoding builder
* @return the content builder
*/
public Builder encoding(org.springdoc.core.fn.builders.encoding.Builder encodingBuilder) {
this.encodings = ArrayUtils.add(this.encodings, encodingBuilder.build());
return this;
}
/**
* Extension content builder.
*
* @param extensionBuilder the extension builder
* @return the content builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build content.
*
* @return the content
*/
public Content build() {<FILL_FUNCTION_BODY>}
}
|
return new Content() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String mediaType() {
return mediaType;
}
@Override
public ExampleObject[] examples() {
return examples;
}
@Override
public Schema schema() {
return schema;
}
@Override
public SchemaProperty[] schemaProperties() {
return schemaProperties;
}
@Override
public Schema additionalPropertiesSchema() {
return additionalPropertiesSchema;
}
@Override
public ArraySchema additionalPropertiesArraySchema() {
return additionalPropertiesArraySchema;
}
@Override
public ArraySchema array() {
return array;
}
@Override
public Encoding[] encoding() {
return encodings;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public DependentSchema[] dependentSchemas() {
return new DependentSchema[0];
}
@Override
public Schema contentSchema() {
return contentSchema;
}
@Override
public Schema propertyNames() {
return propertyNames;
}
@Override
public Schema _if() {
return _if;
}
@Override
public Schema _then() {
return _then;
}
@Override
public Schema _else() {
return _else;
}
@Override
public Schema not() {
return not;
}
@Override
public Schema[] oneOf() {
return oneOf;
}
@Override
public Schema[] anyOf() {
return anyOf;
}
@Override
public Schema[] allOf() {
return allOf;
}
};
| 1,286
| 486
| 1,772
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/discriminatormapping/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The property value that will be mapped to a Schema
*
*/
private String value = "";
/**
* The schema that is being mapped to a property value
*
*/
private Class<?> schema = Void.class;
/**
* The Extensions.
*/
private Extension[] extensions = {};
/**
* Instantiates a new Discriminator mapping builder.
*/
private Builder() {
}
/**
* A discriminator mapping builde discriminator mapping builder.
*
* @return the discriminator mapping builder
*/
public static Builder discriminatorMappingBuilder() {
return new Builder();
}
/**
* Value discriminator mapping builder.
*
* @param value the value
* @return the discriminator mapping builder
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* Schema discriminator mapping builder.
*
* @param schema the schema
* @return the discriminator mapping builder
*/
public Builder schema(Class<?> schema) {
this.schema = schema;
return this;
}
/**
* Build discriminator mapping.
*
* @return the discriminator mapping
*/
public DiscriminatorMapping build() {<FILL_FUNCTION_BODY>}
}
|
return new DiscriminatorMapping() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String value() {
return value;
}
@Override
public Class<?> schema() {
return schema;
}
@Override
public Extension[] extensions() {
return extensions;
}
};
| 352
| 108
| 460
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/encoding/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The name of this encoding object instance.
* This property is a key in encoding map of MediaType object and
* MUST exist in a schema as a property.
*
*/
private String name = "";
/**
* The Content-Type for encoding a specific property.
*
*/
private String contentType = "";
/**
* Describes how a specific property value will be serialized depending on its type
*
*/
private String style = "";
/**
* When this is true, property values of type array or object generate separate parameters for each value of the array,
* or key-value-pair of the map.
*
*/
private boolean explode;
/**
* Determines whether the parameter value SHOULD allow reserved characters,
* as defined by RFC3986 to be included without percent-encoding.
*
*/
private boolean allowReserved;
/**
* An array of header objects
*
*/
private Header[] headers = {};
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* Instantiates a new Encoding builder.
*/
private Builder() {
}
/**
* Builder encoding builder.
*
* @return the encoding builder
*/
public static Builder encodingBuilder() {
return new Builder();
}
/**
* Name encoding builder.
*
* @param name the name
* @return the encoding builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Content type encoding builder.
*
* @param contentType the content type
* @return the encoding builder
*/
public Builder contentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* Style encoding builder.
*
* @param style the style
* @return the encoding builder
*/
public Builder style(String style) {
this.style = style;
return this;
}
/**
* Explode encoding builder.
*
* @param explode the explode
* @return the encoding builder
*/
public Builder explode(boolean explode) {
this.explode = explode;
return this;
}
/**
* Allow reserved encoding builder.
*
* @param allowReserved the allow reserved
* @return the encoding builder
*/
public Builder allowReserved(boolean allowReserved) {
this.allowReserved = allowReserved;
return this;
}
/**
* Headers encoding builder.
*
* @param headerBuilder the header builder
* @return the encoding builder
*/
public Builder headers(org.springdoc.core.fn.builders.header.Builder headerBuilder) {
this.headers = ArrayUtils.add(this.headers, headerBuilder.build());
return this;
}
/**
* Extension encoding builder.
*
* @param extensionBuilder the extension builder
* @return the encoding builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build encoding.
*
* @return the encoding
*/
public Encoding build() {<FILL_FUNCTION_BODY>}
}
|
return new Encoding() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String contentType() {
return contentType;
}
@Override
public String style() {
return style;
}
@Override
public boolean explode() {
return explode;
}
@Override
public boolean allowReserved() {
return allowReserved;
}
@Override
public Header[] headers() {
return headers;
}
@Override
public Extension[] extensions() {
return extensions;
}
};
| 863
| 192
| 1,055
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/exampleobject/Builder.java
|
Builder
|
build
|
class Builder {
/**
* A unique name to identify this particular example
*/
private String name = "";
/**
* A brief summary of the purpose or context of the example
*/
private String summary = "";
/**
* A string representation of the example. This is mutually exclusive with the externalValue property, and ignored if the externalValue property is specified. If the media type associated with the example allows parsing into an object, it may be converted from a string
*/
private String value = "";
/**
* A URL to point to an external document to be used as an example. This is mutually exclusive with the value property.
*/
private String externalValue = "";
/**
* The list of optional extensions
*/
private Extension[] extensions = {};
/**
* A reference to a example defined in components examples.
*/
private String ref = "";
/**
* A description of the purpose or context of the example
*/
private String description = "";
/**
* Instantiates a new Example object builder.
*/
private Builder() {
}
/**
* An example object example object builder.
*
* @return the example object builder
*/
public static Builder exampleOjectBuilder() {
return new Builder();
}
/**
* Name example object builder.
*
* @param name the name
* @return the example object builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Summary example object builder.
*
* @param summary the summary
* @return the example object builder
*/
public Builder summary(String summary) {
this.summary = summary;
return this;
}
/**
* Value example object builder.
*
* @param value the value
* @return the example object builder
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* External value example object builder.
*
* @param externalValue the external value
* @return the example object builder
*/
public Builder externalValue(String externalValue) {
this.externalValue = externalValue;
return this;
}
/**
* Extensions example object builder.
*
* @param extensionBuilder the extensions
* @return the example object builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Ref example object builder.
*
* @param ref the ref
* @return the example object builder
*/
public Builder ref(String ref) {
this.ref = ref;
return this;
}
/**
* Description example object builder.
*
* @param description the description
* @return the example object builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Build example object.
*
* @return the example object
*/
public ExampleObject build() {<FILL_FUNCTION_BODY>}
}
|
return new ExampleObject() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String summary() {
return summary;
}
@Override
public String value() {
return value;
}
@Override
public String externalValue() {
return externalValue;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public String ref() {
return ref;
}
@Override
public String description() {
return description;
}
};
| 792
| 183
| 975
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/extension/Builder.java
|
Builder
|
build
|
class Builder {
/**
* An option name for these extensions.
*
*/
private String name = "";
/**
* The extension properties.
*
*/
private ExtensionProperty[] properties;
/**
* Instantiates a new Extension builder.
*/
private Builder() {
}
/**
* Builder extension builder.
*
* @return the extension builder
*/
public static Builder extensionBuilder() {
return new Builder();
}
/**
* Name extension builder.
*
* @param name the name
* @return the extension builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Properties extension builder.
*
* @param extensionPropertyBuilder the properties
* @return the extension builder
*/
public Builder propertie(org.springdoc.core.fn.builders.extensionproperty.Builder extensionPropertyBuilder) {
this.properties = ArrayUtils.add(this.properties, extensionPropertyBuilder.build());
return this;
}
/**
* Build extension.
*
* @return the extension
*/
public Extension build() {<FILL_FUNCTION_BODY>}
}
|
return new Extension() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public ExtensionProperty[] properties() {
return properties;
}
};
| 304
| 81
| 385
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/extensionproperty/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The name of the property.
*
*/
private String name;
/**
* The value of the property.
*
*/
private String value;
/**
* If set to true, field `value` will be parsed and serialized as JSON/YAML
*
*/
private boolean parseValue;
/**
* Instantiates a new Extension property builder.
*/
private Builder() {
}
/**
* An extension property builder.
*
* @return the extension property builder
*/
public static Builder extensionPropertyBuilder() {
return new Builder();
}
/**
* Name extension property builder.
*
* @param name the name
* @return the extension property builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Value extension property builder.
*
* @param value the value
* @return the extension property builder
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* Parse value extension property builder.
*
* @param parseValue the parse value
* @return the extension property builder
*/
public Builder parseValue(boolean parseValue) {
this.parseValue = parseValue;
return this;
}
/**
* Build extension property.
*
* @return the extension property
*/
public ExtensionProperty build() {<FILL_FUNCTION_BODY>}
}
|
return new ExtensionProperty() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String value() {
return value;
}
@Override
public boolean parseValue() {
return parseValue;
}
};
| 384
| 102
| 486
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/externaldocumentation/Builder.java
|
Builder
|
build
|
class Builder {
/**
* A short description of the target documentation.
*
*/
private String description = "";
/**
* The URL for the target documentation. Value must be in the format of a URL.
*
*/
private String url = "";
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* Instantiates a new External documentation builder.
*/
private Builder() {
}
/**
* An external documentation external documentation builder.
*
* @return the external documentation builder
*/
public static Builder externalDocumentationBuilder() {
return new Builder();
}
/**
* Description external documentation builder.
*
* @param description the description
* @return the external documentation builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Url external documentation builder.
*
* @param url the url
* @return the external documentation builder
*/
public Builder url(String url) {
this.url = url;
return this;
}
/**
* Extensions external documentation builder.
*
* @param extensionBuilder the extensions
* @return the external documentation builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build external documentation.
*
* @return the external documentation
*/
public ExternalDocumentation build() {<FILL_FUNCTION_BODY>}
}
|
return new ExternalDocumentation() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String description() {
return description;
}
@Override
public String url() {
return url;
}
@Override
public Extension[] extensions() {
return extensions;
}
};
| 413
| 103
| 516
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/header/Builder.java
|
Builder
|
build
|
class Builder {
/**
* Required: The name of the header. The name is only used as the key to store this header in a map.
*/
private String name;
/**
* Additional description data to provide on the purpose of the header
*/
private String description = "";
/**
* The schema defining the type used for the header. Ignored if the properties content or array are specified.
*/
private Schema schema = org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().build();
/**
* Determines whether this header is mandatory. The property may be included and its default value is false.
*/
private boolean required;
/**
* Specifies that a header is deprecated and should be transitioned out of usage.
*/
private boolean deprecated;
/**
* A reference to a header defined in components headers.
*
* @since swagger -core 2.0.3
*/
private String ref = "";
/**
* The Explode.
*/
private Explode explode = Explode.DEFAULT;
/**
* The Hidden.
*/
private boolean hidden;
/**
* The Example.
*/
private String example = "";
/**
* The Examples.
*/
private ExampleObject[] examples = {};
/**
* Array array schema.
*/
private ArraySchema array = org.springdoc.core.fn.builders.arrayschema.Builder.arraySchemaBuilder().build();
/**
* Instantiates a new Header builder.
*/
private Builder() {
}
/**
* Builder header builder.
*
* @return the header builder
*/
public static Builder headerBuilder() {
return new Builder();
}
/**
* Name header builder.
*
* @param name the name
* @return the header builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Description header builder.
*
* @param description the description
* @return the header builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Schema header builder.
*
* @param schemaBuilder the schema builder
* @return the header builder
*/
public Builder schema(org.springdoc.core.fn.builders.schema.Builder schemaBuilder) {
this.schema = schemaBuilder.build();
return this;
}
/**
* Required header builder.
*
* @param required the required
* @return the header builder
*/
public Builder required(boolean required) {
this.required = required;
return this;
}
/**
* Deprecated header builder.
*
* @param deprecated the deprecated
* @return the header builder
*/
public Builder deprecated(boolean deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* Ref header builder.
*
* @param ref the ref
* @return the header builder
*/
public Builder ref(String ref) {
this.ref = ref;
return this;
}
/**
* Explode builder.
*
* @param val the val
* @return the builder
*/
public Builder explode(Explode val) {
explode = val;
return this;
}
/**
* Hidden builder.
*
* @param val the val
* @return the builder
*/
public Builder hidden(boolean val) {
hidden = val;
return this;
}
/**
* Example builder.
*
* @param val the val
* @return the builder
*/
public Builder example(String val) {
example = val;
return this;
}
/**
* Examples builder.
*
* @param val the val
* @return the builder
*/
public Builder examples(ExampleObject[] val) {
examples = val;
return this;
}
/**
* Build header.
*
* @return the header
*/
public Header build() {<FILL_FUNCTION_BODY>}
}
|
return new Header() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String description() {
return description;
}
@Override
public Schema schema() {
return schema;
}
@Override
public boolean required() {
return required;
}
@Override
public boolean deprecated() {
return deprecated;
}
@Override
public String ref() {
return ref;
}
@Override
public Explode explode() {
return explode;
}
@Override
public boolean hidden() {
return hidden;
}
@Override
public String example() {
return example;
}
@Override
public ExampleObject[] examples() {
return examples;
}
@Override
public ArraySchema array() {
return array;
}
};
| 1,052
| 270
| 1,322
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/link/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The name of this link.
*
*/
private String name = "";
/**
* A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and must point to an Operation Object. Relative operationRef values may be used to locate an existing Operation Object in the OpenAPI definition. Ignored if the operationId property is specified.
*
*/
private String operationRef = "";
/**
* The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
*
*/
private String operationId = "";
/**
* Array of parameters to pass to an operation as specified with operationId or identified via operationRef.
*
*/
private LinkParameter[] parameters = {};
/**
* A description of the link. CommonMark syntax may be used for rich text representation.
*
*/
private String description = "";
/**
* A literal value or {expression} to use as a request body when calling the target operation.
*
*/
private String requestBody = "";
/**
* An alternative server to service this operation.
*
*/
private Server server = org.springdoc.core.fn.builders.server.Builder.serverBuilder().build();
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* A reference to a link defined in components links.
*
* @since swagger -core 2.0.3
*/
private String ref = "";
/**
* Instantiates a new Link builder.
*/
private Builder() {
}
/**
* Builder link builder.
*
* @return the link builder
*/
public static Builder linkBuilder() {
return new Builder();
}
/**
* Name link builder.
*
* @param name the name
* @return the link builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Operation ref link builder.
*
* @param operationRef the operation ref
* @return the link builder
*/
public Builder operationRef(String operationRef) {
this.operationRef = operationRef;
return this;
}
/**
* Operation id link builder.
*
* @param operationId the operation id
* @return the link builder
*/
public Builder operationId(String operationId) {
this.operationId = operationId;
return this;
}
/**
* Parameter link builder.
*
* @param linkParameterBuilder the link parameter builder
* @return the link builder
*/
public Builder parameter(org.springdoc.core.fn.builders.linkparameter.Builder linkParameterBuilder) {
this.parameters = ArrayUtils.add(this.parameters, linkParameterBuilder.build());
return this;
}
/**
* Description link builder.
*
* @param description the description
* @return the link builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Request body link builder.
*
* @param requestBody the request body
* @return the link builder
*/
public Builder requestBody(String requestBody) {
this.requestBody = requestBody;
return this;
}
/**
* Server link builder.
*
* @param serverBuilder the server builder
* @return the link builder
*/
public Builder server(org.springdoc.core.fn.builders.server.Builder serverBuilder) {
this.server = serverBuilder.build();
return this;
}
/**
* Extension link builder.
*
* @param extensionBuilder the extension builder
* @return the link builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Ref link builder.
*
* @param ref the ref
* @return the link builder
*/
public Builder ref(String ref) {
this.ref = ref;
return this;
}
/**
* Build link.
*
* @return the link
*/
public Link build() {<FILL_FUNCTION_BODY>}
}
|
return new Link() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String operationRef() {
return operationRef;
}
@Override
public String operationId() {
return operationId;
}
@Override
public LinkParameter[] parameters() {
return parameters;
}
@Override
public String description() {
return description;
}
@Override
public String requestBody() {
return requestBody;
}
@Override
public Server server() {
return server;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public String ref() {
return ref;
}
};
| 1,100
| 229
| 1,329
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/linkparameter/Builder.java
|
Builder
|
build
|
class Builder {
/**
* The name of this link parameter.
*
*/
private String name = "";
/**
* A constant or an expression to be evaluated and passed to the linked operation.
*
*/
private String expression = "";
/**
* Instantiates a new Link parameter builder.
*/
private Builder() {
}
/**
* Builder link parameter builder.
*
* @return the link parameter builder
*/
public static Builder linkParameterBuilder() {
return new Builder();
}
/**
* Name link parameter builder.
*
* @param name the name
* @return the link parameter builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Expression link parameter builder.
*
* @param expression the expression
* @return the link parameter builder
*/
public Builder expression(String expression) {
this.expression = expression;
return this;
}
/**
* Build link parameter.
*
* @return the link parameter
*/
public LinkParameter build() {<FILL_FUNCTION_BODY>}
}
|
return new LinkParameter() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String expression() {
return expression;
}
};
| 292
| 81
| 373
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/requestbody/Builder.java
|
Builder
|
build
|
class Builder {
/**
* A brief description of the request body.
*
*/
private String description = "";
/**
* The content of the request body.
*
*/
private Content[] content = {};
/**
* Determines if the request body is required in the request. Defaults to false.
*
*/
private boolean required;
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* A reference to a RequestBody defined in components RequestBodies.
*
* @since swagger -core 2.0.3
*/
private String ref = "";
private boolean useParameterTypeSchema = false;
/**
* Instantiates a new Request body builder.
*/
private Builder() {
}
/**
* Builder request body builder.
*
* @return the request body builder
*/
public static Builder requestBodyBuilder() {
return new Builder();
}
/**
* Description request body builder.
*
* @param description the description
* @return the request body builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Content request body builder.
*
* @param contentBuilder the content builder
* @return the request body builder
*/
public Builder content(org.springdoc.core.fn.builders.content.Builder contentBuilder) {
this.content = ArrayUtils.add(this.content, contentBuilder.build());
return this;
}
/**
* Implementation request body builder.
*
* @param clazz the clazz
* @return the request body builder
*/
public Builder implementation(Class clazz) {
this.content = ArrayUtils.add(this.content, org.springdoc.core.fn.builders.content.Builder.contentBuilder().schema(org.springdoc.core.fn.builders.schema.Builder.schemaBuilder().implementation(clazz)).build());
return this;
}
/**
* Required request body builder.
*
* @param required the required
* @return the request body builder
*/
public Builder required(boolean required) {
this.required = required;
return this;
}
/**
* Extension request body builder.
*
* @param extensionBuilder the extension builder
* @return the request body builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Ref request body builder.
*
* @param ref the ref
* @return the request body builder
*/
public Builder ref(String ref) {
this.ref = ref;
return this;
}
/**
* Build request body.
*
* @return the request body
*/
public RequestBody build() {<FILL_FUNCTION_BODY>}
}
|
return new RequestBody() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String description() {
return description;
}
@Override
public Content[] content() {
return content;
}
@Override
public boolean required() {
return required;
}
@Override
public Extension[] extensions() {
return extensions;
}
@Override
public String ref() {
return ref;
}
@Override
public boolean useParameterTypeSchema() {
return useParameterTypeSchema;
}
};
| 751
| 169
| 920
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/securityrequirement/Builder.java
|
Builder
|
build
|
class Builder {
/**
* This name must correspond to a declared SecurityRequirement.
*
*/
private String name;
/**
* If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of scope names required for the execution.
* For other security scheme types, the array must be empty.
*
*/
private String[] scopes = {};
/**
* Instantiates a new Security requirement builder.
*/
private Builder() {
}
/**
* Builder security requirement builder.
*
* @return the security requirement builder
*/
public static Builder securityRequirementBuilder() {
return new Builder();
}
/**
* Name security requirement builder.
*
* @param name the name
* @return the security requirement builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Scopes security requirement builder.
*
* @param scopes the scopes
* @return the security requirement builder
*/
public Builder scopes(String[] scopes) {
this.scopes = scopes;
return this;
}
/**
* Build security requirement.
*
* @return the security requirement
*/
public SecurityRequirement build() {<FILL_FUNCTION_BODY>}
}
|
return new SecurityRequirement() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String[] scopes() {
return scopes;
}
};
| 338
| 84
| 422
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/server/Builder.java
|
Builder
|
build
|
class Builder {
/**
* Required. A URL to the target host.
* This URL supports Server Variables and may be relative, to indicate that the host location is relative to the location where the
* OpenAPI definition is being served. Variable substitutions will be made when a variable is named in {brackets}.
*
*/
private String url = "";
/**
* An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
*
*/
private String description = "";
/**
* An array of variables used for substitution in the server's URL template.
*
*/
private ServerVariable[] variables = {};
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* Instantiates a new Server builder.
*/
private Builder() {
}
/**
* Builder server builder.
*
* @return the server builder
*/
public static Builder serverBuilder() {
return new Builder();
}
/**
* Url server builder.
*
* @param url the url
* @return the server builder
*/
public Builder url(String url) {
this.url = url;
return this;
}
/**
* Description server builder.
*
* @param description the description
* @return the server builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Variables server builder.
*
* @param serverVariableBuilder the server variable builder
* @return the server builder
*/
public Builder variables(org.springdoc.core.fn.builders.servervariable.Builder serverVariableBuilder) {
this.variables = ArrayUtils.add(this.variables, serverVariableBuilder.build());
return this;
}
/**
* Extension server builder.
*
* @param extensionBuilder the extension builder
* @return the server builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build server.
*
* @return the server
*/
public Server build() {<FILL_FUNCTION_BODY>}
}
|
return new Server() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String url() {
return url;
}
@Override
public String description() {
return description;
}
@Override
public ServerVariable[] variables() {
return variables;
}
@Override
public Extension[] extensions() {
return extensions;
}
};
| 585
| 123
| 708
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/fn/builders/servervariable/Builder.java
|
Builder
|
build
|
class Builder {
/**
* Required. The name of this variable.
*
*/
private String name;
/**
* An array of allowable values for this variable. This field map to the enum property in the OAS schema.
*
* @return String array of allowableValues
*/
private String[] allowableValues = {};
/**
* Required. The default value of this variable.
*
*/
private String defaultValue;
/**
* An optional description for the server variable.
*
*/
private String description = "";
/**
* The list of optional extensions
*
*/
private Extension[] extensions = {};
/**
* Instantiates a new Server variable builder.
*/
private Builder() {
}
/**
* Builder server variable builder.
*
* @return the server variable builder
*/
public static Builder serverVariableBuilder() {
return new Builder();
}
/**
* Name server variable builder.
*
* @param name the name
* @return the server variable builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Allowable values server variable builder.
*
* @param allowableValues the allowable values
* @return the server variable builder
*/
public Builder allowableValues(String[] allowableValues) {
this.allowableValues = allowableValues;
return this;
}
/**
* Default value server variable builder.
*
* @param defaultValue the default value
* @return the server variable builder
*/
public Builder defaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
/**
* Description server variable builder.
*
* @param description the description
* @return the server variable builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Extension server variable builder.
*
* @param extensionBuilder the extension builder
* @return the server variable builder
*/
public Builder extension(org.springdoc.core.fn.builders.extension.Builder extensionBuilder) {
this.extensions = ArrayUtils.add(this.extensions, extensionBuilder.build());
return this;
}
/**
* Build server variable.
*
* @return the server variable
*/
public ServerVariable build() {<FILL_FUNCTION_BODY>}
}
|
return new ServerVariable() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String name() {
return name;
}
@Override
public String[] allowableValues() {
return allowableValues;
}
@Override
public String defaultValue() {
return defaultValue;
}
@Override
public String description() {
return description;
}
@Override
public Extension[] extensions() {
return extensions;
}
};
| 619
| 148
| 767
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/models/ControllerAdviceInfo.java
|
ControllerAdviceInfo
|
getApiResponseMap
|
class ControllerAdviceInfo {
/**
* The Controller advice.
*/
private final Object controllerAdvice;
/**
* The Method advice infos.
*/
private List<MethodAdviceInfo> methodAdviceInfos = new ArrayList<>();
/**
* Instantiates a new Controller advice info.
*
* @param controllerAdvice the controller advice
*/
public ControllerAdviceInfo(Object controllerAdvice) {
this.controllerAdvice = controllerAdvice;
}
/**
* Gets controller advice.
*
* @return the controller advice
*/
public Object getControllerAdvice() {
return controllerAdvice;
}
/**
* Gets api response map.
*
* @return the api response map
*/
public Map<String, ApiResponse> getApiResponseMap() {<FILL_FUNCTION_BODY>}
public List<MethodAdviceInfo> getMethodAdviceInfos() {
return methodAdviceInfos;
}
public void addMethodAdviceInfos(MethodAdviceInfo methodAdviceInfo) {
this.methodAdviceInfos.add(methodAdviceInfo);
}
}
|
Map<String, ApiResponse> apiResponseMap = new LinkedHashMap<>();
for (MethodAdviceInfo methodAdviceInfo : methodAdviceInfos) {
if (!CollectionUtils.isEmpty(methodAdviceInfo.getApiResponses()))
apiResponseMap.putAll(methodAdviceInfo.getApiResponses());
}
return apiResponseMap;
| 288
| 95
| 383
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/models/ParameterId.java
|
ParameterId
|
equals
|
class ParameterId {
/**
* The P name.
*/
private String pName;
/**
* The Param type.
*/
private String paramType;
/**
* The Ref.
*/
private String $ref;
/**
* Instantiates a new Parameter id.
*
* @param parameter the parameter
*/
public ParameterId(Parameter parameter) {
this.pName = parameter.getName();
this.paramType = parameter.getIn();
this.$ref = parameter.get$ref();
}
/**
* Instantiates a new Parameter id.
*
* @param parameter the parameter
*/
public ParameterId(io.swagger.v3.oas.annotations.Parameter parameter) {
this.pName = parameter.name();
this.paramType = StringUtils.isNotBlank(parameter.in().toString()) ? parameter.in().toString() : null;
this.$ref = StringUtils.isNotBlank(parameter.ref()) ? parameter.ref() : null;
}
/**
* Instantiates a new Parameter id.
*
* @param pName the p name
* @param paramType the param type
*/
public ParameterId(String pName, String paramType) {
this.pName = pName;
this.paramType = paramType;
}
/**
* Gets name.
*
* @return the name
*/
public String getpName() {
return pName;
}
/**
* Sets name.
*
* @param pName the p name
*/
public void setpName(String pName) {
this.pName = pName;
}
/**
* Gets param type.
*
* @return the param type
*/
public String getParamType() {
return paramType;
}
/**
* Sets param type.
*
* @param paramType the param type
*/
public void setParamType(String paramType) {
this.paramType = paramType;
}
/**
* Get ref string.
*
* @return the string
*/
public String get$ref() {
return $ref;
}
/**
* Set ref.
*
* @param $ref the ref
*/
public void set$ref(String $ref) {
this.$ref = $ref;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(pName, paramType, $ref);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterId that = (ParameterId) o;
if (this.pName == null && StringUtils.isBlank(this.paramType))
return Objects.equals($ref, that.$ref);
if (this.pName != null && StringUtils.isBlank(this.paramType))
return Objects.equals(pName, that.pName);
return Objects.equals(pName, that.pName) && Objects.equals(paramType, that.paramType);
| 662
| 159
| 821
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/models/ParameterInfo.java
|
ParameterInfo
|
calculateParams
|
class ParameterInfo {
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ParameterInfo.class);
/**
* The Method parameter.
*/
private final MethodParameter methodParameter;
/**
* The P name.
*/
private String pName;
/**
* The Parameter model.
*/
private io.swagger.v3.oas.models.parameters.Parameter parameterModel;
/**
* The Required.
*/
private boolean required;
/**
* The Default value.
*/
private Object defaultValue;
/**
* The Param type.
*/
private String paramType;
/**
* if the paramater type is RequestPart
*/
private boolean requestPart;
/**
* The Parameter id.
*/
private ParameterId parameterId;
/**
* Instantiates a new Parameter info.
* @param pName the parameter name
* @param methodParameter the method parameter
* @param genericParameterService the parameter builder
* @param parameterAnnotation the parameter annotation
*/
public ParameterInfo(String pName, MethodParameter methodParameter, GenericParameterService genericParameterService, Parameter parameterAnnotation) {
RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
PathVariable pathVar = methodParameter.getParameterAnnotation(PathVariable.class);
CookieValue cookieValue = methodParameter.getParameterAnnotation(CookieValue.class);
boolean isFile = genericParameterService.isFile(methodParameter);
this.methodParameter = methodParameter;
this.pName = pName;
if (requestHeader != null)
calculateParams(requestHeader);
else if (requestParam != null)
calculateParams(requestParam, isFile);
else if (pathVar != null)
calculateParams(pathVar);
else if (cookieValue != null)
calculateParams(cookieValue);
if (StringUtils.isNotBlank(this.pName))
this.pName = genericParameterService.resolveEmbeddedValuesAndExpressions(this.pName).toString();
if (this.defaultValue != null && !ValueConstants.DEFAULT_NONE.equals(this.defaultValue.toString())) {
this.defaultValue = genericParameterService.resolveEmbeddedValuesAndExpressions(this.defaultValue.toString());
genericParameterService.getOptionalWebConversionServiceProvider()
.ifPresent(conversionService -> {
try {
this.defaultValue = conversionService.convert(this.defaultValue, new TypeDescriptor(methodParameter));
}
catch (Exception e) {
LOGGER.warn("Using the following default value : {}, without spring conversionService", this.defaultValue);
}
}
);
}
this.required = this.required && !methodParameter.isOptional();
if (parameterAnnotation != null) {
this.parameterId = new ParameterId(parameterAnnotation);
if (StringUtils.isBlank(parameterId.getpName()))
this.parameterId.setpName(this.pName);
if (StringUtils.isBlank(parameterId.getParamType()))
this.parameterId.setParamType(this.paramType);
}
else
this.parameterId = new ParameterId(this.pName, paramType);
}
/**
* Gets name.
*
* @return the name
*/
public String getpName() {
return pName;
}
/**
* Sets name.
*
* @param pName the p name
*/
public void setpName(String pName) {
this.pName = pName;
}
/**
* Gets method parameter.
*
* @return the method parameter
*/
public MethodParameter getMethodParameter() {
return methodParameter;
}
/**
* Gets parameter model.
*
* @return the parameter model
*/
public io.swagger.v3.oas.models.parameters.Parameter getParameterModel() {
return parameterModel;
}
/**
* Sets parameter model.
*
* @param parameterModel the parameter model
*/
public void setParameterModel(io.swagger.v3.oas.models.parameters.Parameter parameterModel) {
this.parameterModel = parameterModel;
}
/**
* Is required boolean.
*
* @return the boolean
*/
public boolean isRequired() {
return required;
}
/**
* Sets required.
*
* @param required the required
*/
public void setRequired(boolean required) {
this.required = required;
}
/**
* Gets default value.
*
* @return the default value
*/
public Object getDefaultValue() {
return defaultValue;
}
/**
* Sets default value.
*
* @param defaultValue the default value
*/
public void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Gets param type.
*
* @return the param type
*/
public String getParamType() {
return paramType;
}
/**
* Sets param type.
*
* @param paramType the param type
*/
public void setParamType(String paramType) {
this.paramType = paramType;
}
/**
* Calculate params.
*
* @param cookieValue the cookie value
*/
private void calculateParams(CookieValue cookieValue) {
if (StringUtils.isNotEmpty(cookieValue.value()))
this.pName = cookieValue.value();
this.required = cookieValue.required();
this.defaultValue = cookieValue.defaultValue();
this.paramType = ParameterIn.COOKIE.toString();
}
/**
* Calculate params.
*
* @param pathVar the path var
*/
private void calculateParams(PathVariable pathVar) {
if (StringUtils.isNotEmpty(pathVar.value()))
this.pName = pathVar.value();
this.required = pathVar.required();
this.paramType = ParameterIn.PATH.toString();
}
/**
* Calculate params.
*
* @param requestParam the request param
* @param isFile the is file
*/
private void calculateParams(RequestParam requestParam, boolean isFile) {<FILL_FUNCTION_BODY>}
/**
* Calculate params.
*
* @param requestHeader the request header
*/
private void calculateParams(RequestHeader requestHeader) {
if (StringUtils.isNotEmpty(requestHeader.value()))
this.pName = requestHeader.value();
this.required = requestHeader.required();
this.defaultValue = requestHeader.defaultValue();
this.paramType = ParameterIn.HEADER.toString();
}
/**
* Is request part boolean.
*
* @return the boolean
*/
public boolean isRequestPart() {
return requestPart;
}
/**
* Sets request part.
*
* @param requestPart the request part
*/
public void setRequestPart(boolean requestPart) {
this.requestPart = requestPart;
}
/**
* Gets parameter id.
*
* @return the parameter id
*/
public ParameterId getParameterId() {
return parameterId;
}
/**
* Sets parameter id.
*
* @param parameterId the parameter id
*/
public void setParameterId(ParameterId parameterId) {
this.parameterId = parameterId;
}
}
|
if (StringUtils.isNotEmpty(requestParam.value()))
this.pName = requestParam.value();
this.required = requestParam.required();
this.defaultValue = requestParam.defaultValue();
if (!isFile)
this.paramType = ParameterIn.QUERY.toString();
| 1,940
| 78
| 2,018
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/models/RequestBodyInfo.java
|
RequestBodyInfo
|
addProperties
|
class RequestBodyInfo {
/**
* The Request body.
*/
private RequestBody requestBody;
/**
* The Merged schema.
*/
private Schema mergedSchema;
/**
* Gets request body.
*
* @return the request body
*/
public RequestBody getRequestBody() {
return requestBody;
}
/**
* Sets request body.
*
* @param requestBody the request body
*/
public void setRequestBody(RequestBody requestBody) {
this.requestBody = requestBody;
}
/**
* Gets merged schema.
*
* @return the merged schema
*/
public Schema getMergedSchema() {
return mergedSchema;
}
/**
* Sets merged schema.
*
* @param mergedSchema the merged schema
*/
public void setMergedSchema(Schema mergedSchema) {
this.mergedSchema = mergedSchema;
}
/**
* Add properties.
*
* @param paramName the param name
* @param schemaN the schema n
*/
public void addProperties(String paramName, Schema schemaN) {<FILL_FUNCTION_BODY>}
}
|
if (mergedSchema == null)
mergedSchema = new ObjectSchema();
mergedSchema.addProperty(paramName, schemaN);
| 302
| 40
| 342
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/parsers/KotlinCoroutinesReturnTypeParser.java
|
KotlinCoroutinesReturnTypeParser
|
getReturnType
|
class KotlinCoroutinesReturnTypeParser implements ReturnTypeParser {
@Override
public Type getReturnType(MethodParameter methodParameter) {<FILL_FUNCTION_BODY>}
}
|
Method method = methodParameter.getMethod();
Type returnType = Object.class;
assert method != null;
Optional<Parameter> continuationParameter = Arrays.stream(method.getParameters())
.filter(parameter -> parameter.getType().getCanonicalName().equals(Continuation.class.getCanonicalName()))
.findFirst();
if (continuationParameter.isPresent()) {
Type continuationType = continuationParameter.get().getParameterizedType();
if (continuationType instanceof ParameterizedType) {
Type actualTypeArguments = ((ParameterizedType) continuationType).getActualTypeArguments()[0];
if (actualTypeArguments instanceof WildcardType)
returnType = ((WildcardType) actualTypeArguments).getLowerBounds()[0];
}
}
return returnType;
| 47
| 208
| 255
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/AbstractSwaggerUiConfigProperties.java
|
SwaggerUrl
|
toString
|
class SwaggerUrl {
/**
* The Url.
*/
@JsonProperty("url")
private String url;
/**
* The Name.
*/
@JsonIgnore
private String name;
/**
* The Display name.
*/
@JsonProperty("name")
private String displayName;
/**
* Instantiates a new Swagger url.
*/
public SwaggerUrl() {
}
/**
* Instantiates a new Swagger url.
*
* @param group the group
* @param url the url
* @param displayName the display name
*/
public SwaggerUrl(String group, String url, String displayName) {
Objects.requireNonNull(group, GROUP_NAME_NOT_NULL_OR_EMPTY);
this.url = url;
this.name = group;
this.displayName = StringUtils.defaultIfEmpty(displayName, this.name);
}
/**
* Gets display name.
*
* @return the display name
*/
public String getDisplayName() {
return displayName;
}
/**
* Sets display name.
*
* @param displayName the display name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* Gets url.
*
* @return the url
*/
public String getUrl() {
return url;
}
/**
* Sets url.
*
* @param url the url
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets name.
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SwaggerUrl that = (SwaggerUrl) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder("SwaggerUrl{");
sb.append("url='").append(url).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
| 642
| 75
| 717
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SpringDocConfigProperties.java
|
GroupConfig
|
equals
|
class GroupConfig {
/**
* The Paths to match.
*/
private List<String> pathsToMatch;
/**
* The Packages to scan.
*/
private List<String> packagesToScan;
/**
* The Packages to exclude.
*/
private List<String> packagesToExclude;
/**
* The Paths to exclude.
*/
private List<String> pathsToExclude;
/**
* The Group.
*/
private String group;
/**
* The Produces to match.
*/
private List<String> producesToMatch;
/**
* The Headers to match.
*/
private List<String> headersToMatch;
/**
* The Consumes to match.
*/
private List<String> consumesToMatch;
/**
* The Display name.
*/
private String displayName;
/**
* The Open api.
*/
private OpenAPI openApi;
/**
* Instantiates a new Group config.
*/
public GroupConfig() {
}
/**
* Instantiates a new Group config.
*
* @param group the group
* @param pathsToMatch the paths to match
* @param packagesToScan the packages to scan
* @param packagesToExclude the packages to exclude
* @param pathsToExclude the paths to exclude
* @param producesToMatch the produces to match
* @param consumesToMatch the consumes to match
* @param headersToMatch the headers to match
* @param displayName the display name
*/
public GroupConfig(String group, List<String> pathsToMatch, List<String> packagesToScan,
List<String> packagesToExclude, List<String> pathsToExclude,
List<String> producesToMatch, List<String> consumesToMatch, List<String> headersToMatch,
String displayName) {
this.pathsToMatch = pathsToMatch;
this.pathsToExclude = pathsToExclude;
this.packagesToExclude = packagesToExclude;
this.packagesToScan = packagesToScan;
this.group = group;
this.producesToMatch = producesToMatch;
this.consumesToMatch = consumesToMatch;
this.headersToMatch = headersToMatch;
this.displayName = displayName;
}
/**
* Gets headers to match.
*
* @return the headers to match
*/
public List<String> getHeadersToMatch() {
return headersToMatch;
}
/**
* Sets headers to match.
*
* @param headersToMatch the headers to match
*/
public void setHeadersToMatch(List<String> headersToMatch) {
this.headersToMatch = headersToMatch;
}
/**
* Gets consumes to match.
*
* @return the consumes to match
*/
public List<String> getConsumesToMatch() {
return consumesToMatch;
}
/**
* Sets consumes to match.
*
* @param consumesToMatch the consumes to match
*/
public void setConsumesToMatch(List<String> consumesToMatch) {
this.consumesToMatch = consumesToMatch;
}
/**
* Gets paths to match.
*
* @return the paths to match
*/
public List<String> getPathsToMatch() {
return pathsToMatch;
}
/**
* Sets paths to match.
*
* @param pathsToMatch the paths to match
*/
public void setPathsToMatch(List<String> pathsToMatch) {
this.pathsToMatch = pathsToMatch;
}
/**
* Gets packages to scan.
*
* @return the packages to scan
*/
public List<String> getPackagesToScan() {
return packagesToScan;
}
/**
* Sets packages to scan.
*
* @param packagesToScan the packages to scan
*/
public void setPackagesToScan(List<String> packagesToScan) {
this.packagesToScan = packagesToScan;
}
/**
* Gets group.
*
* @return the group
*/
public String getGroup() {
return group;
}
/**
* Sets group.
*
* @param group the group
*/
public void setGroup(String group) {
this.group = group;
}
/**
* Gets packages to exclude.
*
* @return the packages to exclude
*/
public List<String> getPackagesToExclude() {
return packagesToExclude;
}
/**
* Sets packages to exclude.
*
* @param packagesToExclude the packages to exclude
*/
public void setPackagesToExclude(List<String> packagesToExclude) {
this.packagesToExclude = packagesToExclude;
}
/**
* Gets paths to exclude.
*
* @return the paths to exclude
*/
public List<String> getPathsToExclude() {
return pathsToExclude;
}
/**
* Sets paths to exclude.
*
* @param pathsToExclude the paths to exclude
*/
public void setPathsToExclude(List<String> pathsToExclude) {
this.pathsToExclude = pathsToExclude;
}
/**
* Gets produces to match.
*
* @return the produces to match
*/
public List<String> getProducesToMatch() {
return producesToMatch;
}
/**
* Sets produces to match.
*
* @param producesToMatch the produces to match
*/
public void setProducesToMatch(List<String> producesToMatch) {
this.producesToMatch = producesToMatch;
}
/**
* Gets display name.
*
* @return the display name
*/
public String getDisplayName() {
return displayName;
}
/**
* Sets display name.
*
* @param displayName the display name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* Gets open api.
*
* @return the open api
*/
public OpenAPI getOpenApi() {
return openApi;
}
/**
* Sets open api.
*
* @param openApi the open api
*/
public void setOpenApi(OpenAPI openApi) {
this.openApi = openApi;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(group);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupConfig that = (GroupConfig) o;
return Objects.equals(group, that.group);
| 1,776
| 62
| 1,838
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SwaggerUiOAuthProperties.java
|
SwaggerUiOAuthProperties
|
getConfigParameters
|
class SwaggerUiOAuthProperties {
/**
* The Client id.
*/
private String clientId;
/**
* The Client secret.
*/
private String clientSecret;
/**
* The Realm.
*/
private String realm;
/**
* The App name.
*/
private String appName;
/**
* The Scope separator.
*/
private String scopeSeparator;
/**
* The Additional query string params.
*/
private Map<String, String> additionalQueryStringParams;
/**
* The Use basic authentication with access code grant.
*/
private Boolean useBasicAuthenticationWithAccessCodeGrant;
/**
* The Use pkce with authorization code grant.
*/
private Boolean usePkceWithAuthorizationCodeGrant;
/**
* The Scopes selected by default upon authentication.
*/
private List<String> scopes;
/**
* Gets config parameters.
*
* @return the config parameters
*/
public Map<String, Object> getConfigParameters() {<FILL_FUNCTION_BODY>}
/**
* Gets client id.
*
* @return the client id
*/
public String getClientId() {
return clientId;
}
/**
* Sets client id.
*
* @param clientId the client id
*/
public void setClientId(String clientId) {
this.clientId = clientId;
}
/**
* Gets client secret.
*
* @return the client secret
*/
public String getClientSecret() {
return clientSecret;
}
/**
* Sets client secret.
*
* @param clientSecret the client secret
*/
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
/**
* Gets realm.
*
* @return the realm
*/
public String getRealm() {
return realm;
}
/**
* Sets realm.
*
* @param realm the realm
*/
public void setRealm(String realm) {
this.realm = realm;
}
/**
* Gets app name.
*
* @return the app name
*/
public String getAppName() {
return appName;
}
/**
* Sets app name.
*
* @param appName the app name
*/
public void setAppName(String appName) {
this.appName = appName;
}
/**
* Gets scope separator.
*
* @return the scope separator
*/
public String getScopeSeparator() {
return scopeSeparator;
}
/**
* Sets scope separator.
*
* @param scopeSeparator the scope separator
*/
public void setScopeSeparator(String scopeSeparator) {
this.scopeSeparator = scopeSeparator;
}
/**
* Gets additional query string params.
*
* @return the additional query string params
*/
public Map<String, String> getAdditionalQueryStringParams() {
return additionalQueryStringParams;
}
/**
* Sets additional query string params.
*
* @param additionalQueryStringParams the additional query string params
*/
public void setAdditionalQueryStringParams(Map<String, String> additionalQueryStringParams) {
this.additionalQueryStringParams = additionalQueryStringParams;
}
/**
* Gets use basic authentication with access code grant.
*
* @return the use basic authentication with access code grant
*/
public Boolean getUseBasicAuthenticationWithAccessCodeGrant() {
return useBasicAuthenticationWithAccessCodeGrant;
}
/**
* Sets use basic authentication with access code grant.
*
* @param useBasicAuthenticationWithAccessCodeGrant the use basic authentication with access code grant
*/
public void setUseBasicAuthenticationWithAccessCodeGrant(Boolean useBasicAuthenticationWithAccessCodeGrant) {
this.useBasicAuthenticationWithAccessCodeGrant = useBasicAuthenticationWithAccessCodeGrant;
}
/**
* Gets use pkce with authorization code grant.
*
* @return the use pkce with authorization code grant
*/
public Boolean getUsePkceWithAuthorizationCodeGrant() {
return usePkceWithAuthorizationCodeGrant;
}
/**
* Sets use pkce with authorization code grant.
*
* @param usePkceWithAuthorizationCodeGrant the use pkce with authorization code grant
*/
public void setUsePkceWithAuthorizationCodeGrant(Boolean usePkceWithAuthorizationCodeGrant) {
this.usePkceWithAuthorizationCodeGrant = usePkceWithAuthorizationCodeGrant;
}
/**
* Get the pre-selected scopes during authentication.
*
* @return the pre-selected scopes during authentication
*/
public List<String> getScopes() {
return scopes;
}
/**
* Sets the pre-selected scopes during authentication.
*
* @param scopes the pre-selected scopes during authentication
*/
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
}
|
final Map<String, Object> params = new TreeMap<>();
SpringDocPropertiesUtils.put("clientId", clientId, params);
SpringDocPropertiesUtils.put("clientSecret", clientSecret, params);
SpringDocPropertiesUtils.put("realm", realm, params);
SpringDocPropertiesUtils.put("scopeSeparator", scopeSeparator, params);
SpringDocPropertiesUtils.put("appName", appName, params);
if (!CollectionUtils.isEmpty(scopes)) {
SpringDocPropertiesUtils.put("scopes", String.join(" ", scopes), params);
}
SpringDocPropertiesUtils.put("useBasicAuthenticationWithAccessCodeGrant", useBasicAuthenticationWithAccessCodeGrant, params);
SpringDocPropertiesUtils.put("usePkceWithAuthorizationCodeGrant", usePkceWithAuthorizationCodeGrant, params);
SpringDocPropertiesUtils.put("additionalQueryStringParams", additionalQueryStringParams, params);
return params;
| 1,297
| 251
| 1,548
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/providers/ActuatorProvider.java
|
ActuatorProvider
|
onApplicationEvent
|
class ActuatorProvider implements ApplicationListener<WebServerInitializedEvent> {
/**
* The Management server properties.
*/
protected ManagementServerProperties managementServerProperties;
/**
* The Web endpoint properties.
*/
protected WebEndpointProperties webEndpointProperties;
/**
* The Server properties.
*/
protected ServerProperties serverProperties;
/**
* The Spring doc config properties.
*/
protected SpringDocConfigProperties springDocConfigProperties;
/**
* The Actuator web server.
*/
protected WebServer actuatorWebServer;
/**
* The Application web server.
*/
protected WebServer applicationWebServer;
/**
* The Management application context.
*/
protected ApplicationContext managementApplicationContext;
/**
* Instantiates a new Actuator provider.
*
* @param managementServerProperties the management server properties
* @param webEndpointProperties the web endpoint properties
* @param serverProperties the server properties
* @param springDocConfigProperties the spring doc config properties
*/
public ActuatorProvider(Optional<ManagementServerProperties> managementServerProperties,
Optional<WebEndpointProperties> webEndpointProperties,
ServerProperties serverProperties,
SpringDocConfigProperties springDocConfigProperties) {
managementServerProperties.ifPresent(managementServerProperties1 -> this.managementServerProperties = managementServerProperties1);
webEndpointProperties.ifPresent(webEndpointProperties1 -> this.webEndpointProperties = webEndpointProperties1);
this.serverProperties = serverProperties;
this.springDocConfigProperties = springDocConfigProperties;
}
/**
* Gets tag.
*
* @return the tag
*/
public static Tag getTag() {
Tag actuatorTag = new Tag();
actuatorTag.setName(Constants.SPRINGDOC_ACTUATOR_TAG);
actuatorTag.setDescription(Constants.SPRINGDOC_ACTUATOR_DESCRIPTION);
actuatorTag.setExternalDocs(
new ExternalDocumentation()
.url(Constants.SPRINGDOC_ACTUATOR_DOC_URL)
.description(Constants.SPRINGDOC_ACTUATOR_DOC_DESCRIPTION)
);
return actuatorTag;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {<FILL_FUNCTION_BODY>}
/**
* Is rest controller boolean.
*
* @param operationPath the operation path
* @param handlerMethod the handler method
* @return the boolean
*/
public boolean isRestController(String operationPath, HandlerMethod handlerMethod) {
return operationPath.startsWith(AntPathMatcher.DEFAULT_PATH_SEPARATOR)
&& !AbstractOpenApiResource.isHiddenRestControllers(handlerMethod.getBeanType())
&& AbstractOpenApiResource.containsResponseBody(handlerMethod);
}
/**
* Is use management port boolean.
*
* @return the boolean
*/
public boolean isUseManagementPort() {
return springDocConfigProperties.isUseManagementPort();
}
/**
* Gets base path.
*
* @return the base path
*/
public String getBasePath() {
return webEndpointProperties.getBasePath();
}
/**
* Gets context path.
*
* @return the context path
*/
public String getContextPath() {
return EMPTY;
}
/**
* Gets actuator path.
*
* @return the actuator path
*/
public String getActuatorPath() {
return managementServerProperties.getBasePath();
}
/**
* Gets application port.
*
* @return the application port
*/
public int getApplicationPort() {
return applicationWebServer.getPort();
}
/**
* Gets actuator port.
*
* @return the actuator port
*/
public int getActuatorPort() {
return actuatorWebServer.getPort();
}
/**
* Gets methods.
*
* @return the methods
*/
public abstract Map getMethods();
}
|
if (WebServerApplicationContext.hasServerNamespace(event.getApplicationContext(), "management")) {
managementApplicationContext = event.getApplicationContext();
actuatorWebServer = event.getWebServer();
}
else {
applicationWebServer = event.getWebServer();
}
| 1,028
| 77
| 1,105
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/providers/ObjectMapperProvider.java
|
ObjectMapperProvider
|
createJson
|
class ObjectMapperProvider extends ObjectMapperFactory {
/**
* The Json mapper.
*/
private final ObjectMapper jsonMapper;
/**
* The Yaml mapper.
*/
private final ObjectMapper yamlMapper;
/**
* Instantiates a new Spring doc object mapper.
*
* @param springDocConfigProperties the spring doc config properties
*/
public ObjectMapperProvider(SpringDocConfigProperties springDocConfigProperties) {
OpenApiVersion openApiVersion = springDocConfigProperties.getApiDocs().getVersion();
if (openApiVersion == OpenApiVersion.OPENAPI_3_1) {
jsonMapper = Json31.mapper();
yamlMapper = Yaml31.mapper();
}
else {
jsonMapper = Json.mapper();
yamlMapper = Yaml.mapper();
}
}
/**
* Create json object mapper.
*
* @param springDocConfigProperties the spring doc config properties
* @return the object mapper
*/
public static ObjectMapper createJson(SpringDocConfigProperties springDocConfigProperties) {<FILL_FUNCTION_BODY>}
/**
* Sort output.
*
* @param objectMapper the object mapper
*/
public static void sortOutput(ObjectMapper objectMapper, SpringDocConfigProperties springDocConfigProperties) {
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
if (OpenApiVersion.OPENAPI_3_1 == springDocConfigProperties.getApiDocs().getVersion()) {
objectMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin31.class);
objectMapper.addMixIn(Schema.class, SortedSchemaMixin31.class);
}
else {
objectMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin.class);
objectMapper.addMixIn(Schema.class, SortedSchemaMixin.class);
}
}
/**
* Mapper object mapper.
*
* @return the object mapper
*/
public ObjectMapper jsonMapper() {
return jsonMapper;
}
/**
* Yaml mapper object mapper.
*
* @return the object mapper
*/
public ObjectMapper yamlMapper() {
return yamlMapper;
}
}
|
OpenApiVersion openApiVersion = springDocConfigProperties.getApiDocs().getVersion();
ObjectMapper objectMapper;
if (openApiVersion == OpenApiVersion.OPENAPI_3_1)
objectMapper = ObjectMapperProvider.createJson31();
else
objectMapper = ObjectMapperProvider.createJson();
if (springDocConfigProperties.isWriterWithOrderByKeys())
sortOutput(objectMapper, springDocConfigProperties);
return objectMapper;
| 626
| 123
| 749
|
<methods>public void <init>() ,public static com.fasterxml.jackson.databind.ObjectMapper buildStrictGenericObjectMapper() ,public static com.fasterxml.jackson.databind.ObjectMapper create(com.fasterxml.jackson.core.JsonFactory, boolean) ,public static com.fasterxml.jackson.databind.ObjectMapper createJson() ,public static com.fasterxml.jackson.databind.ObjectMapper createJson(com.fasterxml.jackson.core.JsonFactory) ,public static com.fasterxml.jackson.databind.ObjectMapper createJson31() ,public static com.fasterxml.jackson.databind.ObjectMapper createJson31(com.fasterxml.jackson.core.JsonFactory) ,public static com.fasterxml.jackson.databind.ObjectMapper createJsonConverter() ,public static com.fasterxml.jackson.databind.ObjectMapper createYaml() ,public static com.fasterxml.jackson.databind.ObjectMapper createYaml(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ,public static com.fasterxml.jackson.databind.ObjectMapper createYaml(boolean) ,public static com.fasterxml.jackson.databind.ObjectMapper createYaml31() ,public static com.fasterxml.jackson.databind.ObjectMapper createYaml31(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) <variables>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/providers/SpringDocJavadocProvider.java
|
SpringDocJavadocProvider
|
getFirstSentence
|
class SpringDocJavadocProvider implements JavadocProvider {
/**
* The comment formatter.
*/
private final CommentFormatter formatter = new CommentFormatter();
/**
* Gets class description.
*
* @param cl the class
* @return the class description
*/
@Override
public String getClassJavadoc(Class<?> cl) {
ClassJavadoc classJavadoc = RuntimeJavadoc.getJavadoc(cl);
return formatter.format(classJavadoc.getComment());
}
/**
* Gets param descripton of record class.
*
* @param cl the class
* @return map of field and param descriptions
*/
@Override
public Map<String, String> getRecordClassParamJavadoc(Class<?> cl) {
ClassJavadoc classJavadoc = RuntimeJavadoc.getJavadoc(cl);
return classJavadoc.getRecordComponents().stream()
.collect(Collectors.toMap(ParamJavadoc::getName, recordClass -> formatter.format(recordClass.getComment())));
}
/**
* Gets method javadoc description.
*
* @param method the method
* @return the method javadoc description
*/
@Override
public String getMethodJavadocDescription(Method method) {
MethodJavadoc methodJavadoc = RuntimeJavadoc.getJavadoc(method);
return formatter.format(methodJavadoc.getComment());
}
/**
* Gets method javadoc return.
*
* @param method the method
* @return the method javadoc return
*/
@Override
public String getMethodJavadocReturn(Method method) {
MethodJavadoc methodJavadoc = RuntimeJavadoc.getJavadoc(method);
return formatter.format(methodJavadoc.getReturns());
}
/**
* Gets method throws declaration.
*
* @param method the method
* @return the method throws (name-description map)
*/
public Map<String, String> getMethodJavadocThrows(Method method) {
return RuntimeJavadoc.getJavadoc(method)
.getThrows()
.stream()
.collect(toMap(ThrowsJavadoc::getName, javadoc -> formatter.format(javadoc.getComment())));
}
/**
* Gets param javadoc.
*
* @param method the method
* @param name the name
* @return the param javadoc
*/
@Override
public String getParamJavadoc(Method method, String name) {
MethodJavadoc methodJavadoc = RuntimeJavadoc.getJavadoc(method);
List<ParamJavadoc> paramsDoc = methodJavadoc.getParams();
return paramsDoc.stream().filter(paramJavadoc1 -> name.equals(paramJavadoc1.getName())).findAny()
.map(paramJavadoc1 -> formatter.format(paramJavadoc1.getComment())).orElse(null);
}
/**
* Gets field javadoc.
*
* @param field the field
* @return the field javadoc
*/
@Override
public String getFieldJavadoc(Field field) {
FieldJavadoc fieldJavadoc = RuntimeJavadoc.getJavadoc(field);
return formatter.format(fieldJavadoc.getComment());
}
@Override
public String getFirstSentence(String text) {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isEmpty(text)) {
return text;
}
int pOpenIndex = text.indexOf("<p>");
int pCloseIndex = text.indexOf("</p>");
int dotIndex = text.indexOf(".");
if (pOpenIndex != -1) {
if (pOpenIndex == 0 && pCloseIndex != -1) {
if (dotIndex != -1) {
return text.substring(3, min(pCloseIndex, dotIndex));
}
return text.substring(3, pCloseIndex);
}
if (dotIndex != -1) {
return text.substring(0, min(pOpenIndex, dotIndex));
}
return text.substring(0, pOpenIndex);
}
if (dotIndex != -1
&& text.length() != dotIndex + 1
&& Character.isWhitespace(text.charAt(dotIndex + 1))) {
return text.substring(0, dotIndex + 1);
}
return text;
| 882
| 266
| 1,148
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/providers/WebConversionServiceProvider.java
|
WebConversionServiceProvider
|
getSpringConvertedType
|
class WebConversionServiceProvider implements InitializingBean, ApplicationContextAware {
/**
* The constant CONVERTERS.
*/
private static final String CONVERTERS = "converters";
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WebConversionServiceProvider.class);
/**
* The constant SERVLET_APPLICATION_CONTEXT_CLASS.
*/
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
/**
* The constant REACTIVE_APPLICATION_CONTEXT_CLASS.
*/
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
/**
* The Formatting conversion service.
*/
private GenericConversionService formattingConversionService;
/**
* The Application context.
*/
private ApplicationContext applicationContext;
@Override
public void afterPropertiesSet() {
if (isAssignable(SERVLET_APPLICATION_CONTEXT_CLASS, this.applicationContext.getClass())) {
this.formattingConversionService = applicationContext.getBean("mvcConversionService", FormattingConversionService.class);
}
else if (isAssignable(REACTIVE_APPLICATION_CONTEXT_CLASS, this.applicationContext.getClass())) {
this.formattingConversionService = applicationContext.getBean("webFluxConversionService", FormattingConversionService.class);
}
else
formattingConversionService = new DefaultFormattingConversionService();
}
/**
* Attempts to convert {@code source} into the target type as described by {@code targetTypeDescriptor}.
*
* @param source the source
* @param targetTypeDescriptor the target type descriptor
* @return the converted source
*/
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor targetTypeDescriptor) {
return formattingConversionService.convert(source, targetTypeDescriptor);
}
/**
* Gets spring converted type.
*
* @param clazz the clazz
* @return the spring converted type
*/
public Class<?> getSpringConvertedType(Class<?> clazz) {<FILL_FUNCTION_BODY>}
/**
* Is assignable boolean.
*
* @param target the target
* @param type the type
* @return the boolean
*/
private boolean isAssignable(String target, Class<?> type) {
try {
return ClassUtils.resolveClassName(target, null).isAssignableFrom(type);
}
catch (Throwable ex) {
return false;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
Class<?> result = clazz;
Field convertersField = FieldUtils.getDeclaredField(GenericConversionService.class, CONVERTERS, true);
if (convertersField != null) {
Object converters;
if (!AopUtils.isAopProxy(formattingConversionService)){
try {
converters = convertersField.get(formattingConversionService);
convertersField = FieldUtils.getDeclaredField(converters.getClass(), CONVERTERS, true);
Map<ConvertiblePair, Object> springConverters = (Map) convertersField.get(converters);
Optional<ConvertiblePair> convertiblePairOptional = springConverters.keySet().stream().filter(convertiblePair -> convertiblePair.getTargetType().equals(clazz)).findAny();
if (convertiblePairOptional.isPresent()) {
ConvertiblePair convertiblePair = convertiblePairOptional.get();
result = convertiblePair.getSourceType();
}
}
catch (IllegalAccessException e) {
LOGGER.warn(e.getMessage());
}
}
}
return result;
| 728
| 301
| 1,029
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/utils/PropertyResolverUtils.java
|
PropertyResolverUtils
|
resolve
|
class PropertyResolverUtils {
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(PropertyResolverUtils.class);
/**
* The Factory.
*/
private final ConfigurableBeanFactory factory;
/**
* The Message source.
*/
private final MessageSource messageSource;
/**
* The Spring doc config properties.
*/
private final SpringDocConfigProperties springDocConfigProperties;
/**
* Instantiates a new Property resolver utils.
*
* @param factory the factory
* @param messageSource the message source
* @param springDocConfigProperties the spring doc config properties
*/
public PropertyResolverUtils(ConfigurableBeanFactory factory, MessageSource messageSource, SpringDocConfigProperties springDocConfigProperties) {
this.factory = factory;
this.messageSource = messageSource;
this.springDocConfigProperties = springDocConfigProperties;
}
/**
* Resolve string.
*
* @param parameterProperty the parameter property
* @param locale the locale
* @return the string
*/
public String resolve(String parameterProperty, Locale locale) {<FILL_FUNCTION_BODY>}
/**
* Returns a string where all leading indentation has been removed from each line.
* It detects the smallest common indentation of all the lines in the input string,
* and removes it.
*
* @param text The original string with possible leading indentation.
* @return The string with leading indentation removed from each line.
*/
private String trimIndent(String text) {
if (text == null) {
return null;
}
final String newLine = "\n";
String[] lines = text.split(newLine);
int minIndent = resolveMinIndent(lines);
return Arrays.stream(lines)
.map(line -> line.substring(Math.min(line.length(), minIndent)))
.reduce((a, b) -> a + newLine + b)
.orElse(StringUtils.EMPTY);
}
private int resolveMinIndent(String[] lines) {
return Arrays.stream(lines)
.filter(line -> !line.trim().isEmpty())
.mapToInt(this::countLeadingSpaces)
.min()
.orElse(0);
}
private int countLeadingSpaces(String line) {
int count = 0;
for (char ch : line.toCharArray()) {
if (ch != ' ') break;
count++;
}
return count;
}
/**
* Gets factory.
*
* @return the factory
*/
public ConfigurableBeanFactory getFactory() {
return factory;
}
/**
* Gets spring doc config properties.
*
* @return the spring doc config properties
*/
public SpringDocConfigProperties getSpringDocConfigProperties() {
return springDocConfigProperties;
}
/**
* Gets spec version.
*
* @return the spec version
*/
public SpecVersion getSpecVersion() {
return springDocConfigProperties.getSpecVersion();
}
/**
* Is openapi 31 boolean.
*
* @return the boolean
*/
public boolean isOpenapi31() {
return springDocConfigProperties.isOpenapi31();
}
/**
* Is resolve extensions properties boolean.
*
* @return the boolean
*/
public boolean isResolveExtensionsProperties() {
return springDocConfigProperties.getApiDocs().isResolveExtensionsProperties();
}
/**
* Resolve extensions map.
*
* @param locale the locale
* @param extensions the extensions
* @return the map
*/
public Map<String, Object> resolveExtensions(Locale locale, Map<String, Object> extensions) {
if (!CollectionUtils.isEmpty(extensions)) {
Map<String, Object> extensionsResolved = new HashMap<>();
extensions.forEach((key, value) -> {
String keyResolved = resolve(key, locale);
if (value instanceof HashMap<?, ?>) {
Map<String, Object> valueResolved = new HashMap<>();
((HashMap<?, ?>) value).forEach((key1, value1) -> {
String key1Resolved = resolve(key1.toString(), locale);
String value1Resolved = resolve(value1.toString(), locale);
valueResolved.put(key1Resolved, value1Resolved);
});
extensionsResolved.put(keyResolved, valueResolved);
}
else
extensionsResolved.put(keyResolved, value);
});
return extensionsResolved;
}
else
return extensions;
}
}
|
String result = parameterProperty;
if (parameterProperty != null) {
if (!springDocConfigProperties.isDisableI18n())
try {
result = messageSource.getMessage(parameterProperty, null, locale);
}
catch (NoSuchMessageException ex) {
LOGGER.trace(ex.getMessage());
}
if (parameterProperty.equals(result))
try {
if (springDocConfigProperties.isTrimKotlinIndent()) {
parameterProperty = trimIndent(parameterProperty);
}
result = factory.resolveEmbeddedValue(parameterProperty);
}
catch (IllegalArgumentException ex) {
LOGGER.warn(ex.getMessage());
}
}
return result;
| 1,205
| 195
| 1,400
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/ui/AbstractSwaggerResourceResolver.java
|
AbstractSwaggerResourceResolver
|
findWebJarResourcePath
|
class AbstractSwaggerResourceResolver {
/**
* The Swagger ui config properties.
*/
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
/**
* Instantiates a new Web jars version resource resolver.
*
* @param swaggerUiConfigProperties the swagger ui config properties
*/
public AbstractSwaggerResourceResolver(SwaggerUiConfigProperties swaggerUiConfigProperties) {
this.swaggerUiConfigProperties = swaggerUiConfigProperties;
}
/**
* Find web jar resource path string.
*
* @param pathStr the path
* @return the string
*/
@Nullable
protected String findWebJarResourcePath(String pathStr) {<FILL_FUNCTION_BODY>}
}
|
Path path = Paths.get(pathStr);
if (path.getNameCount() < 2) return null;
String version = swaggerUiConfigProperties.getVersion();
if (version == null) return null;
Path first = path.getName(0);
Path rest = path.subpath(1, path.getNameCount());
return first.resolve(version).resolve(rest).toString();
| 194
| 103
| 297
|
<no_super_class>
|
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-common/src/main/java/org/springdoc/ui/AbstractSwaggerWelcome.java
|
AbstractSwaggerWelcome
|
buildConfigUrl
|
class AbstractSwaggerWelcome {
/**
* The Swagger ui configuration.
*/
protected final SwaggerUiConfigProperties swaggerUiConfig;
/**
* The Spring doc config properties.
*/
protected final SpringDocConfigProperties springDocConfigProperties;
/**
* The Swagger ui calculated config.
*/
protected final SwaggerUiConfigParameters swaggerUiConfigParameters;
/**
* The Swagger config url.
*/
protected String swaggerConfigUrl;
/**
* The Api docs url.
*/
protected String apiDocsUrl;
/**
* The Context path.
*/
protected String contextPath;
/**
* Instantiates a new Abstract swagger welcome.
*
* @param swaggerUiConfig the swagger ui config
* @param springDocConfigProperties the spring doc config properties
* @param swaggerUiConfigParameters the swagger ui config parameters
*/
public AbstractSwaggerWelcome(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters) {
this.swaggerUiConfig = swaggerUiConfig;
this.springDocConfigProperties = springDocConfigProperties;
this.swaggerUiConfigParameters = swaggerUiConfigParameters;
}
/**
* Init.
*/
protected void init() {
springDocConfigProperties.getGroupConfigs().forEach(groupConfig -> swaggerUiConfigParameters.addGroup(groupConfig.getGroup(), groupConfig.getDisplayName()));
calculateUiRootPath();
}
/**
* Build url string.
*
* @param contextPath the context path
* @param docsUrl the docs url
* @return the string
*/
protected String buildUrl(String contextPath, String docsUrl) {
if (contextPath.endsWith(DEFAULT_PATH_SEPARATOR)) {
return contextPath.substring(0, contextPath.length() - 1) + docsUrl;
}
if (!docsUrl.startsWith(DEFAULT_PATH_SEPARATOR))
docsUrl = DEFAULT_PATH_SEPARATOR + docsUrl;
return contextPath + docsUrl;
}
/**
* Build config url.
*
* @param uriComponentsBuilder the uri components builder
*/
protected void buildConfigUrl(UriComponentsBuilder uriComponentsBuilder) {<FILL_FUNCTION_BODY>}
/**
* Build swagger ui url string.
*
* @param swaggerUiUrl the swagger ui url
* @return the string
*/
protected abstract String buildUrlWithContextPath(String swaggerUiUrl);
/**
* Gets uri components builder.
*
* @param sbUrl the sb url
* @return the uri components builder
*/
protected UriComponentsBuilder getUriComponentsBuilder(String sbUrl) {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(sbUrl);
if ((swaggerUiConfig.getQueryConfigEnabled() != null && swaggerUiConfig.getQueryConfigEnabled())) {
swaggerUiConfigParameters.getConfigParameters().entrySet().stream()
.filter(entry -> !SwaggerUiConfigParameters.CONFIG_URL_PROPERTY.equals(entry.getKey()))
.filter(entry -> !SwaggerUiConfigParameters.OAUTH2_REDIRECT_URL_PROPERTY.equals(entry.getKey()))
.filter(entry -> !SwaggerUiConfigParameters.URL_PROPERTY.equals(entry.getKey()))
.filter(entry -> !entry.getKey().startsWith(SwaggerUiConfigParameters.URLS_PROPERTY))
.filter(entry -> (entry.getValue() instanceof String) ? StringUtils.isNotEmpty((String) entry.getValue()) : entry.getValue() != null)
.forEach(entry -> uriBuilder.queryParam(entry.getKey(), entry.getValue()));
uriBuilder.queryParam(SwaggerUiConfigParameters.CONFIG_URL_PROPERTY, swaggerUiConfigParameters.getConfigUrl());
}
return uriBuilder;
}
/**
* Calculate oauth 2 redirect url.
*
* @param uriComponentsBuilder the uri components builder
*/
protected abstract void calculateOauth2RedirectUrl(UriComponentsBuilder uriComponentsBuilder);
/**
* Calculate ui root path.
*
* @param sbUrls the sb urls
*/
protected abstract void calculateUiRootPath(StringBuilder... sbUrls);
/**
* Calculate ui root common.
*
* @param sbUrl the sb url
* @param sbUrls the sb urls
*/
protected void calculateUiRootCommon(StringBuilder sbUrl, StringBuilder[] sbUrls) {
if (ArrayUtils.isNotEmpty(sbUrls))
sbUrl = sbUrls[0];
String swaggerPath = swaggerUiConfigParameters.getPath();
if (swaggerPath.contains(DEFAULT_PATH_SEPARATOR))
sbUrl.append(swaggerPath, 0, swaggerPath.lastIndexOf(DEFAULT_PATH_SEPARATOR));
swaggerUiConfigParameters.setUiRootPath(sbUrl.toString());
}
/**
* Build api doc url string.
*
* @return the string
*/
protected abstract String buildApiDocUrl();
/**
* Build swagger config url string.
*
* @return the string
*/
protected abstract String buildSwaggerConfigUrl();
/**
* Gets oauth2 redirect url.
*
* @return the oauth2 redirect url
*/
protected String getOauth2RedirectUrl() {
return StringUtils.defaultIfBlank(swaggerUiConfig.getOauth2RedirectUrl(), SWAGGER_UI_OAUTH_REDIRECT_URL);
}
/**
* Gets swagger ui url.
*
* @return the swagger ui url
*/
protected String getSwaggerUiUrl() {
return SWAGGER_UI_URL;
}
}
|
if (StringUtils.isEmpty(swaggerUiConfig.getConfigUrl())) {
apiDocsUrl = buildApiDocUrl();
swaggerConfigUrl = buildSwaggerConfigUrl();
swaggerUiConfigParameters.setConfigUrl(swaggerConfigUrl);
if (CollectionUtils.isEmpty(swaggerUiConfigParameters.getUrls())) {
String swaggerUiUrl = swaggerUiConfig.getUrl();
if (StringUtils.isEmpty(swaggerUiUrl))
swaggerUiConfigParameters.setUrl(apiDocsUrl);
else if (swaggerUiConfigParameters.isValidUrl(swaggerUiUrl))
swaggerUiConfigParameters.setUrl(swaggerUiUrl);
else
swaggerUiConfigParameters.setUrl(buildUrlWithContextPath(swaggerUiUrl));
}
else
swaggerUiConfigParameters.addUrl(apiDocsUrl);
if (!CollectionUtils.isEmpty(swaggerUiConfig.getUrls())) {
swaggerUiConfig.cloneUrls().forEach(swaggerUrl -> {
swaggerUiConfigParameters.getUrls().remove(swaggerUrl);
if (!swaggerUiConfigParameters.isValidUrl(swaggerUrl.getUrl()))
swaggerUrl.setUrl(buildUrlWithContextPath(swaggerUrl.getUrl()));
swaggerUiConfigParameters.getUrls().add(swaggerUrl);
});
}
}
calculateOauth2RedirectUrl(uriComponentsBuilder);
| 1,538
| 386
| 1,924
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.