diff --git a/lib/codegen/codegen.dart b/lib/codegen/codegen.dart index 9f82b4c9..f62bc9c9 100644 --- a/lib/codegen/codegen.dart +++ b/lib/codegen/codegen.dart @@ -70,7 +70,7 @@ class Codegen { case CodegenLanguage.javaOkHttp: return JavaOkHttpCodeGen().getCode(rM); case CodegenLanguage.javaUnirest: - return JavaUnirestGen().getCode(rM, boundary); + return JavaUnirestGen().getCode(rM); case CodegenLanguage.juliaHttp: return JuliaHttpClientCodeGen().getCode(rM); case CodegenLanguage.kotlinOkHttp: diff --git a/lib/codegen/java/unirest.dart b/lib/codegen/java/unirest.dart index c5824ee1..4260f6b7 100644 --- a/lib/codegen/java/unirest.dart +++ b/lib/codegen/java/unirest.dart @@ -6,17 +6,16 @@ import 'package:apidash/models/models.dart' show RequestModel; import 'package:apidash/consts.dart'; class JavaUnirestGen { - final String kTemplateUnirestImports = ''' -import kong.unirest.core.*;\n + final String kStringUnirestImports = ''' +import kong.unirest.core.*; + '''; - final String kTemplateFileIoImports = ''' + final String kStringFileIoImports = ''' import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream;\n + '''; - final String kTemplateStart = ''' + final String kStringStart = ''' public class Main { public static void main(String[] args) { '''; @@ -26,7 +25,9 @@ public class Main { '''; final String kTemplateRequestBodyContent = ''' - final String requestBody = "{{body}}";\n + final String requestBody = """ +{{body}}"""; + '''; final String kTemplateRequestCreation = ''' @@ -38,10 +39,6 @@ public class Main { .header("{{name}}", "{{value}}")\n '''; - final String kTemplateContentType = ''' - .contentType("{{contentType}}")\n -'''; - final String kTemplateUrlQueryParam = ''' .queryString("{{name}}", "{{value}}")\n '''; @@ -54,23 +51,19 @@ public class Main { .field("{{name}}", new File("{{value}}"))\n '''; - final String kTemplateRequestBodySetup = ''' - .body(requestBody)\n + final String kStringRequestBodySetup = ''' + .body(requestBody) '''; - final String kTemplateBoundarySetup = ''' - .boundary("{{boundary}}")\n -'''; - - final String kTemplateRequestEnd = """ + final String kStringRequestEnd = """ .asJson(); System.out.println(response.getStatus()); System.out.println(response.getBody()); } -}\n +} """; - String? getCode(RequestModel requestModel, String? boundary) { + String? getCode(RequestModel requestModel) { try { String result = ''; bool hasBody = false; @@ -88,103 +81,51 @@ public class Main { } // this is the common import and will be imported for every generated code snippet - result += kTemplateUnirestImports; + result += kStringUnirestImports; // java file io packages are to be imported only when there is a form with file present - if (requestModel.hasBody && - kMethodsWithBody.contains(requestModel.method) && - requestModel.hasFormData && - requestModel.hasFileInFormData) { - result += kTemplateFileIoImports; + if (requestModel.hasFormData && requestModel.hasFileInFormData) { + result += kStringFileIoImports; } // adding the main method under Main class - result += kTemplateStart; + result += kStringStart; var url = stripUriParams(uri); - // contains the HTTP method associated with the request - var method = requestModel.method; - - // contains the entire request body as a string if body is present - var requestBody = requestModel.requestBody; - // generating the URL to which the request has to be submitted var templateUrl = jj.Template(kTemplateUrl); result += templateUrl.render({"url": url}); - // creating request body if available - var rM = requestModel.copyWith(url: url); - var harJson = requestModelToHARJsonRequest(rM, useEnabled: true); - // if request type is not form data, the request method can include // a body, and the body of the request is not null, in that case // we need to parse the body as it is, and write it to the body - if (!requestModel.hasFormData && - kMethodsWithBody.contains(method) && - requestBody != null) { - // find out the content length for the request, i.e. request body's size - var contentLength = utf8.encode(requestBody).length; - if (contentLength > 0) { - var templateBodyContent = jj.Template(kTemplateRequestBodyContent); - hasBody = true; - if (harJson["postData"]?["text"] != null) { - result += templateBodyContent.render({ - "body": kEncoder.convert(harJson["postData"]["text"]).substring( - 1, kEncoder.convert(harJson["postData"]["text"]).length - 1) - }); - } - } + if (requestModel.hasTextData || requestModel.hasJsonData) { + var templateBodyContent = jj.Template(kTemplateRequestBodyContent); + result += templateBodyContent.render({ + "body": requestModel.requestBody, + }); + hasBody = true; } var templateRequestCreation = jj.Template(kTemplateRequestCreation); - result += - templateRequestCreation.render({"method": method.name.toLowerCase()}); + result += templateRequestCreation + .render({"method": requestModel.method.name.toLowerCase()}); // ~~~~~~~~~~~~~~~~~~ request header start ~~~~~~~~~~~~~~~~~~ - var m = <String, String>{}; - for (var i in harJson["headers"]) { - m[i["name"]] = i["value"]; - } - - // especially sets up Content-Type header if the request has a body - // and Content-Type is not explicitely set by the developer - if (requestModel.hasBody && - requestModel.hasFormData && - !requestModel.hasFileInFormData) { - m["Content-Type"] = "application/x-www-form-urlencoded"; - } - - // we will use this request boundary to set boundary if multipart formdata is used - String requestBoundary = ""; - String multipartTypePrefix = "multipart/form-data; boundary="; - if (m.containsKey("Content-Type") && - m["Content-Type"] != null && - m["Content-Type"]!.startsWith(RegExp(multipartTypePrefix))) { - String tmp = m["Content-Type"]!; - requestBoundary = tmp.substring(multipartTypePrefix.length); - - // if a boundary is provided, we will use that as the default boundary - if (boundary != null) { - requestBoundary = boundary; - m["Content-Type"] = multipartTypePrefix + boundary; - } + var headers = requestModel.enabledHeadersMap; + if (hasBody && !requestModel.hasContentTypeHeader) { + headers[kHeaderContentType] = + requestModel.requestBodyContentType.header; } var templateRequestHeader = jj.Template(kTemplateRequestHeader); - // setting up rest of the request headers - m.forEach((name, value) { + headers.forEach((name, value) { result += templateRequestHeader.render({"name": name, "value": value}); }); - // if (hasBody && !m.containsKey("Content-Type")) { - // var templateContentType = jj.Template(kTemplateContentType); - // result += templateContentType.render( - // {"contentType": requestModel.requestBodyContentType.header}); - // } - // ~~~~~~~~~~~~~~~~~~ request header ends ~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~ query parameters start ~~~~~~~~~~~~~~~~~~ @@ -201,47 +142,28 @@ public class Main { // ~~~~~~~~~~~~~~~~~~ query parameters end ~~~~~~~~~~~~~~~~~~ // handling form data - if (requestModel.hasFormData && - requestModel.formDataMapList.isNotEmpty && - kMethodsWithBody.contains(method)) { + if (requestModel.hasFormData) { // including form data into the request - var formDataList = requestModel.formDataMapList; var templateRequestTextFormData = jj.Template(kTemplateRequestTextFormData); var templateRequestFileFormData = jj.Template(kTemplateRequestFileFormData); - for (var formDataMap in formDataList) { - if (formDataMap["type"] == "text") { - result += templateRequestTextFormData.render({ - "name": formDataMap['name'], // - "value": formDataMap['value'] // - }); - } else if (formDataMap["type"] == "file") { - result += templateRequestFileFormData.render({ - "name": formDataMap['name'], // - "value": formDataMap['value'] // - }); + for (var field in requestModel.formDataList) { + if (field.type == FormDataType.text) { + result += templateRequestTextFormData + .render({"name": field.name, "value": field.value}); + } else if (field.type == FormDataType.file) { + result += templateRequestFileFormData + .render({"name": field.name, "value": field.value}); } } - - if (requestModel.hasFileInFormData) { - var templateBoundarySetup = jj.Template(kTemplateBoundarySetup); - result += templateBoundarySetup.render({"boundary": requestBoundary}); - } - - hasBody = true; } - var templateRequestBodySetup = jj.Template(kTemplateRequestBodySetup); - if (kMethodsWithBody.contains(method) && - hasBody && - !requestModel.hasFormData) { - result += templateRequestBodySetup.render(); + if (hasBody) { + result += kStringRequestBodySetup; } - var templateRequestBodyEnd = jj.Template(kTemplateRequestEnd); - result += templateRequestBodyEnd.render(); - + result += kStringRequestEnd; return result; } catch (e) { return null; diff --git a/test/codegen/java_unirest_codegen_test.dart b/test/codegen/java_unirest_codegen_test.dart index f760156a..c3022ecb 100644 --- a/test/codegen/java_unirest_codegen_test.dart +++ b/test/codegen/java_unirest_codegen_test.dart @@ -313,12 +313,15 @@ public class Main { group('POST Request', () { test('POST 1', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/case/lower"; - final String requestBody = "{\n\"text\": \"I LOVE Flutter\"\n}"; + final String requestBody = """ +{ +"text": "I LOVE Flutter" +}"""; HttpResponse<JsonNode> response = Unirest .post(requestURL) .header("Content-Type", "text/plain") @@ -328,7 +331,7 @@ public class Main { System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelPost1, "https"), @@ -336,12 +339,20 @@ public class Main { }); test('POST 2', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/case/lower"; - final String requestBody = "{\n\"text\": \"I LOVE Flutter\",\n\"flag\": null,\n\"male\": true,\n\"female\": false,\n\"no\": 1.2,\n\"arr\": [\"null\", \"true\", \"false\", null]\n}"; + final String requestBody = """ +{ +"text": "I LOVE Flutter", +"flag": null, +"male": true, +"female": false, +"no": 1.2, +"arr": ["null", "true", "false", null] +}"""; HttpResponse<JsonNode> response = Unirest .post(requestURL) .header("Content-Type", "application/json") @@ -351,7 +362,7 @@ public class Main { System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelPost2, "https"), @@ -359,23 +370,26 @@ public class Main { }); test('POST 3', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/case/lower"; - final String requestBody = "{\n\"text\": \"I LOVE Flutter\"\n}"; + final String requestBody = """ +{ +"text": "I LOVE Flutter" +}"""; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "application/json") .header("User-Agent", "Test Agent") + .header("Content-Type", "application/json") .body(requestBody) .asJson(); System.out.println(response.getStatus()); System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelPost3, "https"), @@ -389,7 +403,6 @@ public class Main { final String requestURL = "https://api.apidash.dev/io/form"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "application/x-www-form-urlencoded") .field("text", "API") .field("sep", "|") .field("times", "3") @@ -416,7 +429,6 @@ public class Main { final String requestURL = "https://api.apidash.dev/io/form"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "application/x-www-form-urlencoded") .header("User-Agent", "Test Agent") .field("text", "API") .field("sep", "|") @@ -439,19 +451,14 @@ public class Main { const expectedCode = r"""import kong.unirest.core.*; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/io/img"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "multipart/form-data; boundary=9b0411e0-aac7-1f25-8ba0-9f99ae8c34fc") .field("token", "xyz") .field("imfile", new File("/Documents/up/1.png")) - .boundary("9b0411e0-aac7-1f25-8ba0-9f99ae8c34fc") .asJson(); System.out.println(response.getStatus()); System.out.println(response.getBody()); @@ -460,27 +467,21 @@ public class Main { """; expect( codeGen.getCode( - CodegenLanguage.javaUnirest, requestModelPost6, "https", - boundary: "9b0411e0-aac7-1f25-8ba0-9f99ae8c34fc"), + CodegenLanguage.javaUnirest, requestModelPost6, "https"), expectedCode); }); test('POST 7', () { const expectedCode = r"""import kong.unirest.core.*; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/io/img"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "multipart/form-data; boundary=ef90cc20-c166-1f25-b663-29f0c584d89a") .field("token", "xyz") .field("imfile", new File("/Documents/up/1.png")) - .boundary("ef90cc20-c166-1f25-b663-29f0c584d89a") .asJson(); System.out.println(response.getStatus()); System.out.println(response.getBody()); @@ -489,8 +490,7 @@ public class Main { """; expect( codeGen.getCode( - CodegenLanguage.javaUnirest, requestModelPost7, "https", - boundary: "ef90cc20-c166-1f25-b663-29f0c584d89a"), + CodegenLanguage.javaUnirest, requestModelPost7, "https"), expectedCode); }); test('POST 8', () { @@ -501,7 +501,6 @@ public class Main { final String requestURL = "https://api.apidash.dev/io/form"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "application/x-www-form-urlencoded") .queryString("size", "2") .queryString("len", "3") .field("text", "API") @@ -525,23 +524,18 @@ public class Main { const expectedCode = r"""import kong.unirest.core.*; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; public class Main { public static void main(String[] args) { final String requestURL = "https://api.apidash.dev/io/img"; HttpResponse<JsonNode> response = Unirest .post(requestURL) - .header("Content-Type", "multipart/form-data; boundary=62bd1880-c57b-1f25-b663-29f0c584d89a") .header("User-Agent", "Test Agent") .header("Keep-Alive", "true") .queryString("size", "2") .queryString("len", "3") .field("token", "xyz") .field("imfile", new File("/Documents/up/1.png")) - .boundary("62bd1880-c57b-1f25-b663-29f0c584d89a") .asJson(); System.out.println(response.getStatus()); System.out.println(response.getBody()); @@ -550,23 +544,23 @@ public class Main { """; expect( codeGen.getCode( - CodegenLanguage.javaUnirest, - requestModelPost9, - "https", - boundary: "62bd1880-c57b-1f25-b663-29f0c584d89a", - ), + CodegenLanguage.javaUnirest, requestModelPost9, "https"), expectedCode); }); }); group('PUT Request', () { test('PUT 1', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://reqres.in/api/users/2"; - final String requestBody = "{\n\"name\": \"morpheus\",\n\"job\": \"zion resident\"\n}"; + final String requestBody = """ +{ +"name": "morpheus", +"job": "zion resident" +}"""; HttpResponse<JsonNode> response = Unirest .put(requestURL) .header("Content-Type", "application/json") @@ -576,7 +570,7 @@ public class Main { System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelPut1, "https"), @@ -586,12 +580,16 @@ public class Main { group('PATCH Request', () { test('PATCH 1', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://reqres.in/api/users/2"; - final String requestBody = "{\n\"name\": \"marfeus\",\n\"job\": \"accountant\"\n}"; + final String requestBody = """ +{ +"name": "marfeus", +"job": "accountant" +}"""; HttpResponse<JsonNode> response = Unirest .patch(requestURL) .header("Content-Type", "application/json") @@ -601,7 +599,7 @@ public class Main { System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelPatch1, "https"), @@ -631,12 +629,16 @@ public class Main { }); test('DELETE 2', () { - const expectedCode = r"""import kong.unirest.core.*; + const expectedCode = r'''import kong.unirest.core.*; public class Main { public static void main(String[] args) { final String requestURL = "https://reqres.in/api/users/2"; - final String requestBody = "{\n\"name\": \"marfeus\",\n\"job\": \"accountant\"\n}"; + final String requestBody = """ +{ +"name": "marfeus", +"job": "accountant" +}"""; HttpResponse<JsonNode> response = Unirest .delete(requestURL) .header("Content-Type", "application/json") @@ -646,7 +648,7 @@ public class Main { System.out.println(response.getBody()); } } -"""; +'''; expect( codeGen.getCode( CodegenLanguage.javaUnirest, requestModelDelete2, "https"),