Skip to content

Commit

Permalink
Merge branch 'master' into support-status-code-errors
Browse files Browse the repository at this point in the history
  • Loading branch information
TharmiganK authored Feb 14, 2024
2 parents 71eb56e + 2245a6a commit 5ec92e5
Show file tree
Hide file tree
Showing 36 changed files with 1,463 additions and 144 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -174,26 +174,19 @@ private void addPathItem(String httpMethod, Paths path, Operation operation, Str
*
* @return Operation Adaptor object of given resource
*/
private Optional<OperationInventory> convertResourceToOperation(FunctionDefinitionNode resource, String httpMethod,
String generateRelativePath,
private Optional<OperationInventory> convertResourceToOperation(FunctionDefinitionNode resourceFunction,
String httpMethod, String generateRelativePath,
Components components) {
OperationInventory operationInventory = new OperationInventory();
operationInventory.setHttpOperation(httpMethod);
operationInventory.setPath(generateRelativePath);
/* Set operation id */
String resName = (resource.functionName().text() + "_" +
generateRelativePath).replaceAll("\\{///}", "_");

if (generateRelativePath.equals("/")) {
resName = resource.functionName().text();
}
operationInventory.setOperationId(getOperationId(resName));
operationInventory.setOperationId(getOperationId(resourceFunction));
// Set operation summary
// Map API documentation
Map<String, String> apiDocs = listAPIDocumentations(resource, operationInventory);
Map<String, String> apiDocs = listAPIDocumentations(resourceFunction, operationInventory);
//Add path parameters if in path and query parameters
ParameterMapper parameterMapper = new ParameterMapperImpl(resource, operationInventory, components, apiDocs,
additionalData, treatNilableAsOptional);
ParameterMapper parameterMapper = new ParameterMapperImpl(resourceFunction, operationInventory, components,
apiDocs, additionalData, treatNilableAsOptional);
parameterMapper.setParameters();
List<OpenAPIMapperDiagnostic> diagnostics = additionalData.diagnostics();
if (diagnostics.size() > 1 || (diagnostics.size() == 1 && !diagnostics.get(0).getCode().equals(
Expand All @@ -207,7 +200,7 @@ private Optional<OperationInventory> convertResourceToOperation(FunctionDefiniti
}
}

ResponseMapper responseMapper = new ResponseMapperImpl(resource, operationInventory, components,
ResponseMapper responseMapper = new ResponseMapperImpl(resourceFunction, operationInventory, components,
additionalData);
responseMapper.setApiResponses();
return Optional.of(operationInventory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import io.ballerina.openapi.service.mapper.diagnostic.DiagnosticMessages;
import io.ballerina.openapi.service.mapper.diagnostic.ExceptionDiagnostic;
import io.ballerina.openapi.service.mapper.diagnostic.OpenAPIMapperDiagnostic;
import io.ballerina.openapi.service.mapper.hateoas.HateoasMapper;
import io.ballerina.openapi.service.mapper.hateoas.HateoasMapperImpl;
import io.ballerina.openapi.service.mapper.model.AdditionalData;
import io.ballerina.openapi.service.mapper.model.ModuleMemberVisitor;
import io.ballerina.openapi.service.mapper.model.OASGenerationMetaInfo;
Expand Down Expand Up @@ -209,6 +211,8 @@ public static OASResult generateOAS(OASGenerationMetaInfo oasGenerationMetaInfo)
ConstraintMapper constraintMapper = new ConstraintMapperImpl(openapi, moduleMemberVisitor,
diagnostics);
constraintMapper.setConstraints();
HateoasMapper hateoasMapper = new HateoasMapperImpl();
hateoasMapper.setOpenApiLinks(serviceDefinition, openapi);
return new OASResult(openapi, diagnostics);
} else {
return new OASResult(openapi, oasResult.getDiagnostics());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.openapi.service.mapper.constraint;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.openapi.service.mapper.hateoas;

public class Constants {

public static final String OPENAPI_LINK_DEFAULT_REL = "_self";
public static final String BALLERINA_LINKEDTO_KEYWORD = "linkedTo";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.openapi.service.mapper.hateoas;

public class HateoasLink {
private String resourceName;
private String relation;
private String resourceMethod;

public String getResourceName() {
return resourceName;
}

public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}

public String getRel() {
return relation;
}

public void setRel(String relation) {
this.relation = relation;
}

public String getResourceMethod() {
return resourceMethod;
}

public void setResourceMethod(String resourceMethod) {
this.resourceMethod = resourceMethod;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.openapi.service.mapper.hateoas;

import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode;
import io.swagger.v3.oas.models.OpenAPI;

/**
* This {@link HateoasMapper} uses to set HATEOAS links into the OpenAPI context.
*
* @since 1.9.0
*/
public interface HateoasMapper {

/**
* Sets HATEOAS links into the OpenAPI context.
*
* @param serviceNode Specific service declaration node
* @param openAPI Current OpenAPI context
*/
void setOpenApiLinks(ServiceDeclarationNode serviceNode, OpenAPI openAPI);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.openapi.service.mapper.hateoas;

import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode;
import io.ballerina.compiler.syntax.tree.Node;
import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode;
import io.ballerina.compiler.syntax.tree.SyntaxKind;
import io.ballerina.openapi.service.mapper.Constants;
import io.ballerina.openapi.service.mapper.utils.MapperCommonUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.links.Link;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

import static io.ballerina.openapi.service.mapper.hateoas.Constants.BALLERINA_LINKEDTO_KEYWORD;
import static io.ballerina.openapi.service.mapper.hateoas.Constants.OPENAPI_LINK_DEFAULT_REL;
import static io.ballerina.openapi.service.mapper.utils.MapperCommonUtils.generateRelativePath;
import static io.ballerina.openapi.service.mapper.utils.MapperCommonUtils.getResourceConfigAnnotation;
import static io.ballerina.openapi.service.mapper.utils.MapperCommonUtils.getValueForAnnotationFields;

/**
* This {@link HateoasMapperImpl} class represents the implementation of the {@link HateoasMapper}.
*
* @since 1.9.0
*/
public class HateoasMapperImpl implements HateoasMapper {

@Override
public void setOpenApiLinks(ServiceDeclarationNode serviceNode, OpenAPI openAPI) {
Paths paths = openAPI.getPaths();
Service hateoasService = extractHateoasMetaInfo(serviceNode);
for (Node node: serviceNode.members()) {
if (!node.kind().equals(SyntaxKind.RESOURCE_ACCESSOR_DEFINITION)) {
continue;
}
FunctionDefinitionNode resource = (FunctionDefinitionNode) node;
Optional<ApiResponses> responses = getApiResponsesForResource(resource, paths);
if (responses.isEmpty()) {
continue;
}
setOpenApiLinksInApiResponse(hateoasService, resource, responses.get());
}
}

private Service extractHateoasMetaInfo(ServiceDeclarationNode serviceNode) {
Service service = new Service();
for (Node child : serviceNode.children()) {
if (SyntaxKind.RESOURCE_ACCESSOR_DEFINITION.equals(child.kind())) {
FunctionDefinitionNode resourceFunction = (FunctionDefinitionNode) child;
String resourceMethod = resourceFunction.functionName().text();
String operationId = MapperCommonUtils.getOperationId(resourceFunction);
Optional<String> resourceName = getResourceConfigAnnotation(resourceFunction)
.flatMap(resourceConfig -> getValueForAnnotationFields(resourceConfig, "name"));
if (resourceName.isEmpty()) {
continue;
}
String cleanedResourceName = resourceName.get().replaceAll("\"", "");
Resource hateoasResource = new Resource(resourceMethod, operationId);
service.addResource(cleanedResourceName, hateoasResource);
}
}
return service;
}

private Optional<ApiResponses> getApiResponsesForResource(FunctionDefinitionNode resource, Paths paths) {
String resourcePath = MapperCommonUtils.unescapeIdentifier(generateRelativePath(resource));
if (!paths.containsKey(resourcePath)) {
return Optional.empty();
}
PathItem openApiResource = paths.get(resourcePath);
String httpMethod = resource.functionName().toString().trim();
ApiResponses responses = null;
switch (httpMethod.trim().toUpperCase(Locale.ENGLISH)) {
case Constants.GET -> {
responses = openApiResource.getGet().getResponses();
}
case Constants.PUT -> {
responses = openApiResource.getPut().getResponses();
}
case Constants.POST -> {
responses = openApiResource.getPost().getResponses();
}
case Constants.DELETE -> {
responses = openApiResource.getDelete().getResponses();
}
case Constants.OPTIONS -> {
responses = openApiResource.getOptions().getResponses();
}
case Constants.PATCH -> {
responses = openApiResource.getPatch().getResponses();
}
case Constants.HEAD -> {
responses = openApiResource.getHead().getResponses();
}
default -> { }
}
return Optional.ofNullable(responses);
}

private void setOpenApiLinksInApiResponse(Service hateoasService, FunctionDefinitionNode resource,
ApiResponses apiResponses) {
Map<String, Link> swaggerLinks = mapHateoasLinksToOpenApiLinks(hateoasService, resource);
if (swaggerLinks.isEmpty()) {
return;
}
for (Map.Entry<String, ApiResponse> entry : apiResponses.entrySet()) {
int statusCode = Integer.parseInt(entry.getKey());
if (statusCode >= 200 && statusCode < 300) {
entry.getValue().setLinks(swaggerLinks);
}
}
}

private List<HateoasLink> getLinks(String linkedTo) {
List<HateoasLink> links = new ArrayList<>();
String[] linkArray = linkedTo.replaceAll("[\\[\\]]", "").split("\\},\\s*");
for (String linkString : linkArray) {
HateoasLink link = parseHateoasLink(linkString);
links.add(link);
}
return links;
}

private HateoasLink parseHateoasLink(String input) {
HateoasLink hateoasLink = new HateoasLink();
HashMap<String, String> keyValueMap = new HashMap<>();
String[] keyValuePairs = input.replaceAll("[{}]", "").split(",\\s*");
for (String pair : keyValuePairs) {
String[] parts = pair.split(":\\s*");
if (parts.length != 2) {
continue;
}
String key = parts[0].trim();
String value = parts[1].replaceAll("\"", "").trim();
keyValueMap.put(key, value);
}
hateoasLink.setResourceName(keyValueMap.get("name"));
hateoasLink.setRel(keyValueMap.getOrDefault("relation", OPENAPI_LINK_DEFAULT_REL));
hateoasLink.setResourceMethod(keyValueMap.get("method"));
return hateoasLink;
}

private Map<String, Link> mapHateoasLinksToOpenApiLinks(Service hateoasService,
FunctionDefinitionNode resourceFunction) {
Optional<String> linkedTo = getResourceConfigAnnotation(resourceFunction)
.flatMap(resourceConfig -> getValueForAnnotationFields(resourceConfig, BALLERINA_LINKEDTO_KEYWORD));
if (linkedTo.isEmpty()) {
return Collections.emptyMap();
}
List<HateoasLink> links = getLinks(linkedTo.get());
Map<String, Link> hateoasLinks = new HashMap<>();
for (HateoasLink link : links) {
Optional<Resource> resource = hateoasService.getHateoasResourceMapping().entrySet().stream()
.filter(resources -> link.getResourceName().equals(resources.getKey()))
.findFirst()
.flatMap(hateoasResourceMapping -> hateoasResourceMapping.getValue().stream()
.filter(hateoasRes -> link.getResourceMethod().equals(hateoasRes.resourceMethod()))
.findFirst());
if (resource.isEmpty()) {
continue;
}
Link openapiLink = new Link();
String operationId = resource.get().operationId();
openapiLink.setOperationId(operationId);
hateoasLinks.put(link.getRel(), openapiLink);
}
return hateoasLinks;
}
}
Loading

0 comments on commit 5ec92e5

Please sign in to comment.