From 8d88455fb7773d887bf8caeb6b6ee6b34e413b56 Mon Sep 17 00:00:00 2001 From: thushalya Date: Tue, 2 May 2023 08:27:16 +0530 Subject: [PATCH] Try changing apicurio model to rc-2 for second time --- .../asyncapi/cli/BallerinaCodeGenerator.java | 19 +- .../asyncapi/core/GeneratorConstants.java | 14 +- .../asyncapi/core/GeneratorUtils.java | 2 +- .../client/BallerinaClientGenerator.java | 81 +- .../client/BallerinaUtilGenerator.java | 482 +++---- .../client/FunctionBodyGenerator.java | 1201 +++++++++-------- .../client/FunctionReturnTypeGenerator.java | 27 +- .../schema/BallerinaTypesGenerator.java | 51 +- .../generators/schema/TypeGeneratorUtils.java | 67 +- .../RecordTypeGenerator.java | 3 + .../TypeGenerator.java | 2 +- asyncapi-core/src/main/java/module-info.java | 1 + 12 files changed, 985 insertions(+), 965 deletions(-) diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cli/BallerinaCodeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cli/BallerinaCodeGenerator.java index ec86673c0..ee29381a2 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cli/BallerinaCodeGenerator.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cli/BallerinaCodeGenerator.java @@ -25,6 +25,7 @@ import io.ballerina.asyncapi.core.generators.client.BallerinaClientGenerator; import io.ballerina.asyncapi.core.generators.client.BallerinaTestGenerator; import io.ballerina.asyncapi.core.generators.client.model.AASClientConfig; +import io.ballerina.asyncapi.core.generators.schema.BallerinaTypesGenerator; //import io.ballerina.asyncapi.core.generators.schema.BallerinaTypesGenerator; import io.ballerina.asyncapi.core.model.GenSrcFile; import io.ballerina.compiler.syntax.tree.SyntaxTree; @@ -329,20 +330,20 @@ private List generateClientFiles(Path asyncAPI, boolean nullable) List preGeneratedTypeDefNodes = new ArrayList<>( ballerinaClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); preGeneratedTypeDefNodes.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList()); - // Generate ballerina records to represent schemas. -// BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( -// asyncAPIDef, nullable, preGeneratedTypeDefNodes); +// Generate ballerina records to represent schemas. + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPIDef, nullable, preGeneratedTypeDefNodes); -// SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); -// String schemaContent = Formatter.format(schemaSyntaxTree).toString(); + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + String schemaContent = Formatter.format(schemaSyntaxTree).toString(); // if (filter.getTags().size() > 0) { // // Remove unused records and enums when generating the client by the tags given. // schemaContent = GeneratorUtils.removeUnusedEntities(schemaSyntaxTree, mainContent, schemaContent, null); // } -// if (!schemaContent.isBlank()) { -// sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, -// schemaContent)); -// } + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, + schemaContent)); + } // Generate test boilerplate code for test cases if (this.includeTestFiles) { diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorConstants.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorConstants.java index c0c42f915..9a5ce5d74 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorConstants.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorConstants.java @@ -98,7 +98,8 @@ public String getValue() { public static final String CLIENT_CLASS = "Client"; public static final String CLIENT_EP = "clientEp"; public static final String EQUAL = "="; - public static final String CONFIG = "config"; + public static final String CLIENT_CONFIG = "clientConfig"; + public static final String CONFIG = "clientConfig"; public static final String FUNCTION = "function"; public static final String PREFIX_TEST = " test"; public static final String ANNOT_TEST = "test:Config"; @@ -154,7 +155,7 @@ public String getValue() { public static final String API_KEY_CONFIG_PARAM = "apiKeyConfig"; public static final String AUTH = "auth"; public static final String AUTH_CONFIG = "authConfig"; - public static final String WEBSOCKET_CLIENT_CONFIG = "websocketClientConfig"; + public static final String CLIENT_HTTP1_SETTINGS = "ClientHttp1Settings"; public static final String CLIENT_HTTP1_SETTINGS_FIELD = "http1Settings"; // public static final String HTTP2_SETTINGS = "http:Cookie"; @@ -167,7 +168,7 @@ public String getValue() { public static final String SECURE_SOCKET = "websocket:ClientSecureSocket"; public static final String SECURE_SOCKET_FIELD = "secureSocket"; - public static final String PING_PONG_SERVICE_FIELD= "PingPongService"; + public static final String PING_PONG_SERVICE_FIELD= "pingPongHandler"; public static final String WEB_SOCKET_RETRY_CONFIG = "websocket:WebSocketRetryConfig"; public static final String KEEP_ALIVE = "keepAlive"; @@ -177,7 +178,12 @@ public String getValue() { public static final String REFRESH_TOKEN = "refresh_token"; public static final String CLIENT_CRED = "client_cred"; public static final String PASSWORD = "password"; - public static final String CONNECTION_CONFIG = "ConnectionConfig"; + + public static final String REMOTE_METHOD_NAME_PREFIX ="do"; + +// public static final String CONNECTION_CONFIG = "ConnectionConfig"; + + public static final String CONNECTION_CONFIG = "websocket:ClientConfiguration"; public static final String OAUTH2 = "oauth2"; public static final String SSL_FIELD_NAME = "secureSocket"; public static final String RETRY_CONFIG_FIELD = "retryConfig"; diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorUtils.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorUtils.java index 11c470854..010f601d0 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorUtils.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/GeneratorUtils.java @@ -241,7 +241,7 @@ public static String convertAsyncAPITypeToBallerina(String type) throws Ballerin if (GeneratorConstants.TYPE_MAP.containsKey(type)) { return GeneratorConstants.TYPE_MAP.get(type); } else { - throw new BallerinaAsyncApiException("Unsupported OAS data type `" + type + "`"); + throw new BallerinaAsyncApiException("Unsupported AsyncAPI data type `" + type + "`"); } } diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaClientGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaClientGenerator.java index 9a7264e92..8f21f7873 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaClientGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaClientGenerator.java @@ -19,43 +19,13 @@ package io.ballerina.asyncapi.core.generators.client; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.TextNode; import io.apicurio.datamodels.models.ServerVariable; import io.apicurio.datamodels.models.asyncapi.AsyncApiMessage; import io.apicurio.datamodels.models.asyncapi.AsyncApiServer; import io.apicurio.datamodels.models.asyncapi.v25.*; import io.ballerina.asyncapi.core.exception.BallerinaAsyncApiException; import io.ballerina.asyncapi.core.generators.schema.BallerinaTypesGenerator; -import io.ballerina.compiler.syntax.tree.AnnotationNode; -import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; -import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; -import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; -import io.ballerina.compiler.syntax.tree.FunctionBodyNode; -import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; -import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; -import io.ballerina.compiler.syntax.tree.IdentifierToken; -import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; -import io.ballerina.compiler.syntax.tree.MarkdownDocumentationLineNode; -import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; -import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; -import io.ballerina.compiler.syntax.tree.MetadataNode; -import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; -import io.ballerina.compiler.syntax.tree.ModulePartNode; -import io.ballerina.compiler.syntax.tree.Node; -import io.ballerina.compiler.syntax.tree.NodeList; -import io.ballerina.compiler.syntax.tree.ObjectFieldNode; -import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.ParameterNode; -import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; -import io.ballerina.compiler.syntax.tree.ReturnStatementNode; -import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; -import io.ballerina.compiler.syntax.tree.SeparatedNodeList; -import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.StatementNode; -import io.ballerina.compiler.syntax.tree.SyntaxKind; -import io.ballerina.compiler.syntax.tree.SyntaxTree; -import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.*; import io.ballerina.asyncapi.core.GeneratorConstants; import io.ballerina.asyncapi.core.GeneratorUtils; import io.ballerina.asyncapi.core.generators.client.model.AASClientConfig; @@ -65,13 +35,10 @@ import io.ballerina.tools.text.TextDocuments; -import java.net.MalformedURLException; import java.net.URL; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; @@ -114,7 +81,6 @@ import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.REMOTE_KEYWORD; -import static io.ballerina.compiler.syntax.tree.SyntaxKind.RESOURCE_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURNS_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURN_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; @@ -189,7 +155,8 @@ public BallerinaClientGenerator(AASClientConfig AASClientConfig) { this.ballerinaUtilGenerator = new BallerinaUtilGenerator(); this.remoteFunctionNameList = new ArrayList<>(); this.serverURL = "/"; - this.ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(false, false); + this.ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(false, false , asyncAPI, + ballerinaUtilGenerator); this.resourceMode = AASClientConfig.isResourceMode(); } @@ -260,7 +227,6 @@ private ClassDefinitionNode getClassDefinitionNode() throws BallerinaAsyncApiExc String stringClassName= asyncAPI.getInfo().getTitle().trim()+ GeneratorUtils. removeNonAlphanumeric(asyncAPI.getChannels().getItemNames().get(0).trim())+"Client"; IdentifierToken className= createIdentifierToken(stringClassName); - //TODO: Change this name as extracting it from the title of the asyncapi document // IdentifierToken className = createIdentifierToken(GeneratorConstants.CLIENT_CLASS); NodeList classTypeQualifiers = createNodeList( createToken(ISOLATED_KEYWORD), createToken(CLIENT_KEYWORD)); @@ -323,12 +289,12 @@ private MetadataNode getClassMetadataNode() { * @throws BallerinaAsyncApiException When invalid server URL is provided */ private FunctionDefinitionNode createInitFunction() throws BallerinaAsyncApiException { - - FunctionSignatureNode functionSignatureNode = getInitFunctionSignatureNode(); + ArrayList initMetaDataDoc=new ArrayList(); + FunctionSignatureNode functionSignatureNode = getInitFunctionSignatureNode(initMetaDataDoc); FunctionBodyNode functionBodyNode = getInitFunctionBodyNode(); NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); IdentifierToken functionName = createIdentifierToken("init"); - return createFunctionDefinitionNode(null, getInitDocComment(), qualifierList, createToken(FUNCTION_KEYWORD), + return createFunctionDefinitionNode(null, getInitDocComment(initMetaDataDoc), qualifierList, createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), functionSignatureNode, functionBodyNode); } @@ -341,8 +307,8 @@ private FunctionBodyNode getInitFunctionBodyNode() { List assignmentNodes = new ArrayList<>(); - assignmentNodes.add(ballerinaAuthConfigGenerator.getWebsocketClientConfigVariableNode()); - assignmentNodes.add(ballerinaAuthConfigGenerator.getClientConfigDoStatementNode()); +// assignmentNodes.add(ballerinaAuthConfigGenerator.getWebsocketClientConfigVariableNode()); +// assignmentNodes.add(ballerinaAuthConfigGenerator.getClientConfigDoStatementNode()); // If both apiKey and httpOrOAuth is supported // todo : After revamping @@ -385,11 +351,11 @@ private FunctionBodyNode getInitFunctionBodyNode() { * @return {@link FunctionSignatureNode} * @throws BallerinaAsyncApiException When invalid server URL is provided */ - private FunctionSignatureNode getInitFunctionSignatureNode() throws BallerinaAsyncApiException { + private FunctionSignatureNode getInitFunctionSignatureNode(ArrayList initMetaDataNode) throws BallerinaAsyncApiException { serverURL = getServerURL((AsyncApi25ServersImpl) asyncAPI.getServers()); SeparatedNodeList parameterList = createSeparatedNodeList( - ballerinaAuthConfigGenerator.getConfigParamForClassInit(serverURL)); + ballerinaAuthConfigGenerator.getConfigParamForClassInit(serverURL,initMetaDataNode)); OptionalTypeDescriptorNode returnType = createOptionalTypeDescriptorNode(createToken(ERROR_KEYWORD), createToken(QUESTION_MARK_TOKEN)); ReturnTypeDescriptorNode returnTypeDescriptorNode = createReturnTypeDescriptorNode( @@ -403,9 +369,9 @@ private FunctionSignatureNode getInitFunctionSignatureNode() throws BallerinaAsy * * @return {@link MetadataNode} Metadata node containing entire function documentation comment. */ - private MetadataNode getInitDocComment() { + private MetadataNode getInitDocComment(ArrayList docs) { - List docs = new ArrayList<>(); +// List docs = new ArrayList<>(); String clientInitDocComment = "Gets invoked to initialize the `connector`.\n"; Map extensions = ((AsyncApi25InfoImpl)asyncAPI.getInfo()).getExtensions(); if (extensions != null && !extensions.isEmpty()) { @@ -484,7 +450,7 @@ private List createRemoteFunctions(Map createRemoteFunctions(Map // */ - private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(AsyncApi25MessageImpl message, + private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(Map.Entry message, Map extensions) throws BallerinaAsyncApiException { // Create api doc for function List remoteFunctionDocs = new ArrayList<>(); + AsyncApi25MessageImpl messageValue= (AsyncApi25MessageImpl) message.getValue(); + String messageName=message.getKey(); - if (message.getSummary() != null) { + if (messageValue.getSummary() != null) { remoteFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( - message.getSummary(), true)); - } else if (message.getDescription() != null && !message.getDescription().isBlank()) { + messageValue.getSummary(), true)); + } else if (messageValue.getDescription() != null && !messageValue.getDescription().isBlank()) { remoteFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( - message.getDescription(), true)); + messageValue.getDescription(), true)); } else { MarkdownDocumentationLineNode newLine = createMarkdownDocumentationLineNode(null, createToken(SyntaxKind.HASH_TOKEN), createEmptyNodeList()); @@ -567,14 +535,14 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(AsyncApi25 REMOTE_KEYWORD), createToken(ISOLATED_KEYWORD)); Token functionKeyWord = createToken(FUNCTION_KEYWORD); - IdentifierToken functionName = createIdentifierToken("do"+message.getName()); + IdentifierToken functionName = createIdentifierToken(REMOTE_METHOD_NAME_PREFIX +messageName); - remoteFunctionNameList.add(message.getName()); + remoteFunctionNameList.add(messageName); FunctionSignatureGenerator functionSignatureGenerator = new FunctionSignatureGenerator(asyncAPI, ballerinaSchemaGenerator, typeDefinitionNodeList, resourceMode); FunctionSignatureNode functionSignatureNode = - functionSignatureGenerator.getFunctionSignatureNode(message.getPayload(), + functionSignatureGenerator.getFunctionSignatureNode(messageValue.getPayload(), remoteFunctionDocs,extensions); typeDefinitionNodeList = functionSignatureGenerator.getTypeDefinitionNodeList(); // // Create `Deprecated` annotation if an operation has mentioned as `deprecated:true` @@ -583,6 +551,7 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(AsyncApi25 // remoteFunctionDocs, annotationNodes); // } // Create metadataNode add documentation string + List annotationNodes = new ArrayList<>(); MetadataNode metadataNode = createMetadataNode(createMarkdownDocumentationNode( createNodeList(remoteFunctionDocs)), createNodeList(annotationNodes)); @@ -590,7 +559,7 @@ private FunctionDefinitionNode getClientMethodFunctionDefinitionNode(AsyncApi25 // Create Function Body FunctionBodyGenerator functionBodyGenerator = new FunctionBodyGenerator(imports, typeDefinitionNodeList, asyncAPI, ballerinaSchemaGenerator, ballerinaAuthConfigGenerator, ballerinaUtilGenerator, resourceMode); - FunctionBodyNode functionBodyNode = functionBodyGenerator.getFunctionBodyNode(extensions); + FunctionBodyNode functionBodyNode = functionBodyGenerator.getFunctionBodyNode(extensions, ((RequiredParameterNode)functionSignatureNode.parameters().get(0)).paramName().get().toString()); imports = functionBodyGenerator.getImports(); //Generate relative path diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaUtilGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaUtilGenerator.java index 882d74fe6..97a3115c2 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaUtilGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/BallerinaUtilGenerator.java @@ -126,24 +126,24 @@ public class BallerinaUtilGenerator { private static final String CREATE_MULTIPART_BODY_PARTS = "createBodyParts"; /** - * Set `queryParamsFound` flag to `true` when at least one query parameter found. - * - * @param flag Function will be called only in the occasions where flag needs to be set to `true` - */ - public void setQueryParamsFound(boolean flag) { - this.queryParamsFound = flag; - } - - /** - * Set `headersFound` flag to `true` when at least one header found. - * - * @param flag Function will be called only in the occasions where flag needs to be set to `true` - */ - public void setHeadersFound(boolean flag) { - - this.headersFound = flag; - } - +// * Set `queryParamsFound` flag to `true` when at least one query parameter found. +// * +// * @param flag Function will be called only in the occasions where flag needs to be set to `true` +// */ +// public void setQueryParamsFound(boolean flag) { +// this.queryParamsFound = flag; +// } +// +// /** +// * Set `headersFound` flag to `true` when at least one header found. +// * +// * @param flag Function will be called only in the occasions where flag needs to be set to `true` +// */ +// public void setHeadersFound(boolean flag) { +// +// this.headersFound = flag; +// } +// /** * Set `pathParametersFound` flag to `true` when at least one path parameter found. * @@ -152,229 +152,229 @@ public void setHeadersFound(boolean flag) { public void setPathParametersFound(boolean flag) { this.pathParametersFound = flag; } - - /** - * Set `setRequestBodyEncodingFound` flag to `true` when at least one function found with URL-encoded request body. - * - * @param flag Function will be called only in the occasions where value needs to be set to `true`. - */ - public void setRequestBodyEncodingFound(boolean flag) { - this.requestBodyEncodingFound = flag; - } - - /** - * Set `setRequestBodyMultipartFormDatafound` flag to `true` when at least one function found with multipart - * form-data request body. - * - * @param flag Function will be called only in the occasions where value needs to be set to `true`. - */ - public void setRequestBodyMultipartFormDatafound(boolean flag) { - this.requestBodyMultipartFormDatafound = flag; - } - - /** - * Generates util file syntax tree. - * - * @return Syntax tree of the util.bal file - */ - public SyntaxTree generateUtilSyntaxTree() throws IOException { - Set functionNameList = new LinkedHashSet<>(); - if (requestBodyEncodingFound) { - functionNameList.addAll(Arrays.asList( - CREATE_FORM_URLENCODED_REQUEST_BODY, GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, - GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_SERIALIZED_RECORD_ARRAY - )); - } - if (queryParamsFound) { - functionNameList.addAll(Arrays.asList( - GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, - GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_PATH_FOR_QUERY_PARAM, - GET_SERIALIZED_RECORD_ARRAY - )); - } - if (headersFound) { - functionNameList.add(GET_MAP_FOR_HEADERS); - } - if (pathParametersFound) { - functionNameList.add(GET_ENCODED_URI); - } - if (requestBodyMultipartFormDatafound) { - functionNameList.add(CREATE_MULTIPART_BODY_PARTS); - } - - List memberDeclarationNodes = new ArrayList<>(); - getUtilTypeDeclarationNodes(memberDeclarationNodes); - - Path path = getResourceFilePath(); - - Project project = ProjectLoader.loadProject(path); - Package currentPackage = project.currentPackage(); - DocumentId docId = currentPackage.getDefaultModule().documentIds().iterator().next(); - SyntaxTree syntaxTree = currentPackage.getDefaultModule().document(docId).syntaxTree(); - - ModulePartNode modulePartNode = syntaxTree.rootNode(); - NodeList members = modulePartNode.members(); - for (ModuleMemberDeclarationNode node : members) { - if (node.kind().equals(SyntaxKind.FUNCTION_DEFINITION)) { - for (ChildNodeEntry childNodeEntry : node.childEntries()) { - if (childNodeEntry.name().equals("functionName")) { - if (functionNameList.contains(childNodeEntry.node().get().toString())) { - memberDeclarationNodes.add(node); - } - } - } - } - } - - List imports = new ArrayList<>(); - if (functionNameList.contains(GET_ENCODED_URI)) { - ImportDeclarationNode importForUrl = GeneratorUtils.getImportDeclarationNode(BALLERINA, URL); - imports.add(importForUrl); - } - if (requestBodyMultipartFormDatafound) { - ImportDeclarationNode importMime = GeneratorUtils.getImportDeclarationNode(BALLERINA, MIME); - imports.add(importMime); - } - - NodeList importsList = createNodeList(imports); - ModulePartNode utilModulePartNode = - createModulePartNode(importsList, createNodeList(memberDeclarationNodes), createToken(EOF_TOKEN)); - TextDocument textDocument = TextDocuments.from(""); - SyntaxTree utilSyntaxTree = SyntaxTree.from(textDocument); - return utilSyntaxTree.modifyWith(utilModulePartNode); - } - - /** - * Set the type definition nodes related to the util functions generated. - * - * @param memberDeclarationNodes {@link ModuleMemberDeclarationNode} - */ - private void getUtilTypeDeclarationNodes(List memberDeclarationNodes) { - if (requestBodyEncodingFound || queryParamsFound || headersFound || requestBodyMultipartFormDatafound) { - memberDeclarationNodes.add(getSimpleBasicTypeDefinitionNode()); - } - if (requestBodyEncodingFound || queryParamsFound || requestBodyMultipartFormDatafound) { - memberDeclarationNodes.addAll(Arrays.asList(getEncodingRecord(), getStyleEnum())); - } - if (requestBodyEncodingFound || queryParamsFound) { - memberDeclarationNodes.add(getDefaultEncoding()); - } - } - - /** - * Generates `Encoding` record. - *
-     *     # Represents encoding mechanism details.
-     *     type Encoding record {
-     *          # Defines how multiple values are delimited
-     *          string style = FORM;
-     *          # Specifies whether arrays and objects should generate separate parameters
-     *          boolean explode = true;
-     *      };
-     * 
- * - * @return {@link TypeDefinitionNode} - */ - private TypeDefinitionNode getEncodingRecord() { - // create `style` field - List styleDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( - "Defines how multiple values are delimited", false)); - MarkdownDocumentationNode styleDocumentationNode = createMarkdownDocumentationNode(createNodeList(styleDoc)); - MetadataNode styleMetadataNode = createMetadataNode(styleDocumentationNode, createEmptyNodeList()); - ExpressionNode styleExpressionNode = createRequiredExpressionNode(createIdentifierToken(FORM)); - RecordFieldWithDefaultValueNode styleFieldNode = createRecordFieldWithDefaultValueNode(styleMetadataNode, - null, createToken(STRING_KEYWORD), createIdentifierToken(STYLE), - createToken(EQUAL_TOKEN), styleExpressionNode, createToken(SEMICOLON_TOKEN)); - - // create `explode` field - List explodeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( - "Specifies whether arrays and objects should generate as separate fields", false)); - MarkdownDocumentationNode explodeDocumentationNode = createMarkdownDocumentationNode( - createNodeList(explodeDoc)); - MetadataNode explodeMetadataNode = createMetadataNode(explodeDocumentationNode, createEmptyNodeList()); - ExpressionNode explodeExpressionNode = createRequiredExpressionNode(createIdentifierToken("true")); - RecordFieldWithDefaultValueNode explodeFieldNode = createRecordFieldWithDefaultValueNode(explodeMetadataNode, - null, createToken(BOOLEAN_KEYWORD), createIdentifierToken(EXPLODE), - createToken(EQUAL_TOKEN), explodeExpressionNode, createToken(SEMICOLON_TOKEN)); - - // create `contentType` field - List contentTypeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( - "Specifies the custom content type", false)); - MarkdownDocumentationNode contentTypeDocumentationNode = createMarkdownDocumentationNode( - createNodeList(contentTypeDoc)); - MetadataNode contentTypeMetadataNode = createMetadataNode(contentTypeDocumentationNode, createEmptyNodeList()); - RecordFieldNode contentTypeFieldNode = createRecordFieldNode(contentTypeMetadataNode, - null, createToken(STRING_KEYWORD), createIdentifierToken("contentType"), - createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN)); - - // create `contentType` field - List headerDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( - "Specifies the custom headers", false)); - MarkdownDocumentationNode headerDocumentationNode = createMarkdownDocumentationNode(createNodeList(headerDoc)); - MetadataNode headerMetadataNode = createMetadataNode(headerDocumentationNode, createEmptyNodeList()); - RecordFieldNode headerFieldNode = createRecordFieldNode(headerMetadataNode, null, - createIdentifierToken("map"), createIdentifierToken("headers"), - createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN)); - - // Assemble the TypeDefinitionNode - List typeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( - "Represents encoding mechanism details.", false)); - MarkdownDocumentationNode typeDocumentationNode = createMarkdownDocumentationNode(createNodeList(typeDoc)); - MetadataNode typeMetadataNode = createMetadataNode(typeDocumentationNode, createEmptyNodeList()); - NodeList fieldNodes = createNodeList(styleFieldNode, explodeFieldNode, contentTypeFieldNode, - headerFieldNode); - TypeDescriptorNode typeDescriptorNode = createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), - createToken(OPEN_BRACE_TOKEN), fieldNodes, null, createToken(CLOSE_BRACE_TOKEN)); - return createTypeDefinitionNode(typeMetadataNode, null, createToken(TYPE_KEYWORD), - createIdentifierToken(ENCODING), typeDescriptorNode, createToken(SEMICOLON_TOKEN)); - } - - /** - * Generates `EncodingStyles` enum. - *
-     *     enum EncodingStyle {
-     *          DEEPOBJECT,
-     *          FORM,
-     *          SPACEDELIMITED,
-     *          PIPEDELIMITED
-     *     }
-     * 
- * - * @return {@link EnumDeclarationNode} - */ - private EnumDeclarationNode getStyleEnum() { - EnumMemberNode deepObject = createEnumMemberNode(null, - createIdentifierToken(DEEP_OBJECT), null, null); - EnumMemberNode form = createEnumMemberNode(null, - createIdentifierToken(FORM), null, null); - EnumMemberNode spaceDelimited = createEnumMemberNode(null, - createIdentifierToken(SPACE_DELIMITED), null, null); - EnumMemberNode pipeDelimited = createEnumMemberNode(null, - createIdentifierToken(PIPE_DELIMITED), null, null); - SeparatedNodeList enumMembers = createSeparatedNodeList(deepObject, createToken(COMMA_TOKEN), form, - createToken(COMMA_TOKEN), spaceDelimited, createToken(COMMA_TOKEN), pipeDelimited); - - return createEnumDeclarationNode(null, null, - createToken(ENUM_KEYWORD), createIdentifierToken(ENCODING_STYLE), createToken(OPEN_BRACE_TOKEN), - enumMembers, createToken(CLOSE_BRACE_TOKEN), null); - } - - /** - * Generates `SimpleBasicType` type. - *
-     *     type SimpleBasicType string|boolean|int|float|decimal;
-     * 
- * - * @return - */ - private TypeDefinitionNode getSimpleBasicTypeDefinitionNode() { - - TypeDescriptorNode typeDescriptorNode = createSingletonTypeDescriptorNode( - createSimpleNameReferenceNode(createIdentifierToken("string|boolean|int|float|decimal"))); - return createTypeDefinitionNode(null, null, - createToken(TYPE_KEYWORD), createIdentifierToken("SimpleBasicType"), typeDescriptorNode, - createToken(SEMICOLON_TOKEN)); - } +// +// /** +// * Set `setRequestBodyEncodingFound` flag to `true` when at least one function found with URL-encoded request body. +// * +// * @param flag Function will be called only in the occasions where value needs to be set to `true`. +// */ +// public void setRequestBodyEncodingFound(boolean flag) { +// this.requestBodyEncodingFound = flag; +// } +// +// /** +// * Set `setRequestBodyMultipartFormDatafound` flag to `true` when at least one function found with multipart +// * form-data request body. +// * +// * @param flag Function will be called only in the occasions where value needs to be set to `true`. +// */ +// public void setRequestBodyMultipartFormDatafound(boolean flag) { +// this.requestBodyMultipartFormDatafound = flag; +// } +// +// /** +// * Generates util file syntax tree. +// * +// * @return Syntax tree of the util.bal file +// */ +// public SyntaxTree generateUtilSyntaxTree() throws IOException { +// Set functionNameList = new LinkedHashSet<>(); +// if (requestBodyEncodingFound) { +// functionNameList.addAll(Arrays.asList( +// CREATE_FORM_URLENCODED_REQUEST_BODY, GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, +// GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_SERIALIZED_RECORD_ARRAY +// )); +// } +// if (queryParamsFound) { +// functionNameList.addAll(Arrays.asList( +// GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, +// GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_PATH_FOR_QUERY_PARAM, +// GET_SERIALIZED_RECORD_ARRAY +// )); +// } +// if (headersFound) { +// functionNameList.add(GET_MAP_FOR_HEADERS); +// } +// if (pathParametersFound) { +// functionNameList.add(GET_ENCODED_URI); +// } +// if (requestBodyMultipartFormDatafound) { +// functionNameList.add(CREATE_MULTIPART_BODY_PARTS); +// } +// +// List memberDeclarationNodes = new ArrayList<>(); +// getUtilTypeDeclarationNodes(memberDeclarationNodes); +// +// Path path = getResourceFilePath(); +// +// Project project = ProjectLoader.loadProject(path); +// Package currentPackage = project.currentPackage(); +// DocumentId docId = currentPackage.getDefaultModule().documentIds().iterator().next(); +// SyntaxTree syntaxTree = currentPackage.getDefaultModule().document(docId).syntaxTree(); +// +// ModulePartNode modulePartNode = syntaxTree.rootNode(); +// NodeList members = modulePartNode.members(); +// for (ModuleMemberDeclarationNode node : members) { +// if (node.kind().equals(SyntaxKind.FUNCTION_DEFINITION)) { +// for (ChildNodeEntry childNodeEntry : node.childEntries()) { +// if (childNodeEntry.name().equals("functionName")) { +// if (functionNameList.contains(childNodeEntry.node().get().toString())) { +// memberDeclarationNodes.add(node); +// } +// } +// } +// } +// } +// +// List imports = new ArrayList<>(); +// if (functionNameList.contains(GET_ENCODED_URI)) { +// ImportDeclarationNode importForUrl = GeneratorUtils.getImportDeclarationNode(BALLERINA, URL); +// imports.add(importForUrl); +// } +// if (requestBodyMultipartFormDatafound) { +// ImportDeclarationNode importMime = GeneratorUtils.getImportDeclarationNode(BALLERINA, MIME); +// imports.add(importMime); +// } +// +// NodeList importsList = createNodeList(imports); +// ModulePartNode utilModulePartNode = +// createModulePartNode(importsList, createNodeList(memberDeclarationNodes), createToken(EOF_TOKEN)); +// TextDocument textDocument = TextDocuments.from(""); +// SyntaxTree utilSyntaxTree = SyntaxTree.from(textDocument); +// return utilSyntaxTree.modifyWith(utilModulePartNode); +// } +// +// /** +// * Set the type definition nodes related to the util functions generated. +// * +// * @param memberDeclarationNodes {@link ModuleMemberDeclarationNode} +// */ +// private void getUtilTypeDeclarationNodes(List memberDeclarationNodes) { +// if (requestBodyEncodingFound || queryParamsFound || headersFound || requestBodyMultipartFormDatafound) { +// memberDeclarationNodes.add(getSimpleBasicTypeDefinitionNode()); +// } +// if (requestBodyEncodingFound || queryParamsFound || requestBodyMultipartFormDatafound) { +// memberDeclarationNodes.addAll(Arrays.asList(getEncodingRecord(), getStyleEnum())); +// } +//// if (requestBodyEncodingFound || queryParamsFound) { +//// memberDeclarationNodes.add(getDefaultEncoding()); +//// } +// } +// +// /** +// * Generates `Encoding` record. +// *
+//     *     # Represents encoding mechanism details.
+//     *     type Encoding record {
+//     *          # Defines how multiple values are delimited
+//     *          string style = FORM;
+//     *          # Specifies whether arrays and objects should generate separate parameters
+//     *          boolean explode = true;
+//     *      };
+//     * 
+// * +// * @return {@link TypeDefinitionNode} +// */ +// private TypeDefinitionNode getEncodingRecord() { +// // create `style` field +// List styleDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( +// "Defines how multiple values are delimited", false)); +// MarkdownDocumentationNode styleDocumentationNode = createMarkdownDocumentationNode(createNodeList(styleDoc)); +// MetadataNode styleMetadataNode = createMetadataNode(styleDocumentationNode, createEmptyNodeList()); +// ExpressionNode styleExpressionNode = createRequiredExpressionNode(createIdentifierToken(FORM)); +// RecordFieldWithDefaultValueNode styleFieldNode = createRecordFieldWithDefaultValueNode(styleMetadataNode, +// null, createToken(STRING_KEYWORD), createIdentifierToken(STYLE), +// createToken(EQUAL_TOKEN), styleExpressionNode, createToken(SEMICOLON_TOKEN)); +// +// // create `explode` field +// List explodeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( +// "Specifies whether arrays and objects should generate as separate fields", false)); +// MarkdownDocumentationNode explodeDocumentationNode = createMarkdownDocumentationNode( +// createNodeList(explodeDoc)); +// MetadataNode explodeMetadataNode = createMetadataNode(explodeDocumentationNode, createEmptyNodeList()); +// ExpressionNode explodeExpressionNode = createRequiredExpressionNode(createIdentifierToken("true")); +// RecordFieldWithDefaultValueNode explodeFieldNode = createRecordFieldWithDefaultValueNode(explodeMetadataNode, +// null, createToken(BOOLEAN_KEYWORD), createIdentifierToken(EXPLODE), +// createToken(EQUAL_TOKEN), explodeExpressionNode, createToken(SEMICOLON_TOKEN)); +// +// // create `contentType` field +// List contentTypeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( +// "Specifies the custom content type", false)); +// MarkdownDocumentationNode contentTypeDocumentationNode = createMarkdownDocumentationNode( +// createNodeList(contentTypeDoc)); +// MetadataNode contentTypeMetadataNode = createMetadataNode(contentTypeDocumentationNode, createEmptyNodeList()); +// RecordFieldNode contentTypeFieldNode = createRecordFieldNode(contentTypeMetadataNode, +// null, createToken(STRING_KEYWORD), createIdentifierToken("contentType"), +// createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN)); +// +// // create `contentType` field +// List headerDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( +// "Specifies the custom headers", false)); +// MarkdownDocumentationNode headerDocumentationNode = createMarkdownDocumentationNode(createNodeList(headerDoc)); +// MetadataNode headerMetadataNode = createMetadataNode(headerDocumentationNode, createEmptyNodeList()); +// RecordFieldNode headerFieldNode = createRecordFieldNode(headerMetadataNode, null, +// createIdentifierToken("map"), createIdentifierToken("headers"), +// createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN)); +// +// // Assemble the TypeDefinitionNode +// List typeDoc = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( +// "Represents encoding mechanism details.", false)); +// MarkdownDocumentationNode typeDocumentationNode = createMarkdownDocumentationNode(createNodeList(typeDoc)); +// MetadataNode typeMetadataNode = createMetadataNode(typeDocumentationNode, createEmptyNodeList()); +// NodeList fieldNodes = createNodeList(styleFieldNode, explodeFieldNode, contentTypeFieldNode, +// headerFieldNode); +// TypeDescriptorNode typeDescriptorNode = createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), +// createToken(OPEN_BRACE_TOKEN), fieldNodes, null, createToken(CLOSE_BRACE_TOKEN)); +// return createTypeDefinitionNode(typeMetadataNode, null, createToken(TYPE_KEYWORD), +// createIdentifierToken(ENCODING), typeDescriptorNode, createToken(SEMICOLON_TOKEN)); +// } +// +// /** +// * Generates `EncodingStyles` enum. +// *
+//     *     enum EncodingStyle {
+//     *          DEEPOBJECT,
+//     *          FORM,
+//     *          SPACEDELIMITED,
+//     *          PIPEDELIMITED
+//     *     }
+//     * 
+// * +// * @return {@link EnumDeclarationNode} +// */ +// private EnumDeclarationNode getStyleEnum() { +// EnumMemberNode deepObject = createEnumMemberNode(null, +// createIdentifierToken(DEEP_OBJECT), null, null); +// EnumMemberNode form = createEnumMemberNode(null, +// createIdentifierToken(FORM), null, null); +// EnumMemberNode spaceDelimited = createEnumMemberNode(null, +// createIdentifierToken(SPACE_DELIMITED), null, null); +// EnumMemberNode pipeDelimited = createEnumMemberNode(null, +// createIdentifierToken(PIPE_DELIMITED), null, null); +// SeparatedNodeList enumMembers = createSeparatedNodeList(deepObject, createToken(COMMA_TOKEN), form, +// createToken(COMMA_TOKEN), spaceDelimited, createToken(COMMA_TOKEN), pipeDelimited); +// +// return createEnumDeclarationNode(null, null, +// createToken(ENUM_KEYWORD), createIdentifierToken(ENCODING_STYLE), createToken(OPEN_BRACE_TOKEN), +// enumMembers, createToken(CLOSE_BRACE_TOKEN), null); +// } +// +// /** +// * Generates `SimpleBasicType` type. +// *
+//     *     type SimpleBasicType string|boolean|int|float|decimal;
+//     * 
+// * +// * @return +// */ +// private TypeDefinitionNode getSimpleBasicTypeDefinitionNode() { +// +// TypeDescriptorNode typeDescriptorNode = createSingletonTypeDescriptorNode( +// createSimpleNameReferenceNode(createIdentifierToken("string|boolean|int|float|decimal"))); +// return createTypeDefinitionNode(null, null, +// createToken(TYPE_KEYWORD), createIdentifierToken("SimpleBasicType"), typeDescriptorNode, +// createToken(SEMICOLON_TOKEN)); +// } // /** // * Generates `defaultEncoding` variable declaration node. diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionBodyGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionBodyGenerator.java index c39be666f..27bfdd70f 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionBodyGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionBodyGenerator.java @@ -24,29 +24,7 @@ import io.ballerina.asyncapi.core.GeneratorUtils; import io.ballerina.asyncapi.core.exception.BallerinaAsyncApiException; import io.ballerina.asyncapi.core.generators.schema.BallerinaTypesGenerator; -import io.ballerina.compiler.syntax.tree.AnnotationNode; -import io.ballerina.compiler.syntax.tree.BlockStatementNode; -import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; -import io.ballerina.compiler.syntax.tree.ExpressionNode; -import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; -import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; -import io.ballerina.compiler.syntax.tree.FunctionBodyNode; -import io.ballerina.compiler.syntax.tree.IdentifierToken; -import io.ballerina.compiler.syntax.tree.IfElseStatementNode; -import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; -import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; -import io.ballerina.compiler.syntax.tree.Node; -import io.ballerina.compiler.syntax.tree.NodeList; -import io.ballerina.compiler.syntax.tree.ReturnStatementNode; -import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; -import io.ballerina.compiler.syntax.tree.SpecificFieldNode; -import io.ballerina.compiler.syntax.tree.StatementNode; -import io.ballerina.compiler.syntax.tree.TemplateExpressionNode; -import io.ballerina.compiler.syntax.tree.Token; -import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; -import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; -import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; +import io.ballerina.compiler.syntax.tree.*; import java.util.ArrayList; import java.util.Iterator; @@ -68,21 +46,7 @@ import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBinaryExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBlockStatementNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldAccessExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionBodyBlockNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createIfElseStatementNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnStatementNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createSpecificFieldNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createTemplateExpressionNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; -import static io.ballerina.compiler.syntax.tree.NodeFactory.createVariableDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.*; import static io.ballerina.compiler.syntax.tree.SyntaxKind.BACKTICK_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; @@ -137,12 +101,12 @@ public FunctionBodyGenerator(List imports, List extenstions) + public FunctionBodyNode getFunctionBodyNode(Map extenstions,String paramName) throws BallerinaAsyncApiException { NodeList annotationNodes = createEmptyNodeList(); @@ -162,379 +126,448 @@ public FunctionBodyNode getFunctionBodyNode(Map extenstions) //TODO: move this //Handle query parameter map - handleParameterSchemaInOperation(operation, statementsList); +// handleParameterSchemaInOperation(operation, statementsList); - String method = operation.getKey().name().trim().toLowerCase(Locale.ENGLISH); +// String method = operation.getKey().name().trim().toLowerCase(Locale.ENGLISH); // This return type for target data type binding. String rType = functionReturnType.getReturnType(extenstions); String returnType = returnTypeForTargetTypeField(rType); // Statement Generator for requestBody - if (operation.getValue().getRequestBody() != null) { - RequestBody requestBody = operation.getValue().getRequestBody(); - handleRequestBodyInOperation(statementsList, method, returnType, requestBody); - } else { - createCommonFunctionBodyStatements(statementsList, method, returnType); - } +// if (operation.getValue().getRequestBody() != null) { +// RequestBody requestBody = operation.getValue().getRequestBody(); +// handleRequestBodyInOperation(statementsList, method, returnType, requestBody); +// } else { + createCommonFunctionBodyStatements(statementsList,paramName, returnType); +// } //Create statements NodeList statements = createNodeList(statementsList); return createFunctionBodyBlockNode(createToken(OPEN_BRACE_TOKEN), null, statements, createToken(CLOSE_BRACE_TOKEN), null); } - /** - * Generate statements for query parameters and headers. - */ - private void handleParameterSchemaInOperation(Map.Entry operation, - List statementsList) throws BallerinaOpenApiException { - - List queryApiKeyNameList = new ArrayList<>(); - List headerApiKeyNameList = new ArrayList<>(); - - Set securitySchemesAvailable = getSecurityRequirementForOperation(operation.getValue()); - - if (securitySchemesAvailable.size() > 0) { - Map queryApiKeyMap = ballerinaAuthConfigGenerator.getQueryApiKeyNameList(); - Map headerApiKeyMap = ballerinaAuthConfigGenerator.getHeaderApiKeyNameList(); - for (String schemaName : securitySchemesAvailable) { - if (queryApiKeyMap.containsKey(schemaName)) { - queryApiKeyNameList.add(queryApiKeyMap.get(schemaName)); - } else if (headerApiKeyMap.containsKey(schemaName)) { - headerApiKeyNameList.add(headerApiKeyMap.get(schemaName)); - } - } - } - - List queryParameters = new ArrayList<>(); - List headerParameters = new ArrayList<>(); - - if (operation.getValue().getParameters() != null) { - List parameters = operation.getValue().getParameters(); - for (Parameter parameter : parameters) { - if (parameter.getIn().trim().equals(QUERY)) { - queryParameters.add(parameter); - } else if (parameter.getIn().trim().equals(HEADER)) { - headerParameters.add(parameter); - } - } - } - handleQueryParamsAndHeaders(queryParameters, headerParameters, statementsList, queryApiKeyNameList, - headerApiKeyNameList); - } - - /** - * Handle query parameters and headers within a remote function. - */ - public void handleQueryParamsAndHeaders(List queryParameters, List headerParameters, - List statementsList, List queryApiKeyNameList, - List headerApiKeyNameList) throws BallerinaAsyncApiException { - - boolean combinationOfApiKeyAndHTTPOAuth = ballerinaAuthConfigGenerator.isHttpOROAuth() && - ballerinaAuthConfigGenerator.isHttpApiKey(); - if (combinationOfApiKeyAndHTTPOAuth) { - addUpdatedPathAndHeaders(statementsList, queryApiKeyNameList, queryParameters, - headerApiKeyNameList, headerParameters); - } else { - if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { - ballerinaUtilGenerator.setQueryParamsFound(true); - statementsList.add(getMapForParameters(queryParameters, "map", - QUERY_PARAM, queryApiKeyNameList)); - getUpdatedPathHandlingQueryParamEncoding(statementsList, queryParameters); - } - if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { - statementsList.add(getMapForParameters(headerParameters, "map", - HEADER_VALUES, headerApiKeyNameList)); - statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode( - "map " + HTTP_HEADERS + " = getMapForHeaders(headerValues)")); - isHeader = true; - ballerinaUtilGenerator.setHeadersFound(true); - } - } - } - - /** - * Generate statements for query parameters and headers when a client supports both ApiKey and HTTPOrOAuth - * authentication. - */ - private void addUpdatedPathAndHeaders(List statementsList, List queryApiKeyNameList, - List queryParameters, List headerApiKeyNameList, - List headerParameters) throws BallerinaAsyncApiException{ - - List ifBodyStatementsList = new ArrayList<>(); - - if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { - if (!headerParameters.isEmpty()) { - statementsList.add(getMapForParameters(headerParameters, "map", - HEADER_VALUES, new ArrayList<>())); - } else { - ExpressionStatementNode headerMapCreation = GeneratorUtils.getSimpleExpressionStatementNode( - "map " + HEADER_VALUES + " = {}"); - statementsList.add(headerMapCreation); - } - - if (!headerApiKeyNameList.isEmpty()) { - // update headerValues Map within the if block - // `headerValues["api-key"] = self.apiKeyConfig?.apiKey;` - addApiKeysToMap(HEADER_VALUES, headerApiKeyNameList, ifBodyStatementsList); - } - isHeader = true; - ballerinaUtilGenerator.setHeadersFound(true); - } - - if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { - ballerinaUtilGenerator.setQueryParamsFound(true); - if (!queryParameters.isEmpty()) { - statementsList.add(getMapForParameters(queryParameters, "map", - QUERY_PARAM, new ArrayList<>())); - } else { - ExpressionStatementNode queryParamMapCreation = GeneratorUtils.getSimpleExpressionStatementNode( - "map " + QUERY_PARAM + " = {}"); - statementsList.add(queryParamMapCreation); - } - - if (!queryApiKeyNameList.isEmpty()) { - // update queryParam Map within the if block - // `queryParam["api-key"] = self.apiKeyConfig?.apiKey;` - addApiKeysToMap(QUERY_PARAM, queryApiKeyNameList, ifBodyStatementsList); - } - } - - generateIfBlockToAddApiKeysToMaps(statementsList, ifBodyStatementsList); - - if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { - getUpdatedPathHandlingQueryParamEncoding(statementsList, queryParameters); - } - if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { - statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode( - "map " + HTTP_HEADERS + " = getMapForHeaders(headerValues)")); - } - } - - /** - * Add apiKeys to a given map (queryParam or headerValues). - *

- * `queryParam["api-key"] = self.apiKeyConfig?.apiKey;` - * `headerValues["api-key"] = self.apiKeyConfig?.apiKey;` - */ - private void addApiKeysToMap(String mapName, List apiKeyNames, List statementNodeList) { - - if (!apiKeyNames.isEmpty()) { - for (String apiKey : apiKeyNames) { - IdentifierToken fieldName = createIdentifierToken(mapName + "[" + '"' + apiKey.trim() + '"' + "]"); - Token equal = createToken(EQUAL_TOKEN); - FieldAccessExpressionNode fieldExpr = createFieldAccessExpressionNode( - createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), - createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG_PARAM + - QUESTION_MARK_TOKEN.stringValue()))); - SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode(createIdentifierToken( - getValidName(getValidName(apiKey, false), false))); - ExpressionNode apiKeyExpr = createFieldAccessExpressionNode( - fieldExpr, createToken(DOT_TOKEN), valueExpr); - statementNodeList.add(createAssignmentStatementNode(fieldName, equal, apiKeyExpr, createToken( - SEMICOLON_TOKEN))); - } - } - } - - /** - * Get updated path considering queryParamEncodingMap. - */ - private void getUpdatedPathHandlingQueryParamEncoding(List statementsList, List - queryParameters) throws BallerinaAsyncApiException { - - VariableDeclarationNode queryParamEncodingMap = getQueryParameterEncodingMap(queryParameters); - if (queryParamEncodingMap != null) { - statementsList.add(queryParamEncodingMap); - ExpressionStatementNode updatedPath = GeneratorUtils.getSimpleExpressionStatementNode( - RESOURCE_PATH + " = " + RESOURCE_PATH + " + check getPathForQueryParam(queryParam, " + - "queryParamEncoding)"); - statementsList.add(updatedPath); - } else { - ExpressionStatementNode updatedPath = GeneratorUtils.getSimpleExpressionStatementNode( - RESOURCE_PATH + " = " + RESOURCE_PATH + " + check getPathForQueryParam(queryParam)"); - statementsList.add(updatedPath); - } - } - - /** - * Generate if block when a client supports both ApiKey and HTTPOrOAuth authentication. - * - *

-     * if self.apiKeyConfig is ApiKeysConfig {
-     *      --- given statements ---
-     * }
-     * 
- */ - private void generateIfBlockToAddApiKeysToMaps(List statementsList, - List ifBodyStatementsList) { - - if (!ifBodyStatementsList.isEmpty()) { - NodeList ifBodyStatementsNodeList = createNodeList(ifBodyStatementsList); - BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), - ifBodyStatementsNodeList, createToken(CLOSE_BRACE_TOKEN)); - - // Create expression `self.apiKeyConfig is ApiKeysConfig` - ExpressionNode condition = createBinaryExpressionNode(null, createIdentifierToken(SELF + - DOT_TOKEN.stringValue() + API_KEY_CONFIG_PARAM), - createToken(IS_KEYWORD), - createIdentifierToken(API_KEYS_CONFIG)); - IfElseStatementNode ifBlock = createIfElseStatementNode(createToken(IF_KEYWORD), condition, ifBody, null); - statementsList.add(ifBlock); - } - } - - /** - * Generate VariableDeclarationNode for query parameter encoding map which includes the data related serialization - * mechanism that needs to be used with object or array type parameters. Parameters in primitive types will not be - * included to the map even when the serialization mechanisms are specified. These data is given in the `style` and - * `explode` sections of the OpenAPI definition. Style defines how multiple values are delimited and explode - * specifies whether arrays and objects should generate separate parameters - *

- * --ex: {@code map queryParamEncoding = {"expand": ["deepObject", true]};} - * - * @param queryParameters List of query parameters defined in a particular function - * @return {@link VariableDeclarationNode} - * @throws BallerinaAsyncApiException When invalid referenced schema is given. - */ - private VariableDeclarationNode getQueryParameterEncodingMap(List queryParameters) - throws BallerinaAsyncApiException { - - List filedOfMap = new ArrayList<>(); - BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken("map<" + ENCODING + ">")); - CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( - createIdentifierToken("queryParamEncoding")); - TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); - - for (Parameter parameter : queryParameters) { - Schema paramSchema = parameter.getSchema(); - if (paramSchema.get$ref() != null) { - paramSchema = openAPI.getComponents().getSchemas().get( - getValidName(extractReferenceType(paramSchema.get$ref()), true)); - } - if (paramSchema != null && (paramSchema.getProperties() != null || - (paramSchema.getType() != null && paramSchema.getType().equals("array")) || - (paramSchema instanceof ComposedSchema))) { - if (parameter.getStyle() != null || parameter.getExplode() != null) { - GeneratorUtils.createEncodingMap(filedOfMap, parameter.getStyle().toString(), - parameter.getExplode(), parameter.getName().trim()); - } - } - } - if (!filedOfMap.isEmpty()) { - filedOfMap.remove(filedOfMap.size() - 1); - MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( - createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(filedOfMap), - createToken(CLOSE_BRACE_TOKEN)); - return createVariableDeclarationNode(createEmptyNodeList(), - null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, - createToken(SEMICOLON_TOKEN)); - } - return null; - - } - - /** - * Provides the list of security schemes available for the given operation. - * - * @param operation Current operation - * @return Security schemes that can be used to authorize the given operation - */ - private Set getSecurityRequirementForOperation(Operation operation) { - - Set securitySchemasAvailable = new LinkedHashSet<>(); - List securityRequirements = new ArrayList<>(); - if (operation.getSecurity() != null) { - securityRequirements = operation.getSecurity(); - } else if (openAPI.getSecurity() != null) { - securityRequirements = openAPI.getSecurity(); - } - - if (securityRequirements.size() > 0) { - for (SecurityRequirement requirement : securityRequirements) { - securitySchemasAvailable.addAll(requirement.keySet()); - } - } - return securitySchemasAvailable; - } - - /** - * Handle request body in operation. - */ - private void handleRequestBodyInOperation(List statementsList, String method, String returnType, - RequestBody requestBody) - throws BallerinaOpenApiException { - - if (requestBody.getContent() != null) { - Content rbContent = requestBody.getContent(); - Set> entries = rbContent.entrySet(); - Iterator> iterator = entries.iterator(); - //Currently align with first content of the requestBody - while (iterator.hasNext()) { - createRequestBodyStatements(isHeader, statementsList, method, returnType, iterator); - break; - } - } else if (requestBody.get$ref() != null) { - RequestBody requestBodySchema = - openAPI.getComponents().getRequestBodies().get(extractReferenceType(requestBody.get$ref())); - Content rbContent = requestBodySchema.getContent(); - Set> entries = rbContent.entrySet(); - Iterator> iterator = entries.iterator(); - //Currently align with first content of the requestBody - while (iterator.hasNext()) { - createRequestBodyStatements(isHeader, statementsList, method, returnType, iterator); - break; - } - } - } +// /** +// * This function for creating requestBody statements. +// * -- ex: Request body with json payload. +// *

+//     *    http:Request request = new;
+//     *    json jsonBody = payload.toJson();
+//     *    request.setPayload(jsonBody, "application/json");
+//     *    json response = check self.clientEp->put(path, request);
+//     * 
+// * +// * @param isHeader - Boolean value for header availability. +// * @param statementsList - StatementNode list in body node +// * @param method - Operation method name. +// * @param returnType - Response type +// * @param iterator - RequestBody media type +// */ +// private void createRequestBodyStatements(boolean isHeader, List statementsList, +// String method, String returnType, Iterator> iterator) +// throws BallerinaAsyncApiException { +// +// //Create Request statement +// Map.Entry mediaTypeEntry = iterator.next(); +// if (GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { +// VariableDeclarationNode requestVariable = GeneratorUtils.getSimpleStatement(HTTP_REQUEST, +// REQUEST, NEW); +// statementsList.add(requestVariable); +// } +// if (mediaTypeEntry.getValue() != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { +// genStatementsForRequestMediaType(statementsList, mediaTypeEntry); +// // TODO:Fill with other mime type +// } else { +// // Add default value comment +// ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "// TODO: Update the request as needed"); +// statementsList.add(expressionStatementNode); +// } +// // POST, PUT, PATCH, DELETE, EXECUTE +// VariableDeclarationNode requestStatement = +// GeneratorUtils.getSimpleStatement(returnType, RESPONSE, "check self.clientEp->" +// + method + "(" + RESOURCE_PATH + ", request)"); +// if (isHeader) { +// if (method.equals(POST) || method.equals(PUT) || method.equals(PATCH) || method.equals(DELETE) +// || method.equals(EXECUTE)) { +// requestStatement = GeneratorUtils.getSimpleStatement(returnType, RESPONSE, +// "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", request, " + +// HTTP_HEADERS + ")"); +// statementsList.add(requestStatement); +// Token returnKeyWord = createIdentifierToken("return"); +// SimpleNameReferenceNode returns = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); +// ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returns, +// createToken(SEMICOLON_TOKEN)); +// statementsList.add(returnStatementNode); +// } +// } else { +// statementsList.add(requestStatement); +// Token returnKeyWord = createIdentifierToken("return"); +// SimpleNameReferenceNode returnVariable = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); +// ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returnVariable, +// createToken(SEMICOLON_TOKEN)); +// statementsList.add(returnStatementNode); +// } +// } + +// /** +// * Generate statements for query parameters and headers. +// */ +// private void handleParameterSchemaInOperation(Map.Entry operation, +// List statementsList) throws BallerinaAsyncApiException { +// +// List queryApiKeyNameList = new ArrayList<>(); +// List headerApiKeyNameList = new ArrayList<>(); +// +// Set securitySchemesAvailable = getSecurityRequirementForOperation(operation.getValue()); +// +// if (securitySchemesAvailable.size() > 0) { +// Map queryApiKeyMap = ballerinaAuthConfigGenerator.getQueryApiKeyNameList(); +// Map headerApiKeyMap = ballerinaAuthConfigGenerator.getHeaderApiKeyNameList(); +// for (String schemaName : securitySchemesAvailable) { +// if (queryApiKeyMap.containsKey(schemaName)) { +// queryApiKeyNameList.add(queryApiKeyMap.get(schemaName)); +// } else if (headerApiKeyMap.containsKey(schemaName)) { +// headerApiKeyNameList.add(headerApiKeyMap.get(schemaName)); +// } +// } +// } +// +// List queryParameters = new ArrayList<>(); +// List headerParameters = new ArrayList<>(); +// +// if (operation.getValue().getParameters() != null) { +// List parameters = operation.getValue().getParameters(); +// for (Parameter parameter : parameters) { +// if (parameter.getIn().trim().equals(QUERY)) { +// queryParameters.add(parameter); +// } else if (parameter.getIn().trim().equals(HEADER)) { +// headerParameters.add(parameter); +// } +// } +// } +// handleQueryParamsAndHeaders(queryParameters, headerParameters, statementsList, queryApiKeyNameList, +// headerApiKeyNameList); +// } + +// /** +// * Handle query parameters and headers within a remote function. +// */ +// public void handleQueryParamsAndHeaders(List queryParameters, List headerParameters, +// List statementsList, List queryApiKeyNameList, +// List headerApiKeyNameList) throws BallerinaAsyncApiException { +// +// boolean combinationOfApiKeyAndHTTPOAuth = ballerinaAuthConfigGenerator.isHttpOROAuth() && +// ballerinaAuthConfigGenerator.isHttpApiKey(); +// if (combinationOfApiKeyAndHTTPOAuth) { +// addUpdatedPathAndHeaders(statementsList, queryApiKeyNameList, queryParameters, +// headerApiKeyNameList, headerParameters); +// } else { +// if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { +// ballerinaUtilGenerator.setQueryParamsFound(true); +// statementsList.add(getMapForParameters(queryParameters, "map", +// QUERY_PARAM, queryApiKeyNameList)); +// getUpdatedPathHandlingQueryParamEncoding(statementsList, queryParameters); +// } +// if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { +// statementsList.add(getMapForParameters(headerParameters, "map", +// HEADER_VALUES, headerApiKeyNameList)); +// statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode( +// "map " + HTTP_HEADERS + " = getMapForHeaders(headerValues)")); +// isHeader = true; +// ballerinaUtilGenerator.setHeadersFound(true); +// } +// } +// } + +// /** +// * Generate statements for query parameters and headers when a client supports both ApiKey and HTTPOrOAuth +// * authentication. +// */ +// private void addUpdatedPathAndHeaders(List statementsList, List queryApiKeyNameList, +// List queryParameters, List headerApiKeyNameList, +// List headerParameters) throws BallerinaAsyncApiException{ +// +// List ifBodyStatementsList = new ArrayList<>(); +// +// if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { +// if (!headerParameters.isEmpty()) { +// statementsList.add(getMapForParameters(headerParameters, "map", +// HEADER_VALUES, new ArrayList<>())); +// } else { +// ExpressionStatementNode headerMapCreation = GeneratorUtils.getSimpleExpressionStatementNode( +// "map " + HEADER_VALUES + " = {}"); +// statementsList.add(headerMapCreation); +// } +// +// if (!headerApiKeyNameList.isEmpty()) { +// // update headerValues Map within the if block +// // `headerValues["api-key"] = self.apiKeyConfig?.apiKey;` +// addApiKeysToMap(HEADER_VALUES, headerApiKeyNameList, ifBodyStatementsList); +// } +// isHeader = true; +// ballerinaUtilGenerator.setHeadersFound(true); +// } +// +// if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { +// ballerinaUtilGenerator.setQueryParamsFound(true); +// if (!queryParameters.isEmpty()) { +// statementsList.add(getMapForParameters(queryParameters, "map", +// QUERY_PARAM, new ArrayList<>())); +// } else { +// ExpressionStatementNode queryParamMapCreation = GeneratorUtils.getSimpleExpressionStatementNode( +// "map " + QUERY_PARAM + " = {}"); +// statementsList.add(queryParamMapCreation); +// } +// +// if (!queryApiKeyNameList.isEmpty()) { +// // update queryParam Map within the if block +// // `queryParam["api-key"] = self.apiKeyConfig?.apiKey;` +// addApiKeysToMap(QUERY_PARAM, queryApiKeyNameList, ifBodyStatementsList); +// } +// } +// +// generateIfBlockToAddApiKeysToMaps(statementsList, ifBodyStatementsList); +// +// if (!queryParameters.isEmpty() || !queryApiKeyNameList.isEmpty()) { +// getUpdatedPathHandlingQueryParamEncoding(statementsList, queryParameters); +// } +// if (!headerParameters.isEmpty() || !headerApiKeyNameList.isEmpty()) { +// statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode( +// "map " + HTTP_HEADERS + " = getMapForHeaders(headerValues)")); +// } +// } + +// /** +// * Add apiKeys to a given map (queryParam or headerValues). +// *

+// * `queryParam["api-key"] = self.apiKeyConfig?.apiKey;` +// * `headerValues["api-key"] = self.apiKeyConfig?.apiKey;` +// */ +// private void addApiKeysToMap(String mapName, List apiKeyNames, List statementNodeList) { +// +// if (!apiKeyNames.isEmpty()) { +// for (String apiKey : apiKeyNames) { +// IdentifierToken fieldName = createIdentifierToken(mapName + "[" + '"' + apiKey.trim() + '"' + "]"); +// Token equal = createToken(EQUAL_TOKEN); +// FieldAccessExpressionNode fieldExpr = createFieldAccessExpressionNode( +// createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), +// createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG_PARAM + +// QUESTION_MARK_TOKEN.stringValue()))); +// SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode(createIdentifierToken( +// getValidName(getValidName(apiKey, false), false))); +// ExpressionNode apiKeyExpr = createFieldAccessExpressionNode( +// fieldExpr, createToken(DOT_TOKEN), valueExpr); +// statementNodeList.add(createAssignmentStatementNode(fieldName, equal, apiKeyExpr, createToken( +// SEMICOLON_TOKEN))); +// } +// } +// } +// +// /** +// * Get updated path considering queryParamEncodingMap. +// */ +// private void getUpdatedPathHandlingQueryParamEncoding(List statementsList, List +// queryParameters) throws BallerinaAsyncApiException { +// +// VariableDeclarationNode queryParamEncodingMap = getQueryParameterEncodingMap(queryParameters); +// if (queryParamEncodingMap != null) { +// statementsList.add(queryParamEncodingMap); +// ExpressionStatementNode updatedPath = GeneratorUtils.getSimpleExpressionStatementNode( +// RESOURCE_PATH + " = " + RESOURCE_PATH + " + check getPathForQueryParam(queryParam, " + +// "queryParamEncoding)"); +// statementsList.add(updatedPath); +// } else { +// ExpressionStatementNode updatedPath = GeneratorUtils.getSimpleExpressionStatementNode( +// RESOURCE_PATH + " = " + RESOURCE_PATH + " + check getPathForQueryParam(queryParam)"); +// statementsList.add(updatedPath); +// } +// } + +// /** +// * Generate if block when a client supports both ApiKey and HTTPOrOAuth authentication. +// * +// *

+//     * if self.apiKeyConfig is ApiKeysConfig {
+//     *      --- given statements ---
+//     * }
+//     * 
+// */ +// private void generateIfBlockToAddApiKeysToMaps(List statementsList, +// List ifBodyStatementsList) { +// +// if (!ifBodyStatementsList.isEmpty()) { +// NodeList ifBodyStatementsNodeList = createNodeList(ifBodyStatementsList); +// BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), +// ifBodyStatementsNodeList, createToken(CLOSE_BRACE_TOKEN)); +// +// // Create expression `self.apiKeyConfig is ApiKeysConfig` +// ExpressionNode condition = createBinaryExpressionNode(null, createIdentifierToken(SELF + +// DOT_TOKEN.stringValue() + API_KEY_CONFIG_PARAM), +// createToken(IS_KEYWORD), +// createIdentifierToken(API_KEYS_CONFIG)); +// IfElseStatementNode ifBlock = createIfElseStatementNode(createToken(IF_KEYWORD), condition, ifBody, null); +// statementsList.add(ifBlock); +// } +// } + +// /** +// * Generate VariableDeclarationNode for query parameter encoding map which includes the data related serialization +// * mechanism that needs to be used with object or array type parameters. Parameters in primitive types will not be +// * included to the map even when the serialization mechanisms are specified. These data is given in the `style` and +// * `explode` sections of the OpenAPI definition. Style defines how multiple values are delimited and explode +// * specifies whether arrays and objects should generate separate parameters +// *

+// * --ex: {@code map queryParamEncoding = {"expand": ["deepObject", true]};} +// * +// * @param queryParameters List of query parameters defined in a particular function +// * @return {@link VariableDeclarationNode} +// * @throws BallerinaAsyncApiException When invalid referenced schema is given. +// */ +// private VariableDeclarationNode getQueryParameterEncodingMap(List queryParameters) +// throws BallerinaAsyncApiException { +// +// List filedOfMap = new ArrayList<>(); +// BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, +// createIdentifierToken("map<" + ENCODING + ">")); +// CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( +// createIdentifierToken("queryParamEncoding")); +// TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); +// +// for (Parameter parameter : queryParameters) { +// Schema paramSchema = parameter.getSchema(); +// if (paramSchema.get$ref() != null) { +// paramSchema = openAPI.getComponents().getSchemas().get( +// getValidName(extractReferenceType(paramSchema.get$ref()), true)); +// } +// if (paramSchema != null && (paramSchema.getProperties() != null || +// (paramSchema.getType() != null && paramSchema.getType().equals("array")) || +// (paramSchema instanceof ComposedSchema))) { +// if (parameter.getStyle() != null || parameter.getExplode() != null) { +// GeneratorUtils.createEncodingMap(filedOfMap, parameter.getStyle().toString(), +// parameter.getExplode(), parameter.getName().trim()); +// } +// } +// } +// if (!filedOfMap.isEmpty()) { +// filedOfMap.remove(filedOfMap.size() - 1); +// MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( +// createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(filedOfMap), +// createToken(CLOSE_BRACE_TOKEN)); +// return createVariableDeclarationNode(createEmptyNodeList(), +// null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, +// createToken(SEMICOLON_TOKEN)); +// } +// return null; +// +// } + +// /** +// * Provides the list of security schemes available for the given operation. +// * +// * @param operation Current operation +// * @return Security schemes that can be used to authorize the given operation +// */ +// private Set getSecurityRequirementForOperation(Operation operation) { +// +// Set securitySchemasAvailable = new LinkedHashSet<>(); +// List securityRequirements = new ArrayList<>(); +// if (operation.getSecurity() != null) { +// securityRequirements = operation.getSecurity(); +// } else if (openAPI.getSecurity() != null) { +// securityRequirements = openAPI.getSecurity(); +// } +// +// if (securityRequirements.size() > 0) { +// for (SecurityRequirement requirement : securityRequirements) { +// securitySchemasAvailable.addAll(requirement.keySet()); +// } +// } +// return securitySchemasAvailable; +// } +// +// /** +// * Handle request body in operation. +// */ +// private void handleRequestBodyInOperation(List statementsList, String method, String returnType, +// RequestBody requestBody) +// throws BallerinaOpenApiException { +// +// if (requestBody.getContent() != null) { +// Content rbContent = requestBody.getContent(); +// Set> entries = rbContent.entrySet(); +// Iterator> iterator = entries.iterator(); +// //Currently align with first content of the requestBody +// while (iterator.hasNext()) { +// createRequestBodyStatements(isHeader, statementsList, method, returnType, iterator); +// break; +// } +// } else if (requestBody.get$ref() != null) { +// RequestBody requestBodySchema = +// openAPI.getComponents().getRequestBodies().get(extractReferenceType(requestBody.get$ref())); +// Content rbContent = requestBodySchema.getContent(); +// Set> entries = rbContent.entrySet(); +// Iterator> iterator = entries.iterator(); +// //Currently align with first content of the requestBody +// while (iterator.hasNext()) { +// createRequestBodyStatements(isHeader, statementsList, method, returnType, iterator); +// break; +// } +// } +// } /** - * Generate common statements in function bosy. + * Generate common statements in function body. */ - private void createCommonFunctionBodyStatements(List statementsList, String method, + private void createCommonFunctionBodyStatements(List statementsList, String paramName, String returnType) { - - String clientCallStatement; - - // This condition for several methods. - boolean isEntityBodyMethods = method.equals(POST) || method.equals(PUT) || method.equals(PATCH) - || method.equals(EXECUTE); - if (isHeader) { - if (isEntityBodyMethods) { - ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "http:Request request = new"); - statementsList.add(requestStatementNode); - ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "//TODO: Update the request as needed"); - statementsList.add(expressionStatementNode); - clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + - ", request, " + HTTP_HEADERS + ")"; - } else if (method.equals(DELETE)) { - clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + - ", headers = " + HTTP_HEADERS + ")"; - } else if (method.equals(HEAD)) { - clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", " + - HTTP_HEADERS + ")"; - } else { - clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", " + - HTTP_HEADERS + ")"; - } - } else if (method.equals(DELETE)) { - clientCallStatement = "check self.clientEp-> " + method + "(" + RESOURCE_PATH + ")"; - } else if (isEntityBodyMethods) { - ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "http:Request request = new"); - statementsList.add(requestStatementNode); - ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "//TODO: Update the request as needed"); - statementsList.add(expressionStatementNode); - clientCallStatement = "check self.clientEp-> " + method + "(" + RESOURCE_PATH + ", request)"; - } else { - clientCallStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ")"; - } +// +// String clientReadStatement; +// +// // This condition for several methods. +// boolean isEntityBodyMethods = method.equals(POST) || method.equals(PUT) || method.equals(PATCH) +// || method.equals(EXECUTE); +// if (isHeader) { +// if (isEntityBodyMethods) { +// ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "http:Request request = new"); +// statementsList.add(requestStatementNode); +// ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "//TODO: Update the request as needed"); +// statementsList.add(expressionStatementNode); +// clientReadStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + +// ", request, " + HTTP_HEADERS + ")"; +// } else if (method.equals(DELETE)) { +// clientReadStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + +// ", headers = " + HTTP_HEADERS + ")"; +// } else if (method.equals(HEAD)) { +// clientReadStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", " + +// HTTP_HEADERS + ")"; +// } else { +// clientReadStatement = "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", " + +// HTTP_HEADERS + ")"; +// } +// } else if (method.equals(DELETE)) { +// clientReadStatement = "check self.clientEp-> " + method + "(" + RESOURCE_PATH + ")"; +// } else if (isEntityBodyMethods) { +// ExpressionStatementNode requestStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "http:Request request = new"); +// statementsList.add(requestStatementNode); +// ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "//TODO: Update the request as needed"); +// statementsList.add(expressionStatementNode); +// clientReadStatement = "check self.clientEp-> " + method + "(" + RESOURCE_PATH + ", request)"; +// } else { + String clientCallStatement = "check self.clientEp->" + "writeMessage"+ "(" + paramName + ")"; + ExpressionStatementNode clientCall= createExpressionStatementNode(SyntaxKind.CHECK_EXPRESSION, + createSimpleNameReferenceNode(createIdentifierToken(clientCallStatement)), + createToken(SEMICOLON_TOKEN)); + String clientReadStatement = "check self.clientEp->" + "readMessage"+ "(" + ")"; +// } //Return Variable - VariableDeclarationNode clientCall = GeneratorUtils.getSimpleStatement(returnType, RESPONSE, - clientCallStatement); + VariableDeclarationNode clientRead = GeneratorUtils.getSimpleStatement(returnType, RESPONSE, + clientReadStatement); statementsList.add(clientCall); + statementsList.add(clientRead); Token returnKeyWord = createIdentifierToken("return"); SimpleNameReferenceNode returns = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returns, @@ -542,136 +575,136 @@ private void createCommonFunctionBodyStatements(List statementsLi statementsList.add(returnStatementNode); } - /** - * This method use to generate Path statement inside the function body node. - *

- * ex: - *

 string  path = string `/weather`; 
- * - * @param path - Given path - * @param annotationNodes - Node list for path implementation - * @return - VariableDeclarationNode for path statement. - */ - private VariableDeclarationNode getPathStatement(String path, NodeList annotationNodes) { - - TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(createSimpleNameReferenceNode( - createToken(STRING_KEYWORD)), createCaptureBindingPatternNode( - createIdentifierToken(RESOURCE_PATH))); - // Create initializer - // Content should decide with /pet and /pet/{pet} - path = generatePathWithPathParameter(path); - //String path generator - NodeList content = createNodeList(createLiteralValueToken(null, path, createEmptyMinutiaeList(), - createEmptyMinutiaeList())); - TemplateExpressionNode initializer = createTemplateExpressionNode(null, createToken(STRING_KEYWORD), - createToken(BACKTICK_TOKEN), content, createToken(BACKTICK_TOKEN)); - return createVariableDeclarationNode(annotationNodes, null, - typedBindingPatternNode, createToken(EQUAL_TOKEN), initializer, createToken(SEMICOLON_TOKEN)); - } - - /** - * This method is to used for generating path when it has path parameters. - * - * @param path - yaml contract path - * @return string of path - */ - public String generatePathWithPathParameter(String path) { - - if (path.contains("{")) { - String refinedPath = path; - Pattern p = Pattern.compile("\\{[^}]*}"); - Matcher m = p.matcher(path); - while (m.find()) { - String pathVariable = path.substring(m.start(), m.end()); - if (pathVariable.startsWith("{") && pathVariable.endsWith("}")) { - String d = pathVariable.replace("{", "").replace("}", ""); - String replaceVariable = "{getEncodedUri(" + getValidName(d, false) + ")}"; - refinedPath = refinedPath.replace(pathVariable, replaceVariable); - } - } - path = refinedPath.replaceAll("[{]", "\\${"); - } - ballerinaUtilGenerator.setPathParametersFound(true); - return path; - } - - /** - * This function for creating requestBody statements. - * -- ex: Request body with json payload. - *
-     *    http:Request request = new;
-     *    json jsonBody = payload.toJson();
-     *    request.setPayload(jsonBody, "application/json");
-     *    json response = check self.clientEp->put(path, request);
-     * 
- * - * @param isHeader - Boolean value for header availability. - * @param statementsList - StatementNode list in body node - * @param method - Operation method name. - * @param returnType - Response type - * @param iterator - RequestBody media type - */ - private void createRequestBodyStatements(boolean isHeader, List statementsList, - String method, String returnType, Iterator> iterator) - throws BallerinaOpenApiException { - - //Create Request statement - Map.Entry mediaTypeEntry = iterator.next(); - if (GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { - VariableDeclarationNode requestVariable = GeneratorUtils.getSimpleStatement(HTTP_REQUEST, - REQUEST, NEW); - statementsList.add(requestVariable); - } - if (mediaTypeEntry.getValue() != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { - genStatementsForRequestMediaType(statementsList, mediaTypeEntry); - // TODO:Fill with other mime type - } else { - // Add default value comment - ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( - "// TODO: Update the request as needed"); - statementsList.add(expressionStatementNode); - } - // POST, PUT, PATCH, DELETE, EXECUTE - VariableDeclarationNode requestStatement = - GeneratorUtils.getSimpleStatement(returnType, RESPONSE, "check self.clientEp->" - + method + "(" + RESOURCE_PATH + ", request)"); - if (isHeader) { - if (method.equals(POST) || method.equals(PUT) || method.equals(PATCH) || method.equals(DELETE) - || method.equals(EXECUTE)) { - requestStatement = GeneratorUtils.getSimpleStatement(returnType, RESPONSE, - "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", request, " + - HTTP_HEADERS + ")"); - statementsList.add(requestStatement); - Token returnKeyWord = createIdentifierToken("return"); - SimpleNameReferenceNode returns = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); - ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returns, - createToken(SEMICOLON_TOKEN)); - statementsList.add(returnStatementNode); - } - } else { - statementsList.add(requestStatement); - Token returnKeyWord = createIdentifierToken("return"); - SimpleNameReferenceNode returnVariable = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); - ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returnVariable, - createToken(SEMICOLON_TOKEN)); - statementsList.add(returnStatementNode); - } - } - - /** - * This function is used for generating function body statements according to the given request body media type. - * - * @param statementsList - Previous statements list - * @param mediaTypeEntry - Media type entry - */ - private void genStatementsForRequestMediaType(List statementsList, - Map.Entry mediaTypeEntry) - throws BallerinaOpenApiException { - MimeFactory factory = new MimeFactory(); - MimeType mimeType = factory.getMimeType(mediaTypeEntry, ballerinaUtilGenerator, imports); - mimeType.setPayload(statementsList, mediaTypeEntry); - } +// /** +// * This method use to generate Path statement inside the function body node. +// *

+// * ex: +// *

 string  path = string `/weather`; 
+// * +// * @param path - Given path +// * @param annotationNodes - Node list for path implementation +// * @return - VariableDeclarationNode for path statement. +// */ +// private VariableDeclarationNode getPathStatement(String path, NodeList annotationNodes) { +// +// TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(createSimpleNameReferenceNode( +// createToken(STRING_KEYWORD)), createCaptureBindingPatternNode( +// createIdentifierToken(RESOURCE_PATH))); +// // Create initializer +// // Content should decide with /pet and /pet/{pet} +// path = generatePathWithPathParameter(path); +// //String path generator +// NodeList content = createNodeList(createLiteralValueToken(null, path, createEmptyMinutiaeList(), +// createEmptyMinutiaeList())); +// TemplateExpressionNode initializer = createTemplateExpressionNode(null, createToken(STRING_KEYWORD), +// createToken(BACKTICK_TOKEN), content, createToken(BACKTICK_TOKEN)); +// return createVariableDeclarationNode(annotationNodes, null, +// typedBindingPatternNode, createToken(EQUAL_TOKEN), initializer, createToken(SEMICOLON_TOKEN)); +// } + +// /** +// * This method is to used for generating path when it has path parameters. +// * +// * @param path - yaml contract path +// * @return string of path +// */ +// public String generatePathWithPathParameter(String path) { +// +// if (path.contains("{")) { +// String refinedPath = path; +// Pattern p = Pattern.compile("\\{[^}]*}"); +// Matcher m = p.matcher(path); +// while (m.find()) { +// String pathVariable = path.substring(m.start(), m.end()); +// if (pathVariable.startsWith("{") && pathVariable.endsWith("}")) { +// String d = pathVariable.replace("{", "").replace("}", ""); +// String replaceVariable = "{getEncodedUri(" + getValidName(d, false) + ")}"; +// refinedPath = refinedPath.replace(pathVariable, replaceVariable); +// } +// } +// path = refinedPath.replaceAll("[{]", "\\${"); +// } +// ballerinaUtilGenerator.setPathParametersFound(true); +// return path; +// } + +// /** +// * This function for creating requestBody statements. +// * -- ex: Request body with json payload. +// *
+//     *    http:Request request = new;
+//     *    json jsonBody = payload.toJson();
+//     *    request.setPayload(jsonBody, "application/json");
+//     *    json response = check self.clientEp->put(path, request);
+//     * 
+// * +// * @param isHeader - Boolean value for header availability. +// * @param statementsList - StatementNode list in body node +// * @param method - Operation method name. +// * @param returnType - Response type +// * @param iterator - RequestBody media type +// */ +// private void createRequestBodyStatements(boolean isHeader, List statementsList, +// String method, String returnType, Iterator> iterator) +// throws BallerinaAsyncApiException { +// +// //Create Request statement +// Map.Entry mediaTypeEntry = iterator.next(); +// if (GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { +// VariableDeclarationNode requestVariable = GeneratorUtils.getSimpleStatement(HTTP_REQUEST, +// REQUEST, NEW); +// statementsList.add(requestVariable); +// } +// if (mediaTypeEntry.getValue() != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) { +// genStatementsForRequestMediaType(statementsList, mediaTypeEntry); +// // TODO:Fill with other mime type +// } else { +// // Add default value comment +// ExpressionStatementNode expressionStatementNode = GeneratorUtils.getSimpleExpressionStatementNode( +// "// TODO: Update the request as needed"); +// statementsList.add(expressionStatementNode); +// } +// // POST, PUT, PATCH, DELETE, EXECUTE +// VariableDeclarationNode requestStatement = +// GeneratorUtils.getSimpleStatement(returnType, RESPONSE, "check self.clientEp->" +// + method + "(" + RESOURCE_PATH + ", request)"); +// if (isHeader) { +// if (method.equals(POST) || method.equals(PUT) || method.equals(PATCH) || method.equals(DELETE) +// || method.equals(EXECUTE)) { +// requestStatement = GeneratorUtils.getSimpleStatement(returnType, RESPONSE, +// "check self.clientEp->" + method + "(" + RESOURCE_PATH + ", request, " + +// HTTP_HEADERS + ")"); +// statementsList.add(requestStatement); +// Token returnKeyWord = createIdentifierToken("return"); +// SimpleNameReferenceNode returns = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); +// ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returns, +// createToken(SEMICOLON_TOKEN)); +// statementsList.add(returnStatementNode); +// } +// } else { +// statementsList.add(requestStatement); +// Token returnKeyWord = createIdentifierToken("return"); +// SimpleNameReferenceNode returnVariable = createSimpleNameReferenceNode(createIdentifierToken(RESPONSE)); +// ReturnStatementNode returnStatementNode = createReturnStatementNode(returnKeyWord, returnVariable, +// createToken(SEMICOLON_TOKEN)); +// statementsList.add(returnStatementNode); +// } +// } +// +// /** +// * This function is used for generating function body statements according to the given request body media type. +// * +// * @param statementsList - Previous statements list +// * @param mediaTypeEntry - Media type entry +// */ +// private void genStatementsForRequestMediaType(List statementsList, +// Map.Entry mediaTypeEntry) +// throws BallerinaOpenApiException { +// MimeFactory factory = new MimeFactory(); +// MimeType mimeType = factory.getMimeType(mediaTypeEntry, ballerinaUtilGenerator, imports); +// mimeType.setPayload(statementsList, mediaTypeEntry); +// } /** * This util function for getting type to the targetType data binding. @@ -687,61 +720,61 @@ private String returnTypeForTargetTypeField(String rType) { return (rType.contains(NILLABLE) ? returnType + NILLABLE : returnType); } - /** - * Generate map variable for query parameters and headers. - */ - private VariableDeclarationNode getMapForParameters(List parameters, String mapDataType, - String mapName, List apiKeyNames) { - List filedOfMap = new ArrayList<>(); - BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, - createIdentifierToken(mapDataType)); - CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( - createIdentifierToken(mapName)); - TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); - - for (Parameter parameter : parameters) { - // Initializer - IdentifierToken fieldName = createIdentifierToken('"' + (parameter.getName().trim()) + '"'); - Token colon = createToken(COLON_TOKEN); - SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode( - createIdentifierToken(getValidName(parameter.getName().trim(), false))); - SpecificFieldNode specificFieldNode = createSpecificFieldNode(null, - fieldName, colon, valueExpr); - filedOfMap.add(specificFieldNode); - filedOfMap.add(createToken(COMMA_TOKEN)); - } - - if (!apiKeyNames.isEmpty()) { - for (String apiKey : apiKeyNames) { - IdentifierToken fieldName = createIdentifierToken('"' + apiKey.trim() + '"'); - Token colon = createToken(COLON_TOKEN); - IdentifierToken apiKeyConfigIdentifierToken = createIdentifierToken(API_KEY_CONFIG_PARAM); - if (ballerinaAuthConfigGenerator.isHttpOROAuth() && ballerinaAuthConfigGenerator.isHttpApiKey()) { - apiKeyConfigIdentifierToken = createIdentifierToken(API_KEY_CONFIG_PARAM + - QUESTION_MARK_TOKEN.stringValue()); - } - SimpleNameReferenceNode apiKeyConfigParamNode = createSimpleNameReferenceNode( - apiKeyConfigIdentifierToken); - FieldAccessExpressionNode fieldExpr = createFieldAccessExpressionNode( - createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), - apiKeyConfigParamNode); - SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode(createIdentifierToken( - getValidName(apiKey, false))); - SpecificFieldNode specificFieldNode; - ExpressionNode apiKeyExpr = createFieldAccessExpressionNode( - fieldExpr, createToken(DOT_TOKEN), valueExpr); - specificFieldNode = createSpecificFieldNode(null, fieldName, colon, apiKeyExpr); - filedOfMap.add(specificFieldNode); - filedOfMap.add(createToken(COMMA_TOKEN)); - } - } - - filedOfMap.remove(filedOfMap.size() - 1); - MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( - createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(filedOfMap), - createToken(CLOSE_BRACE_TOKEN)); - return createVariableDeclarationNode(createEmptyNodeList(), - null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, - createToken(SEMICOLON_TOKEN)); - } +// /** +// * Generate map variable for query parameters and headers. +// */ +// private VariableDeclarationNode getMapForParameters(List parameters, String mapDataType, +// String mapName, List apiKeyNames) { +// List filedOfMap = new ArrayList<>(); +// BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, +// createIdentifierToken(mapDataType)); +// CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( +// createIdentifierToken(mapName)); +// TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); +// +// for (Parameter parameter : parameters) { +// // Initializer +// IdentifierToken fieldName = createIdentifierToken('"' + (parameter.getName().trim()) + '"'); +// Token colon = createToken(COLON_TOKEN); +// SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode( +// createIdentifierToken(getValidName(parameter.getName().trim(), false))); +// SpecificFieldNode specificFieldNode = createSpecificFieldNode(null, +// fieldName, colon, valueExpr); +// filedOfMap.add(specificFieldNode); +// filedOfMap.add(createToken(COMMA_TOKEN)); +// } +// +// if (!apiKeyNames.isEmpty()) { +// for (String apiKey : apiKeyNames) { +// IdentifierToken fieldName = createIdentifierToken('"' + apiKey.trim() + '"'); +// Token colon = createToken(COLON_TOKEN); +// IdentifierToken apiKeyConfigIdentifierToken = createIdentifierToken(API_KEY_CONFIG_PARAM); +// if (ballerinaAuthConfigGenerator.isHttpOROAuth() && ballerinaAuthConfigGenerator.isHttpApiKey()) { +// apiKeyConfigIdentifierToken = createIdentifierToken(API_KEY_CONFIG_PARAM + +// QUESTION_MARK_TOKEN.stringValue()); +// } +// SimpleNameReferenceNode apiKeyConfigParamNode = createSimpleNameReferenceNode( +// apiKeyConfigIdentifierToken); +// FieldAccessExpressionNode fieldExpr = createFieldAccessExpressionNode( +// createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), +// apiKeyConfigParamNode); +// SimpleNameReferenceNode valueExpr = createSimpleNameReferenceNode(createIdentifierToken( +// getValidName(apiKey, false))); +// SpecificFieldNode specificFieldNode; +// ExpressionNode apiKeyExpr = createFieldAccessExpressionNode( +// fieldExpr, createToken(DOT_TOKEN), valueExpr); +// specificFieldNode = createSpecificFieldNode(null, fieldName, colon, apiKeyExpr); +// filedOfMap.add(specificFieldNode); +// filedOfMap.add(createToken(COMMA_TOKEN)); +// } +// } +// +// filedOfMap.remove(filedOfMap.size() - 1); +// MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode( +// createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(filedOfMap), +// createToken(CLOSE_BRACE_TOKEN)); +// return createVariableDeclarationNode(createEmptyNodeList(), +// null, bindingPatternNode, createToken(EQUAL_TOKEN), initialize, +// createToken(SEMICOLON_TOKEN)); +// } } diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionReturnTypeGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionReturnTypeGenerator.java index c3add6b9f..1a224c06d 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionReturnTypeGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/client/FunctionReturnTypeGenerator.java @@ -108,6 +108,7 @@ public String getReturnType( Map extensions) throws BallerinaA // } // } // } + String type=null; if(extensions.get(X_RESPONSE).get("oneOf")!=null){ @@ -125,15 +126,17 @@ public String getReturnType( Map extensions) throws BallerinaA } else if (extensions.get(X_RESPONSE).get("$ref")!=null) { - String reference= extensions.get(X_RESPONSE).get("$ref").toString(); - AsyncApi25SchemaImpl refSchema = asyncAPI.getComponents().getSchemas().get( - getValidName(extractReferenceType(reference); - getDataType(refSchema); + String reference= extensions.get(X_RESPONSE).get("$ref").asText(); + String schemaName=getValidName(extractReferenceType(reference),true); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents().getSchemas().get( + schemaName); + type =getDataType(schemaName,refSchema); } + returnTypes.add(type); if (returnTypes.size() > 0) { StringBuilder finalReturnType = new StringBuilder(); @@ -155,15 +158,15 @@ public String getReturnType( Map extensions) throws BallerinaA /** * Get return data type by traversing OAS schemas. */ - private String getDataType(AsyncApi25SchemaImpl schema) + private String getDataType(String schemaName,AsyncApi25SchemaImpl schema) throws BallerinaAsyncApiException { String type=null; if (((schema.getProperties() != null && (schema.getOneOf() != null || schema.getAllOf() != null || schema.getAnyOf() != null)))) { - type = generateReturnDataTypeForComposedSchema( schema,type); + type = generateReturnDataTypeForComposedSchema( schemaName,schema,type); } else if (schema.getType().equals("object")) { - type = handleInLineRecordInResponse( schema); + type = handleInLineRecordInResponse(schemaName, schema); // } else if (schema instanceof MapSchema) { // type = handleResponseWithMapSchema(operation, media, mapSchema); } else if (schema.get$ref() != null) { @@ -270,12 +273,12 @@ private String generateReturnTypeForArraySchema( AsyncApi25SchemaImpl arraySchem /** * Get the return data type according to the OAS ComposedSchemas ex: AllOf, OneOf, AnyOf. */ - private String generateReturnDataTypeForComposedSchema(AsyncApi25SchemaImpl composedSchema,String type) + private String generateReturnDataTypeForComposedSchema(String schemaName,AsyncApi25SchemaImpl composedSchema,String type) throws BallerinaAsyncApiException { if (composedSchema.getOneOf() != null) { // Get oneOfUnionType name - String typeName = "OneOf" + "wso2_testing_oneof" + "Response"; + String typeName = "OneOf" + getValidName(schemaName.trim(),true)+ "Response"; TypeDefinitionNode typeDefNode = ballerinaSchemaGenerator.getTypeDefinitionNode( composedSchema, typeName, new ArrayList<>()); GeneratorUtils.updateTypeDefNodeList(typeName, typeDefNode, typeDefinitionNodeList); @@ -284,7 +287,7 @@ private String generateReturnDataTypeForComposedSchema(AsyncApi25SchemaImpl comp // type = typeName; // } } else if (composedSchema.getAllOf() != null) { - String recordName = "Compound" + "wso2_testing_compound" + + String recordName = "Compound" + getValidName(schemaName,true) + "Response"; TypeDefinitionNode allOfTypeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode (composedSchema, recordName, new ArrayList<>()); @@ -297,12 +300,12 @@ private String generateReturnDataTypeForComposedSchema(AsyncApi25SchemaImpl comp /** * Handle inline record by generating record with name for response in OAS type ObjectSchema. */ - private String handleInLineRecordInResponse( AsyncApi25SchemaImpl objectSchema) + private String handleInLineRecordInResponse(String schemaName, AsyncApi25SchemaImpl objectSchema) throws BallerinaAsyncApiException { Map properties = objectSchema.getProperties(); String ref = objectSchema.get$ref(); - String type = "wso2_testing_object" + "Response"; + String type = getValidName(schemaName,true)+ "Response"; if (ref != null) { type = extractReferenceType(ref.trim()); diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/BallerinaTypesGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/BallerinaTypesGenerator.java index 60556db28..b959e3af6 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/BallerinaTypesGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/BallerinaTypesGenerator.java @@ -55,8 +55,7 @@ import java.util.List; import java.util.Map; -import static io.ballerina.asyncapi.core.GeneratorConstants.CONNECTION_CONFIG; -import static io.ballerina.asyncapi.core.GeneratorConstants.HTTP; +import static io.ballerina.asyncapi.core.GeneratorConstants.*; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; @@ -142,8 +141,8 @@ public SyntaxTree generateSyntaxTree() throws BallerinaAsyncApiException { // } if (GeneratorUtils.isValidSchemaName(schemaKey)) { List schemaDoc = new ArrayList<>(); - typeDefinitionNodeListForSchema.add(getTypeDefinitionNode - ((AsyncApi25SchemaImpl) schema.getValue(), schemaKey, schemaDoc)); + typeDefinitionNodeListForSchema.add(getTypeDefinitionNode( + (AsyncApi25SchemaImpl) schema.getValue(), schemaKey, schemaDoc)); } } } @@ -188,30 +187,34 @@ private void importsForTypeDefinitions(List imports) { continue; } if (node.typeName().text().equals(CONNECTION_CONFIG)) { + ImportDeclarationNode importForWebsocket = GeneratorUtils.getImportDeclarationNode( + GeneratorConstants.BALLERINA, + WEBSOCKET); ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( GeneratorConstants.BALLERINA, HTTP); + imports.add(importForWebsocket); imports.add(importForHttp); } - RecordTypeDescriptorNode record = (RecordTypeDescriptorNode) node.typeDescriptor(); - for (Node field : record.fields()) { - if (!(field instanceof TypeReferenceNode) || - !(((TypeReferenceNode) field).typeName() instanceof QualifiedNameReferenceNode)) { - continue; - } - TypeReferenceNode recordField = (TypeReferenceNode) field; - QualifiedNameReferenceNode typeInclusion = (QualifiedNameReferenceNode) recordField.typeName(); - boolean isHttpImportExist = imports.stream().anyMatch(importNode -> importNode.moduleName().stream() - .anyMatch(moduleName -> moduleName.text().equals(HTTP))); - - if (!isHttpImportExist && typeInclusion.modulePrefix().text().equals(HTTP)) { - ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( - GeneratorConstants.BALLERINA, - HTTP); - imports.add(importForHttp); - break; - } - } +// RecordTypeDescriptorNode record = (RecordTypeDescriptorNode) node.typeDescriptor(); +// for (Node field : record.fields()) { +// if (!(field instanceof TypeReferenceNode) || +// !(((TypeReferenceNode) field).typeName() instanceof QualifiedNameReferenceNode)) { +// continue; +// } +// TypeReferenceNode recordField = (TypeReferenceNode) field; +// QualifiedNameReferenceNode typeInclusion = (QualifiedNameReferenceNode) recordField.typeName(); +// boolean isHttpImportExist = imports.stream().anyMatch(importNode -> importNode.moduleName().stream() +// .anyMatch(moduleName -> moduleName.text().equals(WEBSOCKET))); +// +// if (!isHttpImportExist && typeInclusion.modulePrefix().text().equals(WEBSOCKET)) { +// ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( +// GeneratorConstants.BALLERINA, +// WEBSOCKET); +// imports.add(importForHttp); +// break; +// } +// } } } @@ -234,7 +237,7 @@ public TypeDefinitionNode getTypeDefinitionNode(AsyncApi25SchemaImpl schema, Str // if (constraintNode != null) { // typeAnnotations.add(constraintNode); // } - TypeGeneratorUtils.getRecordDocs(schemaDocs, (AsyncApi25SchemaImpl) schema); + TypeGeneratorUtils.getRecordDocs(schemaDocs, schema); TypeDefinitionNode typeDefinitionNode = typeGenerator.generateTypeDefinitionNode(typeNameToken, schemaDocs); diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/TypeGeneratorUtils.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/TypeGeneratorUtils.java index 994dc39fc..1db4c4e05 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/TypeGeneratorUtils.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/TypeGeneratorUtils.java @@ -18,6 +18,7 @@ package io.ballerina.asyncapi.core.generators.schema; +import com.fasterxml.jackson.databind.node.BooleanNode; import io.apicurio.datamodels.models.Schema; import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; @@ -90,19 +91,19 @@ public static TypeGenerator getTypeGenerator(AsyncApi25SchemaImpl schemaValue, S if (schemaValue.get$ref() != null) { return new ReferencedTypeGenerator(schemaValue, typeName); -// } else if (schemaValue instanceof ComposedSchema) { -// ComposedSchema composedSchema = (ComposedSchema) schemaValue; -// if (composedSchema.getAllOf() != null) { -// return new AllOfRecordTypeGenerator(schemaValue, typeName); -// } else { -// return new UnionTypeGenerator(schemaValue, typeName); -// } + } else if ((schemaValue.getProperties() != null && + (schemaValue.getOneOf() != null || schemaValue.getAllOf() != null || schemaValue.getAnyOf() != null))) { + if (schemaValue.getAllOf() != null) { + return new AllOfRecordTypeGenerator(schemaValue, typeName); + } else { + return new UnionTypeGenerator(schemaValue, typeName); + } //TODO: include mapschema here see openapi code } else if ((schemaValue.getType() != null && schemaValue.getType().equals(GeneratorConstants.OBJECT)) || schemaValue.getProperties() != null) { return new RecordTypeGenerator(schemaValue, typeName); -// } else if (schemaValue instanceof ArraySchema) { -// return new ArrayTypeGenerator(schemaValue, typeName, parentName); + } else if (schemaValue.getType().equals("array")) { + return new ArrayTypeGenerator(schemaValue, typeName, parentName); } else if (schemaValue.getType() != null && primitiveTypeList.contains(schemaValue.getType())) { return new PrimitiveTypeGenerator(schemaValue, typeName); } else { // when schemaValue.type == null @@ -127,7 +128,7 @@ public static TypeDescriptorNode getNullableType(AsyncApi25SchemaImpl schema, Ty TypeDescriptorNode nillableType = originalTypeDesc; boolean nullable = GeneratorMetaData.getInstance().isNullable(); if (schema.getExtensions() != null) { - if (schema.getExtensions().get("x-nullable").equals(true)) { + if (schema.getExtensions().get("x-nullable").equals(BooleanNode.TRUE)) { nillableType = createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); } } else if (nullable) { @@ -160,29 +161,29 @@ public static void updateRecordFieldList(List required, MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(schemaDocNodes); //Generate constraint annotation. - AnnotationNode constraintNode = generateConstraintNode(fieldSchema); - MetadataNode metadataNode; - boolean isConstraintSupport = - constraintNode != null && fieldSchema.getExtensions()!=null & fieldSchema. - getExtensions().get("x-nullable") != null || - (((fieldSchema.getProperties() != null && - (fieldSchema.getOneOf() != null || fieldSchema.getAllOf() != null || - fieldSchema.getAnyOf() != null))) && ( fieldSchema.getOneOf() != null || - fieldSchema.getAnyOf() != null)); - boolean nullable = GeneratorMetaData.getInstance().isNullable(); - if (nullable) { - constraintNode = null; - } else if (isConstraintSupport) { - outStream.printf("WARNING: constraints in the OpenAPI contract will be ignored for the " + - "field `%s`, as constraints are not supported on Ballerina union types%n", - fieldName.toString().trim()); - constraintNode = null; - } - if (constraintNode == null) { - metadataNode = createMetadataNode(documentationNode, createEmptyNodeList()); - } else { - metadataNode = createMetadataNode(documentationNode, createNodeList(constraintNode)); - } +// AnnotationNode constraintNode = generateConstraintNode(fieldSchema); +// MetadataNode metadataNode; +// boolean isConstraintSupport = +// constraintNode != null && fieldSchema.getExtensions()!=null & fieldSchema. +// getExtensions().get("x-nullable") != null || +// (((fieldSchema.getProperties() != null && +// (fieldSchema.getOneOf() != null || fieldSchema.getAllOf() != null || +// fieldSchema.getAnyOf() != null))) && ( fieldSchema.getOneOf() != null || +// fieldSchema.getAnyOf() != null)); +// boolean nullable = GeneratorMetaData.getInstance().isNullable(); +// if (nullable) { +// constraintNode = null; +// } else if (isConstraintSupport) { +// outStream.printf("WARNING: constraints in the OpenAPI contract will be ignored for the " + +// "field `%s`, as constraints are not supported on Ballerina union types%n", +// fieldName.toString().trim()); +// constraintNode = null; +// } +// if (constraintNode == null) { +// metadataNode = createMetadataNode(documentationNode, createEmptyNodeList()); +// } else { + MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(new ArrayList<>())); +// } if (required != null) { setRequiredFields(required, recordFieldList, field, fieldSchema, fieldName, fieldTypeName, metadataNode); diff --git a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java index 7c67bdb5f..6dd08b73c 100644 --- a/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java +++ b/asyncapi-core/src/main/java/io/ballerina/asyncapi/core/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java @@ -243,6 +243,8 @@ public List addRecordFields(List required, Set addRecordFields(List required, Set())); return createTypeDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, generateTypeDescriptorNode(), createToken(SEMICOLON_TOKEN)); diff --git a/asyncapi-core/src/main/java/module-info.java b/asyncapi-core/src/main/java/module-info.java index 630b4f92b..3d4df3536 100644 --- a/asyncapi-core/src/main/java/module-info.java +++ b/asyncapi-core/src/main/java/module-info.java @@ -40,5 +40,6 @@ exports io.ballerina.asyncapi.core.generators.asyncspec; // exports io.ballerina.asyncapi.core.generators.schema; exports io.ballerina.asyncapi.core.model; + exports io.ballerina.asyncapi.core.generators.schema; }