Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code cleanup #1319

Merged
merged 2 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

// end::imports[]
// tag::clazz[]
@Controller("/")
@Controller
public class HelloController {

/**
Expand All @@ -20,4 +20,4 @@ public Mono<String> index(String name) {
return Mono.just("Hello " + name + "!");
}
}
// end::clazz[]
// end::clazz[]
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

// end::imports[]
// tag::clazz[]
@Controller("/")
@Controller
public class HelloController {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,7 @@ public void visit(DefinitionNode node) {
public void visit(ExpImageNode node) {
String text = printChildrenToString(node);
LinkRenderer.Rendering imageRenderer = linkRenderer.render(node, text);
Node linkNode;
if ((linkNode = findParentNode(node, rootNode)) instanceof ExpLinkNode expLinkNode) {
if (findParentNode(node, rootNode) instanceof ExpLinkNode expLinkNode) {
printImageTagWithLink(imageRenderer, linkRenderer.render(expLinkNode, null));
} else {
printImageTag(linkRenderer.render(node, text));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/
public class MediaTypeSerializer extends JsonSerializer<MediaType> implements ResolvableSerializer {

private JsonSerializer<Object> defaultSerializer;
private final JsonSerializer<Object> defaultSerializer;

public MediaTypeSerializer(JsonSerializer<Object> serializer) {
defaultSerializer = serializer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/
public class Schema31Serializer extends JsonSerializer<Schema> implements ResolvableSerializer {

private JsonSerializer<Object> defaultSerializer;
private final JsonSerializer<Object> defaultSerializer;

public Schema31Serializer(JsonSerializer<Object> serializer) {
defaultSerializer = serializer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/
public class SchemaSerializer extends JsonSerializer<Schema> implements ResolvableSerializer {

private JsonSerializer<Object> defaultSerializer;
private final JsonSerializer<Object> defaultSerializer;

public SchemaSerializer(JsonSerializer<Object> serializer) {
defaultSerializer = serializer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,31 +186,31 @@ public Schema createProperty() {
/**
* Allows to exclude specific classes from KEY_CLASSES mappings to primitive
*/
private static Set<String> customExcludedClasses = ConcurrentHashMap.newKeySet();
private static final Set<String> customExcludedClasses = ConcurrentHashMap.newKeySet();

/**
* Allows to exclude specific classes from EXTERNAL_CLASSES mappings to primitive
*/
private static Set<String> customExcludedExternalClasses = ConcurrentHashMap.newKeySet();
private static final Set<String> customExcludedExternalClasses = ConcurrentHashMap.newKeySet();


/**
* Adds support for custom mapping of classes to primitive types
*/
private static Map<String, PrimitiveType> customClasses = new ConcurrentHashMap<>();
private static final Map<String, PrimitiveType> customClasses = new ConcurrentHashMap<>();

/**
* class qualified names prefixes to be considered as "system" types
*/
private static Set<String> systemPrefixes = ConcurrentHashMap.newKeySet();
private static final Set<String> systemPrefixes = ConcurrentHashMap.newKeySet();
/**
* class qualified names NOT to be considered as "system" types
*/
private static Set<String> nonSystemTypes = ConcurrentHashMap.newKeySet();
private static final Set<String> nonSystemTypes = ConcurrentHashMap.newKeySet();
/**
* package names NOT to be considered as "system" types
*/
private static Set<String> nonSystemTypePackages = ConcurrentHashMap.newKeySet();
private static final Set<String> nonSystemTypePackages = ConcurrentHashMap.newKeySet();

/**
* Alternative names for primitive types that have to be supported for
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ public void processOpts() {

// Get boolean properties
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
useBeanValidation = convertPropertyToBoolean(USE_BEANVALIDATION);
}
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);

Expand All @@ -333,12 +333,12 @@ public void processOpts() {
writePropertyBack(OPT_GENERATED_ANNOTATION, generatedAnnotation);

if (additionalProperties.containsKey(USE_OPTIONAL)) {
setUseOptional(convertPropertyToBoolean(USE_OPTIONAL));
useOptional = convertPropertyToBoolean(USE_OPTIONAL);
}
writePropertyBack(USE_OPTIONAL, useOptional);

if (additionalProperties.containsKey(OPT_VISITABLE)) {
setVisitable(convertPropertyToBoolean(OPT_VISITABLE));
visitable = convertPropertyToBoolean(OPT_VISITABLE);
}
writePropertyBack(OPT_VISITABLE, visitable);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@

import io.micronaut.openapi.generator.MicronautCodeGeneratorOptionsBuilder.GeneratorLanguage;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.DefaultCodegen;

import static io.micronaut.openapi.generator.MicronautCodeGeneratorOptionsBuilder.GeneratorLanguage.JAVA;
import static io.micronaut.openapi.generator.MicronautCodeGeneratorOptionsBuilder.GeneratorLanguage.KOTLIN;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public static void assertFileContains(Path path, String... lines) {
}

public static String linearize(String target) {
return target.replaceAll("\r?\n", "").replaceAll("\\s+", "\\s");
return target.replaceAll("\r?\n", "").replaceAll("\\s+", "s");
}

public static void assertFileNotContains(Path path, String... lines) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public class JavadocDescription {

private String methodSummary;
private String methodDescription;
private Map<String, String> parameters = new HashMap<>(4);
private String returnDescription;
private final Map<String, String> parameters = new HashMap<>(4);

/**
* @return method summary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
package io.micronaut.openapi.postprocessors;

import java.util.HashMap;
import java.util.Map;

import io.micronaut.core.util.CollectionUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;

Expand All @@ -29,39 +29,43 @@ public class OpenApiOperationsPostProcessor {
/**
* Process operations, making operation ids unique.
*
* @param openAPI OpenApi object with all definitions
* @param openApi OpenApi object with all definitions
*/
public void processOperations(OpenAPI openAPI) {
if (openAPI.getPaths() == null) {
public void processOperations(OpenAPI openApi) {
if (CollectionUtils.isEmpty(openApi.getPaths())) {
return;
}

Map<String, Integer> operationIdsIndex = new HashMap<>();
var operationIdsIndex = new HashMap<String, Integer>();

openAPI.getPaths().values().stream()
.flatMap(pathItem -> pathItem.readOperations().stream())
.forEach(operation -> {
for (var pathItem : openApi.getPaths().values()) {
for (var operation : pathItem.readOperations()) {
String operationId = operation.getOperationId();

if (operationIdsIndex.containsKey(operationId)) {
int nextValue = operationIdsIndex.get(operationId);

String newOperationId = operationId + '_' + nextValue;
operation.setOperationId(newOperationId);
updateResponseDescription(operation, operationId, newOperationId);

operationIdsIndex.put(operationId, ++nextValue);
} else {
if (!operationIdsIndex.containsKey(operationId)) {
operationIdsIndex.put(operationId, 1);
continue;
}
});
int nextValue = operationIdsIndex.get(operationId);

String newOperationId = operationId + '_' + nextValue;
operation.setOperationId(newOperationId);
updateResponseDescription(operation, operationId, newOperationId);

operationIdsIndex.put(operationId, ++nextValue);
}
}
}

private static void updateResponseDescription(Operation operation, String originalId, String newOperationId) {
if (operation.getResponses() != null) {
operation.getResponses().values().stream()
.filter(apiResponse -> apiResponse != null && apiResponse.getDescription() != null)
.forEach(apiResponse -> apiResponse.setDescription(apiResponse.getDescription().replaceFirst(originalId, newOperationId)));
if (CollectionUtils.isEmpty(operation.getResponses())) {
return;
}
for (var apiResponse : operation.getResponses().values()) {
if (apiResponse == null || apiResponse.getDescription() == null) {
continue;
}
apiResponse.setDescription(apiResponse.getDescription().replaceFirst(originalId, newOperationId));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ private void render(AbstractViewConfig cfg, Path outputDir, String templateName,

template = cfg.render(template, context);
template = replacePlaceHolder(template, "specURL", getSpecURL(cfg, context), "");
template = replacePlaceHolder(template, "title", getTitle(), "");
template = replacePlaceHolder(template, "title", title, "");
if (!Files.exists(outputDir)) {
Files.createDirectories(outputDir);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1978,8 +1978,6 @@ private Schema<?> getSchemaDefinition(OpenAPI openAPI,
if (schema != null) {
processSuperTypes(schema, schemaName, type, definingElement, openAPI, mediaTypes, schemas, context, jsonViewClass);
}
} catch (JsonProcessingException e) {
context.warn("Error reading Swagger Parameter for element [" + type + "]: " + e.getMessage(), type);
} finally {
inProgressSchemas.remove(schemaName);
}
Expand Down Expand Up @@ -2176,13 +2174,11 @@ private void processClassValues(Schema<?> schemaToBind, Map<CharSequence, Object
* @param jsonViewClass Class from JsonView annotation
*
* @return New schema instance
*
* @throws JsonProcessingException when Json parsing fails
*/
@SuppressWarnings("java:S3776")
protected Schema<?> readSchema(AnnotationValue<io.swagger.v3.oas.annotations.media.Schema> schemaValue, OpenAPI openAPI, VisitorContext context,
@Nullable Element type, Map<String, ClassElement> typeArgs, List<MediaType> mediaTypes,
@Nullable ClassElement jsonViewClass) throws JsonProcessingException {
@Nullable ClassElement jsonViewClass) {
Map<CharSequence, Object> values = schemaValue.getValues()
.entrySet()
.stream()
Expand Down Expand Up @@ -2361,7 +2357,7 @@ private String addTypeArgsAnnotations(String memberName, Object annValue) {
var annName = aValue.getAnnotationName();
var values = ((Map<String, Object>) aValue.getValues());
var endPos = annName.contains("$") ? annName.lastIndexOf('$') : annName.length();
result.append(annName.substring(annName.lastIndexOf('.') + 1, endPos));
result.append(annName, annName.lastIndexOf('.') + 1, endPos);
if (CollectionUtils.isNotEmpty(values)) {
result.append('_');
for (var entry : values.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,5 +103,5 @@ public interface ContextProperty {
/**
* Calculated class output directory path.
*/
String MICRONAUT_INTERNAL_CLASSPATH_OUTPUT = "micronaut.internal.classpath.ouptut";
String MICRONAUT_INTERNAL_CLASSPATH_OUTPUT = "micronaut.internal.classpath.output";
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public static GeneratedFile visitMetaInfFile(String path, VisitorContext context
count++;
}
}
// now this is classesOutputDir, parent of META-INF direcory
// now this is classesOutputDir, parent of META-INF directory
generatedFilePath = generatedFilePath.getParent();

context.put(MICRONAUT_INTERNAL_CLASSPATH_OUTPUT, generatedFilePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import io.micronaut.inject.ast.ClassElement;
import io.swagger.v3.oas.models.security.SecurityRequirement;
Expand All @@ -31,7 +30,7 @@
*/
class Endpoint {

private Optional<ClassElement> element;
private ClassElement element;
private List<Tag> tags = Collections.emptyList();
private List<Server> servers = Collections.emptyList();
private List<SecurityRequirement> securityRequirements = Collections.emptyList();
Expand All @@ -41,7 +40,7 @@ class Endpoint {
*
* @param element A ClassElement,
*/
void setClassElement(Optional<ClassElement> element) {
void setClassElement(ClassElement element) {
this.element = element;
}

Expand All @@ -59,7 +58,7 @@ void setTags(List<Tag> tags) {
*
* @return A ClassElement.
*/
Optional<ClassElement> getClassElement() {
ClassElement getClassElement() {
return element;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public class EndpointsConfiguration {
case "security-requirements" -> endpoint.setSecurityRequirements(parseSecurityRequirements(entry.getValue(), context));
case "servers" -> endpoint.setServers(parseServers(entry.getValue(), context));
case "tags" -> endpoint.setTags(parseTags(entry.getValue()));
case "class" -> endpoint.setClassElement(context.getClassElement(entry.getValue()));
case "class" -> endpoint.setClassElement(context.getClassElement(entry.getValue()).orElse(null));
default -> context.warn("Unknown value " + entryType, null);
}
});
Expand Down
Loading
Loading